bookmarks.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. import { SupportedAction, SupportedTargetModel } from '~/interfaces/activity';
  2. import { generateAddActivityMiddleware } from '~/server/middlewares/add-activity';
  3. import { serializeBookmarkSecurely } from '~/server/models/serializers/bookmark-serializer';
  4. import { preNotifyService } from '~/server/service/pre-notify';
  5. import loggerFactory from '~/utils/logger';
  6. import { apiV3FormValidator } from '../../middlewares/apiv3-form-validator';
  7. import BookmarkFolder from '../../models/bookmark-folder';
  8. const logger = loggerFactory('growi:routes:apiv3:bookmarks'); // eslint-disable-line no-unused-vars
  9. const express = require('express');
  10. const { body, query, param } = require('express-validator');
  11. const { serializeUserSecurely } = require('../../models/serializers/user-serializer');
  12. const router = express.Router();
  13. /**
  14. * @swagger
  15. * tags:
  16. * name: Bookmarks
  17. */
  18. /**
  19. * @swagger
  20. *
  21. * components:
  22. * schemas:
  23. * Bookmark:
  24. * description: Bookmark
  25. * type: object
  26. * properties:
  27. * _id:
  28. * type: string
  29. * description: page ID
  30. * example: 5e07345972560e001761fa63
  31. * __v:
  32. * type: number
  33. * description: DB record version
  34. * example: 0
  35. * createdAt:
  36. * type: string
  37. * description: date created at
  38. * example: 2010-01-01T00:00:00.000Z
  39. * page:
  40. * $ref: '#/components/schemas/Page/properties/_id'
  41. * user:
  42. * $ref: '#/components/schemas/User/properties/_id'
  43. *
  44. * BookmarkParams:
  45. * description: BookmarkParams
  46. * type: object
  47. * properties:
  48. * pageId:
  49. * type: string
  50. * description: page ID
  51. * example: 5e07345972560e001761fa63
  52. * bool:
  53. * type: boolean
  54. * description: boolean for bookmark status
  55. *
  56. * BookmarkInfo:
  57. * description: BookmarkInfo
  58. * type: object
  59. * properties:
  60. * sumOfBookmarks:
  61. * type: number
  62. * description: how many people bookmarked the page
  63. * isBookmarked:
  64. * type: boolean
  65. * description: Whether the request user bookmarked (will be returned if the user is included in the request)
  66. */
  67. module.exports = (crowi) => {
  68. const accessTokenParser = require('../../middlewares/access-token-parser')(crowi);
  69. const loginRequiredStrictly = require('../../middlewares/login-required')(crowi);
  70. const loginRequired = require('../../middlewares/login-required')(crowi, true);
  71. const addActivity = generateAddActivityMiddleware(crowi);
  72. const activityEvent = crowi.event('activity');
  73. const { Page, Bookmark } = crowi.models;
  74. const validator = {
  75. bookmarks: [
  76. body('pageId').isString(),
  77. body('bool').isBoolean(),
  78. ],
  79. bookmarkInfo: [
  80. query('pageId').isMongoId(),
  81. ],
  82. };
  83. /**
  84. * @swagger
  85. *
  86. * /bookmarks/info:
  87. * get:
  88. * tags: [Bookmarks]
  89. * summary: /bookmarks/info
  90. * description: Get bookmarked info
  91. * operationId: getBookmarkedInfo
  92. * parameters:
  93. * - name: pageId
  94. * in: query
  95. * description: page id
  96. * schema:
  97. * type: string
  98. * responses:
  99. * 200:
  100. * description: Succeeded to get bookmark info.
  101. * content:
  102. * application/json:
  103. * schema:
  104. * $ref: '#/components/schemas/BookmarkInfo'
  105. */
  106. router.get('/info', accessTokenParser, loginRequired, validator.bookmarkInfo, apiV3FormValidator, async(req, res) => {
  107. const { user } = req;
  108. const { pageId } = req.query;
  109. const responsesParams = {};
  110. try {
  111. const bookmarks = await Bookmark.find({ page: pageId }).populate('user');
  112. let users = [];
  113. if (bookmarks.length > 0) {
  114. users = bookmarks.map(bookmark => serializeUserSecurely(bookmark.user));
  115. }
  116. responsesParams.sumOfBookmarks = bookmarks.length;
  117. responsesParams.bookmarkedUsers = users;
  118. responsesParams.pageId = pageId;
  119. }
  120. catch (err) {
  121. logger.error('get-bookmark-document-failed', err);
  122. return res.apiv3Err(err, 500);
  123. }
  124. // guest user only get bookmark count
  125. if (user == null) {
  126. return res.apiv3(responsesParams);
  127. }
  128. try {
  129. const bookmark = await Bookmark.findByPageIdAndUserId(pageId, user._id);
  130. responsesParams.isBookmarked = (bookmark != null);
  131. return res.apiv3(responsesParams);
  132. }
  133. catch (err) {
  134. logger.error('get-bookmark-state-failed', err);
  135. return res.apiv3Err(err, 500);
  136. }
  137. });
  138. // select page from bookmark where userid = userid
  139. /**
  140. * @swagger
  141. *
  142. * /bookmarks/{userId}:
  143. * get:
  144. * tags: [Bookmarks]
  145. * summary: /bookmarks/{userId}
  146. * description: Get my bookmarked status
  147. * operationId: getMyBookmarkedStatus
  148. * parameters:
  149. * - name: userId
  150. * in: path
  151. * required: true
  152. * description: user id
  153. * schema:
  154. * type: string
  155. * - name: page
  156. * in: query
  157. * description: selected page number
  158. * schema:
  159. * type: number
  160. * - name: limit
  161. * in: query
  162. * description: page item limit
  163. * schema:
  164. * type: number
  165. * - name: offset
  166. * in: query
  167. * description: page item offset
  168. * schema:
  169. * type: number
  170. * responses:
  171. * 200:
  172. * description: Succeeded to get my bookmarked status.
  173. * content:
  174. * application/json:
  175. * schema:
  176. * $ref: '#/components/schemas/Bookmark'
  177. */
  178. validator.userBookmarkList = [
  179. param('userId').isMongoId().withMessage('userId is required'),
  180. ];
  181. router.get('/:userId', accessTokenParser, loginRequired, validator.userBookmarkList, apiV3FormValidator, async(req, res) => {
  182. const { userId } = req.params;
  183. if (userId == null) {
  184. return res.apiv3Err('User id is not found or forbidden', 400);
  185. }
  186. try {
  187. const bookmarkIdsInFolders = await BookmarkFolder.distinct('bookmarks', { owner: userId });
  188. const userRootBookmarks = await Bookmark.find({
  189. _id: { $nin: bookmarkIdsInFolders },
  190. user: userId,
  191. }).populate({
  192. path: 'page',
  193. model: 'Page',
  194. populate: {
  195. path: 'lastUpdateUser',
  196. model: 'User',
  197. },
  198. }).exec();
  199. // serialize Bookmark
  200. const serializedUserRootBookmarks = userRootBookmarks.map(bookmark => serializeBookmarkSecurely(bookmark));
  201. return res.apiv3({ userRootBookmarks: serializedUserRootBookmarks });
  202. }
  203. catch (err) {
  204. logger.error('get-bookmark-failed', err);
  205. return res.apiv3Err(err, 500);
  206. }
  207. });
  208. /**
  209. * @swagger
  210. *
  211. * /bookmarks:
  212. * put:
  213. * tags: [Bookmarks]
  214. * summary: /bookmarks
  215. * description: Update bookmarked status
  216. * operationId: updateBookmarkedStatus
  217. * requestBody:
  218. * content:
  219. * application/json:
  220. * schema:
  221. * $ref: '#/components/schemas/BookmarkParams'
  222. * responses:
  223. * 200:
  224. * description: Succeeded to update bookmarked status.
  225. * content:
  226. * application/json:
  227. * schema:
  228. * $ref: '#/components/schemas/Bookmark'
  229. */
  230. router.put('/', accessTokenParser, loginRequiredStrictly, addActivity, validator.bookmarks, apiV3FormValidator, async(req, res) => {
  231. const { pageId, bool } = req.body;
  232. const userId = req.user?._id;
  233. if (userId == null) {
  234. return res.apiv3Err('A logged in user is required.');
  235. }
  236. let page;
  237. let bookmark;
  238. try {
  239. page = await Page.findByIdAndViewer(pageId, req.user);
  240. if (page == null) {
  241. return res.apiv3Err(`Page '${pageId}' is not found or forbidden`);
  242. }
  243. bookmark = await Bookmark.findByPageIdAndUserId(page._id, req.user._id);
  244. if (bookmark == null) {
  245. if (bool) {
  246. bookmark = await Bookmark.add(page, req.user);
  247. }
  248. else {
  249. logger.warn(`Removing the bookmark for ${page._id} by ${req.user._id} failed because the bookmark does not exist.`);
  250. }
  251. }
  252. else {
  253. // eslint-disable-next-line no-lonely-if
  254. if (bool) {
  255. logger.warn(`Adding the bookmark for ${page._id} by ${req.user._id} failed because the bookmark has already exist.`);
  256. }
  257. else {
  258. bookmark = await Bookmark.removeBookmark(page, req.user);
  259. }
  260. }
  261. }
  262. catch (err) {
  263. logger.error('update-bookmark-failed', err);
  264. return res.apiv3Err(err, 500);
  265. }
  266. if (bookmark != null) {
  267. bookmark.depopulate('page');
  268. bookmark.depopulate('user');
  269. }
  270. const parameters = {
  271. targetModel: SupportedTargetModel.MODEL_PAGE,
  272. target: page,
  273. action: bool ? SupportedAction.ACTION_PAGE_BOOKMARK : SupportedAction.ACTION_PAGE_UNBOOKMARK,
  274. };
  275. activityEvent.emit('update', res.locals.activity._id, parameters, page, preNotifyService.generatePreNotify);
  276. return res.apiv3({ bookmark });
  277. });
  278. return router;
  279. };