memo.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. package server
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "github.com/pkg/errors"
  10. "github.com/usememos/memos/api"
  11. "github.com/usememos/memos/common"
  12. "github.com/labstack/echo/v4"
  13. )
  14. func (s *Server) registerMemoRoutes(g *echo.Group) {
  15. g.POST("/memo", func(c echo.Context) error {
  16. ctx := c.Request().Context()
  17. userID, ok := c.Get(getUserIDContextKey()).(int)
  18. if !ok {
  19. return echo.NewHTTPError(http.StatusUnauthorized, "Missing user in session")
  20. }
  21. memoCreate := &api.MemoCreate{}
  22. if err := json.NewDecoder(c.Request().Body).Decode(memoCreate); err != nil {
  23. return echo.NewHTTPError(http.StatusBadRequest, "Malformatted post memo request").SetInternal(err)
  24. }
  25. if memoCreate.Visibility == "" {
  26. userMemoVisibilitySetting, err := s.Store.FindUserSetting(ctx, &api.UserSettingFind{
  27. UserID: userID,
  28. Key: api.UserSettingMemoVisibilityKey,
  29. })
  30. if err != nil {
  31. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find user setting").SetInternal(err)
  32. }
  33. if userMemoVisibilitySetting != nil {
  34. memoVisibility := api.Private
  35. err := json.Unmarshal([]byte(userMemoVisibilitySetting.Value), &memoVisibility)
  36. if err != nil {
  37. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to unmarshal user setting value").SetInternal(err)
  38. }
  39. memoCreate.Visibility = memoVisibility
  40. } else {
  41. // Private is the default memo visibility.
  42. memoCreate.Visibility = api.Private
  43. }
  44. }
  45. // Find system settings
  46. disablePublicMemosSystemSetting, err := s.Store.FindSystemSetting(ctx, &api.SystemSettingFind{
  47. Name: api.SystemSettingDisablePublicMemosName,
  48. })
  49. if err != nil && common.ErrorCode(err) != common.NotFound {
  50. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find system setting").SetInternal(err)
  51. }
  52. if disablePublicMemosSystemSetting != nil {
  53. disablePublicMemos := false
  54. err = json.Unmarshal([]byte(disablePublicMemosSystemSetting.Value), &disablePublicMemos)
  55. if err != nil {
  56. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to unmarshal system setting").SetInternal(err)
  57. }
  58. if disablePublicMemos {
  59. memoCreate.Visibility = api.Private
  60. }
  61. }
  62. if len(memoCreate.Content) > api.MaxContentLength {
  63. return echo.NewHTTPError(http.StatusBadRequest, "Content size overflow, up to 1MB").SetInternal(err)
  64. }
  65. memoCreate.CreatorID = userID
  66. memo, err := s.Store.CreateMemo(ctx, memoCreate)
  67. if err != nil {
  68. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create memo").SetInternal(err)
  69. }
  70. if err := s.createMemoCreateActivity(c, memo); err != nil {
  71. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create activity").SetInternal(err)
  72. }
  73. for _, resourceID := range memoCreate.ResourceIDList {
  74. if _, err := s.Store.UpsertMemoResource(ctx, &api.MemoResourceUpsert{
  75. MemoID: memo.ID,
  76. ResourceID: resourceID,
  77. }); err != nil {
  78. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to upsert memo resource").SetInternal(err)
  79. }
  80. }
  81. memo, err = s.Store.ComposeMemo(ctx, memo)
  82. if err != nil {
  83. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to compose memo").SetInternal(err)
  84. }
  85. return c.JSON(http.StatusOK, composeResponse(memo))
  86. })
  87. g.PATCH("/memo/:memoId", func(c echo.Context) error {
  88. ctx := c.Request().Context()
  89. userID, ok := c.Get(getUserIDContextKey()).(int)
  90. if !ok {
  91. return echo.NewHTTPError(http.StatusUnauthorized, "Missing user in session")
  92. }
  93. memoID, err := strconv.Atoi(c.Param("memoId"))
  94. if err != nil {
  95. return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("memoId"))).SetInternal(err)
  96. }
  97. memo, err := s.Store.FindMemo(ctx, &api.MemoFind{
  98. ID: &memoID,
  99. })
  100. if err != nil {
  101. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find memo").SetInternal(err)
  102. }
  103. if memo.CreatorID != userID {
  104. return echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized")
  105. }
  106. currentTs := time.Now().Unix()
  107. memoPatch := &api.MemoPatch{
  108. ID: memoID,
  109. UpdatedTs: &currentTs,
  110. }
  111. if err := json.NewDecoder(c.Request().Body).Decode(memoPatch); err != nil {
  112. return echo.NewHTTPError(http.StatusBadRequest, "Malformatted patch memo request").SetInternal(err)
  113. }
  114. if memoPatch.Content != nil && len(*memoPatch.Content) > api.MaxContentLength {
  115. return echo.NewHTTPError(http.StatusBadRequest, "Content size overflow, up to 1MB").SetInternal(err)
  116. }
  117. memo, err = s.Store.PatchMemo(ctx, memoPatch)
  118. if err != nil {
  119. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to patch memo").SetInternal(err)
  120. }
  121. for _, resourceID := range memoPatch.ResourceIDList {
  122. if _, err := s.Store.UpsertMemoResource(ctx, &api.MemoResourceUpsert{
  123. MemoID: memo.ID,
  124. ResourceID: resourceID,
  125. }); err != nil {
  126. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to upsert memo resource").SetInternal(err)
  127. }
  128. }
  129. memo, err = s.Store.ComposeMemo(ctx, memo)
  130. if err != nil {
  131. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to compose memo").SetInternal(err)
  132. }
  133. return c.JSON(http.StatusOK, composeResponse(memo))
  134. })
  135. g.GET("/memo", func(c echo.Context) error {
  136. ctx := c.Request().Context()
  137. memoFind := &api.MemoFind{}
  138. if userID, err := strconv.Atoi(c.QueryParam("creatorId")); err == nil {
  139. memoFind.CreatorID = &userID
  140. }
  141. currentUserID, ok := c.Get(getUserIDContextKey()).(int)
  142. if !ok {
  143. if memoFind.CreatorID == nil {
  144. return echo.NewHTTPError(http.StatusBadRequest, "Missing user id to find memo")
  145. }
  146. memoFind.VisibilityList = []api.Visibility{api.Public}
  147. } else {
  148. if memoFind.CreatorID == nil {
  149. memoFind.CreatorID = &currentUserID
  150. } else {
  151. memoFind.VisibilityList = []api.Visibility{api.Public, api.Protected}
  152. }
  153. }
  154. rowStatus := api.RowStatus(c.QueryParam("rowStatus"))
  155. if rowStatus != "" {
  156. memoFind.RowStatus = &rowStatus
  157. }
  158. pinnedStr := c.QueryParam("pinned")
  159. if pinnedStr != "" {
  160. pinned := pinnedStr == "true"
  161. memoFind.Pinned = &pinned
  162. }
  163. tag := c.QueryParam("tag")
  164. if tag != "" {
  165. contentSearch := "#" + tag
  166. memoFind.ContentSearch = &contentSearch
  167. }
  168. visibilityListStr := c.QueryParam("visibility")
  169. if visibilityListStr != "" {
  170. visibilityList := []api.Visibility{}
  171. for _, visibility := range strings.Split(visibilityListStr, ",") {
  172. visibilityList = append(visibilityList, api.Visibility(visibility))
  173. }
  174. memoFind.VisibilityList = visibilityList
  175. }
  176. if limit, err := strconv.Atoi(c.QueryParam("limit")); err == nil {
  177. memoFind.Limit = &limit
  178. }
  179. if offset, err := strconv.Atoi(c.QueryParam("offset")); err == nil {
  180. memoFind.Offset = &offset
  181. }
  182. list, err := s.Store.FindMemoList(ctx, memoFind)
  183. if err != nil {
  184. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch memo list").SetInternal(err)
  185. }
  186. return c.JSON(http.StatusOK, composeResponse(list))
  187. })
  188. g.GET("/memo/:memoId", func(c echo.Context) error {
  189. ctx := c.Request().Context()
  190. memoID, err := strconv.Atoi(c.Param("memoId"))
  191. if err != nil {
  192. return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("memoId"))).SetInternal(err)
  193. }
  194. memoFind := &api.MemoFind{
  195. ID: &memoID,
  196. }
  197. memo, err := s.Store.FindMemo(ctx, memoFind)
  198. if err != nil {
  199. if common.ErrorCode(err) == common.NotFound {
  200. return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Memo ID not found: %d", memoID)).SetInternal(err)
  201. }
  202. return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find memo by ID: %v", memoID)).SetInternal(err)
  203. }
  204. userID, ok := c.Get(getUserIDContextKey()).(int)
  205. if memo.Visibility == api.Private {
  206. if !ok || memo.CreatorID != userID {
  207. return echo.NewHTTPError(http.StatusForbidden, "this memo is private only")
  208. }
  209. } else if memo.Visibility == api.Protected {
  210. if !ok {
  211. return echo.NewHTTPError(http.StatusForbidden, "this memo is protected, missing user in session")
  212. }
  213. }
  214. return c.JSON(http.StatusOK, composeResponse(memo))
  215. })
  216. g.POST("/memo/:memoId/organizer", func(c echo.Context) error {
  217. ctx := c.Request().Context()
  218. memoID, err := strconv.Atoi(c.Param("memoId"))
  219. if err != nil {
  220. return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("memoId"))).SetInternal(err)
  221. }
  222. userID, ok := c.Get(getUserIDContextKey()).(int)
  223. if !ok {
  224. return echo.NewHTTPError(http.StatusUnauthorized, "Missing user in session")
  225. }
  226. memoOrganizerUpsert := &api.MemoOrganizerUpsert{}
  227. if err := json.NewDecoder(c.Request().Body).Decode(memoOrganizerUpsert); err != nil {
  228. return echo.NewHTTPError(http.StatusBadRequest, "Malformatted post memo organizer request").SetInternal(err)
  229. }
  230. memoOrganizerUpsert.MemoID = memoID
  231. memoOrganizerUpsert.UserID = userID
  232. err = s.Store.UpsertMemoOrganizer(ctx, memoOrganizerUpsert)
  233. if err != nil {
  234. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to upsert memo organizer").SetInternal(err)
  235. }
  236. memo, err := s.Store.FindMemo(ctx, &api.MemoFind{
  237. ID: &memoID,
  238. })
  239. if err != nil {
  240. if common.ErrorCode(err) == common.NotFound {
  241. return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Memo ID not found: %d", memoID)).SetInternal(err)
  242. }
  243. return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to find memo by ID: %v", memoID)).SetInternal(err)
  244. }
  245. return c.JSON(http.StatusOK, composeResponse(memo))
  246. })
  247. g.POST("/memo/:memoId/resource", func(c echo.Context) error {
  248. ctx := c.Request().Context()
  249. memoID, err := strconv.Atoi(c.Param("memoId"))
  250. if err != nil {
  251. return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("memoId"))).SetInternal(err)
  252. }
  253. userID, ok := c.Get(getUserIDContextKey()).(int)
  254. if !ok {
  255. return echo.NewHTTPError(http.StatusUnauthorized, "Missing user in session")
  256. }
  257. memoResourceUpsert := &api.MemoResourceUpsert{}
  258. if err := json.NewDecoder(c.Request().Body).Decode(memoResourceUpsert); err != nil {
  259. return echo.NewHTTPError(http.StatusBadRequest, "Malformatted post memo resource request").SetInternal(err)
  260. }
  261. resourceFind := &api.ResourceFind{
  262. ID: &memoResourceUpsert.ResourceID,
  263. }
  264. resource, err := s.Store.FindResource(ctx, resourceFind)
  265. if err != nil {
  266. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch resource").SetInternal(err)
  267. }
  268. if resource == nil {
  269. return echo.NewHTTPError(http.StatusBadRequest, "Resource not found").SetInternal(err)
  270. } else if resource.CreatorID != userID {
  271. return echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized to bind this resource").SetInternal(err)
  272. }
  273. memoResourceUpsert.MemoID = memoID
  274. currentTs := time.Now().Unix()
  275. memoResourceUpsert.UpdatedTs = &currentTs
  276. if _, err := s.Store.UpsertMemoResource(ctx, memoResourceUpsert); err != nil {
  277. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to upsert memo resource").SetInternal(err)
  278. }
  279. return c.JSON(http.StatusOK, composeResponse(resource))
  280. })
  281. g.GET("/memo/:memoId/resource", func(c echo.Context) error {
  282. ctx := c.Request().Context()
  283. memoID, err := strconv.Atoi(c.Param("memoId"))
  284. if err != nil {
  285. return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("memoId"))).SetInternal(err)
  286. }
  287. resourceFind := &api.ResourceFind{
  288. MemoID: &memoID,
  289. }
  290. resourceList, err := s.Store.FindResourceList(ctx, resourceFind)
  291. if err != nil {
  292. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch resource list").SetInternal(err)
  293. }
  294. return c.JSON(http.StatusOK, composeResponse(resourceList))
  295. })
  296. g.GET("/memo/stats", func(c echo.Context) error {
  297. ctx := c.Request().Context()
  298. normalStatus := api.Normal
  299. memoFind := &api.MemoFind{
  300. RowStatus: &normalStatus,
  301. }
  302. if creatorID, err := strconv.Atoi(c.QueryParam("creatorId")); err == nil {
  303. memoFind.CreatorID = &creatorID
  304. }
  305. if memoFind.CreatorID == nil {
  306. return echo.NewHTTPError(http.StatusBadRequest, "Missing user id to find memo")
  307. }
  308. currentUserID, ok := c.Get(getUserIDContextKey()).(int)
  309. if !ok {
  310. memoFind.VisibilityList = []api.Visibility{api.Public}
  311. } else {
  312. if *memoFind.CreatorID != currentUserID {
  313. memoFind.VisibilityList = []api.Visibility{api.Public, api.Protected}
  314. } else {
  315. memoFind.VisibilityList = []api.Visibility{api.Public, api.Protected, api.Private}
  316. }
  317. }
  318. list, err := s.Store.FindMemoList(ctx, memoFind)
  319. if err != nil {
  320. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch memo list").SetInternal(err)
  321. }
  322. createdTsList := []int64{}
  323. for _, memo := range list {
  324. createdTsList = append(createdTsList, memo.CreatedTs)
  325. }
  326. return c.JSON(http.StatusOK, composeResponse(createdTsList))
  327. })
  328. g.GET("/memo/all", func(c echo.Context) error {
  329. ctx := c.Request().Context()
  330. memoFind := &api.MemoFind{}
  331. _, ok := c.Get(getUserIDContextKey()).(int)
  332. if !ok {
  333. memoFind.VisibilityList = []api.Visibility{api.Public}
  334. } else {
  335. memoFind.VisibilityList = []api.Visibility{api.Public, api.Protected}
  336. }
  337. pinnedStr := c.QueryParam("pinned")
  338. if pinnedStr != "" {
  339. pinned := pinnedStr == "true"
  340. memoFind.Pinned = &pinned
  341. }
  342. tag := c.QueryParam("tag")
  343. if tag != "" {
  344. contentSearch := "#" + tag + " "
  345. memoFind.ContentSearch = &contentSearch
  346. }
  347. visibilityListStr := c.QueryParam("visibility")
  348. if visibilityListStr != "" {
  349. visibilityList := []api.Visibility{}
  350. for _, visibility := range strings.Split(visibilityListStr, ",") {
  351. visibilityList = append(visibilityList, api.Visibility(visibility))
  352. }
  353. memoFind.VisibilityList = visibilityList
  354. }
  355. if limit, err := strconv.Atoi(c.QueryParam("limit")); err == nil {
  356. memoFind.Limit = &limit
  357. }
  358. if offset, err := strconv.Atoi(c.QueryParam("offset")); err == nil {
  359. memoFind.Offset = &offset
  360. }
  361. // Only fetch normal status memos.
  362. normalStatus := api.Normal
  363. memoFind.RowStatus = &normalStatus
  364. list, err := s.Store.FindMemoList(ctx, memoFind)
  365. if err != nil {
  366. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch all memo list").SetInternal(err)
  367. }
  368. return c.JSON(http.StatusOK, composeResponse(list))
  369. })
  370. g.DELETE("/memo/:memoId", func(c echo.Context) error {
  371. ctx := c.Request().Context()
  372. userID, ok := c.Get(getUserIDContextKey()).(int)
  373. if !ok {
  374. return echo.NewHTTPError(http.StatusUnauthorized, "Missing user in session")
  375. }
  376. memoID, err := strconv.Atoi(c.Param("memoId"))
  377. if err != nil {
  378. return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("ID is not a number: %s", c.Param("memoId"))).SetInternal(err)
  379. }
  380. memo, err := s.Store.FindMemo(ctx, &api.MemoFind{
  381. ID: &memoID,
  382. })
  383. if err != nil {
  384. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find memo").SetInternal(err)
  385. }
  386. if memo.CreatorID != userID {
  387. return echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized")
  388. }
  389. memoDelete := &api.MemoDelete{
  390. ID: memoID,
  391. }
  392. if err := s.Store.DeleteMemo(ctx, memoDelete); err != nil {
  393. if common.ErrorCode(err) == common.NotFound {
  394. return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Memo ID not found: %d", memoID))
  395. }
  396. return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to delete memo ID: %v", memoID)).SetInternal(err)
  397. }
  398. return c.JSON(http.StatusOK, true)
  399. })
  400. g.DELETE("/memo/:memoId/resource/:resourceId", func(c echo.Context) error {
  401. ctx := c.Request().Context()
  402. userID, ok := c.Get(getUserIDContextKey()).(int)
  403. if !ok {
  404. return echo.NewHTTPError(http.StatusUnauthorized, "Missing user in session")
  405. }
  406. memoID, err := strconv.Atoi(c.Param("memoId"))
  407. if err != nil {
  408. return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Memo ID is not a number: %s", c.Param("memoId"))).SetInternal(err)
  409. }
  410. resourceID, err := strconv.Atoi(c.Param("resourceId"))
  411. if err != nil {
  412. return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Resource ID is not a number: %s", c.Param("resourceId"))).SetInternal(err)
  413. }
  414. memo, err := s.Store.FindMemo(ctx, &api.MemoFind{
  415. ID: &memoID,
  416. })
  417. if err != nil {
  418. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find memo").SetInternal(err)
  419. }
  420. if memo.CreatorID != userID {
  421. return echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized")
  422. }
  423. memoResourceDelete := &api.MemoResourceDelete{
  424. MemoID: &memoID,
  425. ResourceID: &resourceID,
  426. }
  427. if err := s.Store.DeleteMemoResource(ctx, memoResourceDelete); err != nil {
  428. return echo.NewHTTPError(http.StatusInternalServerError, "Failed to fetch resource list").SetInternal(err)
  429. }
  430. return c.JSON(http.StatusOK, true)
  431. })
  432. }
  433. func (s *Server) createMemoCreateActivity(c echo.Context, memo *api.Memo) error {
  434. ctx := c.Request().Context()
  435. payload := api.ActivityMemoCreatePayload{
  436. Content: memo.Content,
  437. Visibility: memo.Visibility.String(),
  438. }
  439. payloadBytes, err := json.Marshal(payload)
  440. if err != nil {
  441. return errors.Wrap(err, "failed to marshal activity payload")
  442. }
  443. activity, err := s.Store.CreateActivity(ctx, &api.ActivityCreate{
  444. CreatorID: memo.CreatorID,
  445. Type: api.ActivityMemoCreate,
  446. Level: api.ActivityInfo,
  447. Payload: string(payloadBytes),
  448. })
  449. if err != nil || activity == nil {
  450. return errors.Wrap(err, "failed to create activity")
  451. }
  452. return err
  453. }