123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507 |
- package server
- import (
- "encoding/json"
- "fmt"
- "net/http"
- "strconv"
- "strings"
- "time"
- "github.com/pkg/errors"
- "github.com/usememos/memos/api"
- "github.com/usememos/memos/common"
- "github.com/labstack/echo/v4"
- )
- func (s *Server) registerMemoRoutes(g *echo.Group) {
- g.POST("/memo", func(c echo.Context) error {
- ctx := c.Request().Context()
- userID, ok := c.Get(getUserIDContextKey()).(int)
- if !ok {
- return echo.NewHTTPError(http.StatusUnauthorized, "Missing user in session")
- }
- memoCreate := &api.MemoCreate{}
- if err := json.NewDecoder(c.Request().Body).Decode(memoCreate); err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, "Malformatted post memo request").SetInternal(err)
- }
- if memoCreate.Visibility == "" {
- userMemoVisibilitySetting, err := s.Store.FindUserSetting(ctx, &api.UserSettingFind{
- UserID: userID,
- Key: api.UserSettingMemoVisibilityKey,
- })
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find user setting").SetInternal(err)
- }
- if userMemoVisibilitySetting != nil {
- memoVisibility := api.Private
- err := json.Unmarshal([]byte(userMemoVisibilitySetting.Value), &memoVisibility)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to unmarshal user setting value").SetInternal(err)
- }
- memoCreate.Visibility = memoVisibility
- } else {
- // Private is the default memo visibility.
- memoCreate.Visibility = api.Private
- }
- }
- // Find system settings
- disablePublicMemosSystemSetting, err := s.Store.FindSystemSetting(ctx, &api.SystemSettingFind{
- Name: api.SystemSettingDisablePublicMemosName,
- })
- if err != nil && common.ErrorCode(err) != common.NotFound {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find system setting").SetInternal(err)
- }
- if disablePublicMemosSystemSetting != nil {
- disablePublicMemos := false
- err = json.Unmarshal([]byte(disablePublicMemosSystemSetting.Value), &disablePublicMemos)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to unmarshal system setting").SetInternal(err)
- }
- if disablePublicMemos {
- memoCreate.Visibility = api.Private
- }
- }
- if len(memoCreate.Content) > api.MaxContentLength {
- return echo.NewHTTPError(http.StatusBadRequest, "Content size overflow, up to 1MB").SetInternal(err)
- }
- memoCreate.CreatorID = userID
- memo, err := s.Store.CreateMemo(ctx, memoCreate)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create memo").SetInternal(err)
- }
- if err := s.createMemoCreateActivity(c, memo); err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create activity").SetInternal(err)
- }
- for _, resourceID := range memoCreate.ResourceIDList {
- if _, err := s.Store.UpsertMemoResource(ctx, &api.MemoResourceUpsert{
- MemoID: memo.ID,
- ResourceID: resourceID,
- }); err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to upsert memo resource").SetInternal(err)
- }
- }
- memo, err = s.Store.ComposeMemo(ctx, memo)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to compose memo").SetInternal(err)
- }
- return c.JSON(http.StatusOK, composeResponse(memo))
- })
- g.PATCH("/memo/:memoId", func(c echo.Context) error {
- ctx := c.Request().Context()
- userID, ok := c.Get(getUserIDContextKey()).(int)
- if !ok {
- return echo.NewHTTPError(http.StatusUnauthorized, "Missing user in session")
- }
- memoID, err := strconv.Atoi(c.Param("memoId"))
- if err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("memoId"))).SetInternal(err)
- }
- memo, err := s.Store.FindMemo(ctx, &api.MemoFind{
- ID: &memoID,
- })
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find memo").SetInternal(err)
- }
- if memo.CreatorID != userID {
- return echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized")
- }
- currentTs := time.Now().Unix()
- memoPatch := &api.MemoPatch{
- ID: memoID,
- UpdatedTs: ¤tTs,
- }
- if err := json.NewDecoder(c.Request().Body).Decode(memoPatch); err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, "Malformatted patch memo request").SetInternal(err)
- }
- if memoPatch.Content != nil && len(*memoPatch.Content) > api.MaxContentLength {
- return echo.NewHTTPError(http.StatusBadRequest, "Content size overflow, up to 1MB").SetInternal(err)
- }
- memo, err = s.Store.PatchMemo(ctx, memoPatch)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to patch memo").SetInternal(err)
- }
- for _, resourceID := range memoPatch.ResourceIDList {
- if _, err := s.Store.UpsertMemoResource(ctx, &api.MemoResourceUpsert{
- MemoID: memo.ID,
- ResourceID: resourceID,
- }); err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to upsert memo resource").SetInternal(err)
- }
- }
- memo, err = s.Store.ComposeMemo(ctx, memo)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to compose memo").SetInternal(err)
- }
- return c.JSON(http.StatusOK, composeResponse(memo))
- })
- g.GET("/memo", func(c echo.Context) error {
- ctx := c.Request().Context()
- memoFind := &api.MemoFind{}
- if userID, err := strconv.Atoi(c.QueryParam("creatorId")); err == nil {
- memoFind.CreatorID = &userID
- }
- currentUserID, ok := c.Get(getUserIDContextKey()).(int)
- if !ok {
- if memoFind.CreatorID == nil {
- return echo.NewHTTPError(http.StatusBadRequest, "Missing user id to find memo")
- }
- memoFind.VisibilityList = []api.Visibility{api.Public}
- } else {
- if memoFind.CreatorID == nil {
- memoFind.CreatorID = ¤tUserID
- } else {
- memoFind.VisibilityList = []api.Visibility{api.Public, api.Protected}
- }
- }
- rowStatus := api.RowStatus(c.QueryParam("rowStatus"))
- if rowStatus != "" {
- memoFind.RowStatus = &rowStatus
- }
- pinnedStr := c.QueryParam("pinned")
- if pinnedStr != "" {
- pinned := pinnedStr == "true"
- memoFind.Pinned = &pinned
- }
- tag := c.QueryParam("tag")
- if tag != "" {
- contentSearch := "#" + tag
- memoFind.ContentSearch = &contentSearch
- }
- visibilityListStr := c.QueryParam("visibility")
- if visibilityListStr != "" {
- visibilityList := []api.Visibility{}
- for _, visibility := range strings.Split(visibilityListStr, ",") {
- visibilityList = append(visibilityList, api.Visibility(visibility))
- }
- memoFind.VisibilityList = visibilityList
- }
- if limit, err := strconv.Atoi(c.QueryParam("limit")); err == nil {
- memoFind.Limit = &limit
- }
- if offset, err := strconv.Atoi(c.QueryParam("offset")); err == nil {
- memoFind.Offset = &offset
- }
- list, err := s.Store.FindMemoList(ctx, memoFind)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch memo list").SetInternal(err)
- }
- return c.JSON(http.StatusOK, composeResponse(list))
- })
- g.GET("/memo/:memoId", func(c echo.Context) error {
- ctx := c.Request().Context()
- memoID, err := strconv.Atoi(c.Param("memoId"))
- if err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("memoId"))).SetInternal(err)
- }
- memoFind := &api.MemoFind{
- ID: &memoID,
- }
- memo, err := s.Store.FindMemo(ctx, memoFind)
- if err != nil {
- if common.ErrorCode(err) == common.NotFound {
- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Memo ID not found: %d", memoID)).SetInternal(err)
- }
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find memo by ID: %v", memoID)).SetInternal(err)
- }
- userID, ok := c.Get(getUserIDContextKey()).(int)
- if memo.Visibility == api.Private {
- if !ok || memo.CreatorID != userID {
- return echo.NewHTTPError(http.StatusForbidden, "this memo is private only")
- }
- } else if memo.Visibility == api.Protected {
- if !ok {
- return echo.NewHTTPError(http.StatusForbidden, "this memo is protected, missing user in session")
- }
- }
- return c.JSON(http.StatusOK, composeResponse(memo))
- })
- g.POST("/memo/:memoId/organizer", func(c echo.Context) error {
- ctx := c.Request().Context()
- memoID, err := strconv.Atoi(c.Param("memoId"))
- if err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("memoId"))).SetInternal(err)
- }
- userID, ok := c.Get(getUserIDContextKey()).(int)
- if !ok {
- return echo.NewHTTPError(http.StatusUnauthorized, "Missing user in session")
- }
- memoOrganizerUpsert := &api.MemoOrganizerUpsert{}
- if err := json.NewDecoder(c.Request().Body).Decode(memoOrganizerUpsert); err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, "Malformatted post memo organizer request").SetInternal(err)
- }
- memoOrganizerUpsert.MemoID = memoID
- memoOrganizerUpsert.UserID = userID
- err = s.Store.UpsertMemoOrganizer(ctx, memoOrganizerUpsert)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to upsert memo organizer").SetInternal(err)
- }
- memo, err := s.Store.FindMemo(ctx, &api.MemoFind{
- ID: &memoID,
- })
- if err != nil {
- if common.ErrorCode(err) == common.NotFound {
- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Memo ID not found: %d", memoID)).SetInternal(err)
- }
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find memo by ID: %v", memoID)).SetInternal(err)
- }
- return c.JSON(http.StatusOK, composeResponse(memo))
- })
- g.POST("/memo/:memoId/resource", func(c echo.Context) error {
- ctx := c.Request().Context()
- memoID, err := strconv.Atoi(c.Param("memoId"))
- if err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("memoId"))).SetInternal(err)
- }
- userID, ok := c.Get(getUserIDContextKey()).(int)
- if !ok {
- return echo.NewHTTPError(http.StatusUnauthorized, "Missing user in session")
- }
- memoResourceUpsert := &api.MemoResourceUpsert{}
- if err := json.NewDecoder(c.Request().Body).Decode(memoResourceUpsert); err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, "Malformatted post memo resource request").SetInternal(err)
- }
- resourceFind := &api.ResourceFind{
- ID: &memoResourceUpsert.ResourceID,
- }
- resource, err := s.Store.FindResource(ctx, resourceFind)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch resource").SetInternal(err)
- }
- if resource == nil {
- return echo.NewHTTPError(http.StatusBadRequest, "Resource not found").SetInternal(err)
- } else if resource.CreatorID != userID {
- return echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized to bind this resource").SetInternal(err)
- }
- memoResourceUpsert.MemoID = memoID
- currentTs := time.Now().Unix()
- memoResourceUpsert.UpdatedTs = ¤tTs
- if _, err := s.Store.UpsertMemoResource(ctx, memoResourceUpsert); err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to upsert memo resource").SetInternal(err)
- }
- return c.JSON(http.StatusOK, composeResponse(resource))
- })
- g.GET("/memo/:memoId/resource", func(c echo.Context) error {
- ctx := c.Request().Context()
- memoID, err := strconv.Atoi(c.Param("memoId"))
- if err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("memoId"))).SetInternal(err)
- }
- resourceFind := &api.ResourceFind{
- MemoID: &memoID,
- }
- resourceList, err := s.Store.FindResourceList(ctx, resourceFind)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch resource list").SetInternal(err)
- }
- return c.JSON(http.StatusOK, composeResponse(resourceList))
- })
- g.GET("/memo/stats", func(c echo.Context) error {
- ctx := c.Request().Context()
- normalStatus := api.Normal
- memoFind := &api.MemoFind{
- RowStatus: &normalStatus,
- }
- if creatorID, err := strconv.Atoi(c.QueryParam("creatorId")); err == nil {
- memoFind.CreatorID = &creatorID
- }
- if memoFind.CreatorID == nil {
- return echo.NewHTTPError(http.StatusBadRequest, "Missing user id to find memo")
- }
- currentUserID, ok := c.Get(getUserIDContextKey()).(int)
- if !ok {
- memoFind.VisibilityList = []api.Visibility{api.Public}
- } else {
- if *memoFind.CreatorID != currentUserID {
- memoFind.VisibilityList = []api.Visibility{api.Public, api.Protected}
- } else {
- memoFind.VisibilityList = []api.Visibility{api.Public, api.Protected, api.Private}
- }
- }
- list, err := s.Store.FindMemoList(ctx, memoFind)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch memo list").SetInternal(err)
- }
- createdTsList := []int64{}
- for _, memo := range list {
- createdTsList = append(createdTsList, memo.CreatedTs)
- }
- return c.JSON(http.StatusOK, composeResponse(createdTsList))
- })
- g.GET("/memo/all", func(c echo.Context) error {
- ctx := c.Request().Context()
- memoFind := &api.MemoFind{}
- _, ok := c.Get(getUserIDContextKey()).(int)
- if !ok {
- memoFind.VisibilityList = []api.Visibility{api.Public}
- } else {
- memoFind.VisibilityList = []api.Visibility{api.Public, api.Protected}
- }
- pinnedStr := c.QueryParam("pinned")
- if pinnedStr != "" {
- pinned := pinnedStr == "true"
- memoFind.Pinned = &pinned
- }
- tag := c.QueryParam("tag")
- if tag != "" {
- contentSearch := "#" + tag + " "
- memoFind.ContentSearch = &contentSearch
- }
- visibilityListStr := c.QueryParam("visibility")
- if visibilityListStr != "" {
- visibilityList := []api.Visibility{}
- for _, visibility := range strings.Split(visibilityListStr, ",") {
- visibilityList = append(visibilityList, api.Visibility(visibility))
- }
- memoFind.VisibilityList = visibilityList
- }
- if limit, err := strconv.Atoi(c.QueryParam("limit")); err == nil {
- memoFind.Limit = &limit
- }
- if offset, err := strconv.Atoi(c.QueryParam("offset")); err == nil {
- memoFind.Offset = &offset
- }
- // Only fetch normal status memos.
- normalStatus := api.Normal
- memoFind.RowStatus = &normalStatus
- list, err := s.Store.FindMemoList(ctx, memoFind)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch all memo list").SetInternal(err)
- }
- return c.JSON(http.StatusOK, composeResponse(list))
- })
- g.DELETE("/memo/:memoId", func(c echo.Context) error {
- ctx := c.Request().Context()
- userID, ok := c.Get(getUserIDContextKey()).(int)
- if !ok {
- return echo.NewHTTPError(http.StatusUnauthorized, "Missing user in session")
- }
- memoID, err := strconv.Atoi(c.Param("memoId"))
- if err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("memoId"))).SetInternal(err)
- }
- memo, err := s.Store.FindMemo(ctx, &api.MemoFind{
- ID: &memoID,
- })
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find memo").SetInternal(err)
- }
- if memo.CreatorID != userID {
- return echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized")
- }
- memoDelete := &api.MemoDelete{
- ID: memoID,
- }
- if err := s.Store.DeleteMemo(ctx, memoDelete); err != nil {
- if common.ErrorCode(err) == common.NotFound {
- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Memo ID not found: %d", memoID))
- }
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to delete memo ID: %v", memoID)).SetInternal(err)
- }
- return c.JSON(http.StatusOK, true)
- })
- g.DELETE("/memo/:memoId/resource/:resourceId", func(c echo.Context) error {
- ctx := c.Request().Context()
- userID, ok := c.Get(getUserIDContextKey()).(int)
- if !ok {
- return echo.NewHTTPError(http.StatusUnauthorized, "Missing user in session")
- }
- memoID, err := strconv.Atoi(c.Param("memoId"))
- if err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Memo ID is not a number: %s", c.Param("memoId"))).SetInternal(err)
- }
- resourceID, err := strconv.Atoi(c.Param("resourceId"))
- if err != nil {
- return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Resource ID is not a number: %s", c.Param("resourceId"))).SetInternal(err)
- }
- memo, err := s.Store.FindMemo(ctx, &api.MemoFind{
- ID: &memoID,
- })
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find memo").SetInternal(err)
- }
- if memo.CreatorID != userID {
- return echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized")
- }
- memoResourceDelete := &api.MemoResourceDelete{
- MemoID: &memoID,
- ResourceID: &resourceID,
- }
- if err := s.Store.DeleteMemoResource(ctx, memoResourceDelete); err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch resource list").SetInternal(err)
- }
- return c.JSON(http.StatusOK, true)
- })
- }
- func (s *Server) createMemoCreateActivity(c echo.Context, memo *api.Memo) error {
- ctx := c.Request().Context()
- payload := api.ActivityMemoCreatePayload{
- Content: memo.Content,
- Visibility: memo.Visibility.String(),
- }
- payloadBytes, err := json.Marshal(payload)
- if err != nil {
- return errors.Wrap(err, "failed to marshal activity payload")
- }
- activity, err := s.Store.CreateActivity(ctx, &api.ActivityCreate{
- CreatorID: memo.CreatorID,
- Type: api.ActivityMemoCreate,
- Level: api.ActivityInfo,
- Payload: string(payloadBytes),
- })
- if err != nil || activity == nil {
- return errors.Wrap(err, "failed to create activity")
- }
- return err
- }
|