page.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. const loggerFactory = require('@alias/logger');
  2. const logger = loggerFactory('growi:routes:apiv3:page'); // eslint-disable-line no-unused-vars
  3. const express = require('express');
  4. const { body, query } = require('express-validator');
  5. const router = express.Router();
  6. const ErrorV3 = require('../../models/vo/error-apiv3');
  7. /**
  8. * @swagger
  9. * tags:
  10. * name: Page
  11. */
  12. /**
  13. * @swagger
  14. *
  15. * components:
  16. * schemas:
  17. * Page:
  18. * description: Page
  19. * type: object
  20. * properties:
  21. * _id:
  22. * type: string
  23. * description: page ID
  24. * example: 5e07345972560e001761fa63
  25. * __v:
  26. * type: number
  27. * description: DB record version
  28. * example: 0
  29. * commentCount:
  30. * type: number
  31. * description: count of comments
  32. * example: 3
  33. * createdAt:
  34. * type: string
  35. * description: date created at
  36. * example: 2010-01-01T00:00:00.000Z
  37. * creator:
  38. * $ref: '#/components/schemas/User'
  39. * extended:
  40. * type: object
  41. * description: extend data
  42. * example: {}
  43. * grant:
  44. * type: number
  45. * description: grant
  46. * example: 1
  47. * grantedUsers:
  48. * type: array
  49. * description: granted users
  50. * items:
  51. * type: string
  52. * description: user ID
  53. * example: ["5ae5fccfc5577b0004dbd8ab"]
  54. * lastUpdateUser:
  55. * $ref: '#/components/schemas/User'
  56. * liker:
  57. * type: array
  58. * description: granted users
  59. * items:
  60. * type: string
  61. * description: user ID
  62. * example: []
  63. * path:
  64. * type: string
  65. * description: page path
  66. * example: /
  67. * redirectTo:
  68. * type: string
  69. * description: redirect path
  70. * example: ""
  71. * revision:
  72. * type: string
  73. * description: page revision
  74. * seenUsers:
  75. * type: array
  76. * description: granted users
  77. * items:
  78. * type: string
  79. * description: user ID
  80. * example: ["5ae5fccfc5577b0004dbd8ab"]
  81. * status:
  82. * type: string
  83. * description: status
  84. * enum:
  85. * - 'wip'
  86. * - 'published'
  87. * - 'deleted'
  88. * - 'deprecated'
  89. * example: published
  90. * updatedAt:
  91. * type: string
  92. * description: date updated at
  93. * example: 2010-01-01T00:00:00.000Z
  94. *
  95. * LikeParams:
  96. * description: LikeParams
  97. * type: object
  98. * properties:
  99. * pageId:
  100. * type: string
  101. * description: page ID
  102. * example: 5e07345972560e001761fa63
  103. * bool:
  104. * type: boolean
  105. * description: boolean for like status
  106. */
  107. module.exports = (crowi) => {
  108. const accessTokenParser = require('../../middlewares/access-token-parser')(crowi);
  109. const loginRequired = require('../../middlewares/login-required')(crowi);
  110. const csrf = require('../../middlewares/csrf')(crowi);
  111. const apiV3FormValidator = require('../../middlewares/apiv3-form-validator')(crowi);
  112. const globalNotificationService = crowi.getGlobalNotificationService();
  113. const { Page, GlobalNotificationSetting, User } = crowi.models;
  114. const { exportService } = crowi;
  115. const validator = {
  116. likes: [
  117. body('pageId').isString(),
  118. body('bool').isBoolean(),
  119. ],
  120. likeInfo: [
  121. query('_id').isMongoId(),
  122. ],
  123. export: [
  124. query('format').isString().isIn(['md', 'pdf']),
  125. query('revisionId').isString(),
  126. ],
  127. archive: [
  128. body('rootPagePath').isString(),
  129. body('isCommentDownload').isBoolean(),
  130. body('isAttachmentFileDownload').isBoolean(),
  131. body('isSubordinatedPageDownload').isBoolean(),
  132. body('fileType').isString().isIn(['pdf', 'markdown']),
  133. body('hierarchyType').isString().isIn(['allSubordinatedPage', 'decideHierarchy']),
  134. body('hierarchyValue').isNumeric(),
  135. ],
  136. };
  137. /**
  138. * @swagger
  139. *
  140. * /page/likes:
  141. * put:
  142. * tags: [Page]
  143. * summary: /page/likes
  144. * description: Update liked status
  145. * operationId: updateLikedStatus
  146. * requestBody:
  147. * content:
  148. * application/json:
  149. * schema:
  150. * $ref: '#/components/schemas/LikeParams'
  151. * responses:
  152. * 200:
  153. * description: Succeeded to update liked status.
  154. * content:
  155. * application/json:
  156. * schema:
  157. * $ref: '#/components/schemas/Page'
  158. */
  159. router.put('/likes', accessTokenParser, loginRequired, csrf, validator.likes, apiV3FormValidator, async(req, res) => {
  160. const { pageId, bool } = req.body;
  161. let page;
  162. try {
  163. page = await Page.findByIdAndViewer(pageId, req.user);
  164. if (page == null) {
  165. return res.apiv3Err(`Page '${pageId}' is not found or forbidden`);
  166. }
  167. if (bool) {
  168. page = await page.like(req.user);
  169. }
  170. else {
  171. page = await page.unlike(req.user);
  172. }
  173. }
  174. catch (err) {
  175. logger.error('update-like-failed', err);
  176. return res.apiv3Err(err, 500);
  177. }
  178. try {
  179. // global notification
  180. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_LIKE, page, req.user);
  181. }
  182. catch (err) {
  183. logger.error('Like notification failed', err);
  184. }
  185. const result = { page };
  186. result.seenUser = page.seenUsers;
  187. return res.apiv3({ result });
  188. });
  189. router.get('/like-info', loginRequired, validator.likeInfo, async(req, res) => {
  190. const pageId = req.query._id;
  191. const userId = req.user._id;
  192. try {
  193. const page = await Page.findById(pageId);
  194. const users = await Page.findById(pageId).populate('liker', User.USER_PUBLIC_FIELDS);
  195. const sumOfLikers = page.liker.length;
  196. const isLiked = page.liker.includes(userId);
  197. return res.apiv3({ users, sumOfLikers, isLiked });
  198. }
  199. catch (err) {
  200. logger.error('error like info', err);
  201. return res.apiv3Err(err, 500);
  202. }
  203. });
  204. /**
  205. * @swagger
  206. *
  207. * /pages/export:
  208. * get:
  209. * tags: [Export]
  210. * description: return page's markdown
  211. * responses:
  212. * 200:
  213. * description: Return page's markdown
  214. */
  215. router.get('/export/:pageId', loginRequired, validator.export, async(req, res) => {
  216. const { pageId } = req.params;
  217. const { format, revisionId = null } = req.query;
  218. let revision;
  219. try {
  220. const Page = crowi.model('Page');
  221. const page = await Page.findByIdAndViewer(pageId, req.user);
  222. if (page == null) {
  223. const isPageExist = await Page.count({ _id: pageId }) > 0;
  224. if (isPageExist) {
  225. // This page exists but req.user has not read permission
  226. return res.apiv3Err(new ErrorV3(`Haven't the right to see the page ${pageId}.`), 403);
  227. }
  228. return res.apiv3Err(new ErrorV3(`Page ${pageId} is not exist.`), 404);
  229. }
  230. const revisionIdForFind = revisionId || page.revision;
  231. const Revision = crowi.model('Revision');
  232. revision = await Revision.findById(revisionIdForFind);
  233. }
  234. catch (err) {
  235. logger.error('Failed to get page data', err);
  236. return res.apiv3Err(err, 500);
  237. }
  238. const fileName = revision.id;
  239. let stream;
  240. try {
  241. stream = exportService.getReadStreamFromRevision(revision, format);
  242. }
  243. catch (err) {
  244. logger.error('Failed to create readStream', err);
  245. return res.apiv3Err(err, 500);
  246. }
  247. res.set({
  248. 'Content-Disposition': `attachment;filename*=UTF-8''${fileName}.${format}`,
  249. });
  250. return stream.pipe(res);
  251. });
  252. // TODO GW-2746 bulk export pages
  253. // /**
  254. // * @swagger
  255. // *
  256. // * /page/archive:
  257. // * post:
  258. // * tags: [Page]
  259. // * summary: /page/archive
  260. // * description: create page archive
  261. // * requestBody:
  262. // * content:
  263. // * application/json:
  264. // * schema:
  265. // * properties:
  266. // * rootPagePath:
  267. // * type: string
  268. // * description: path of the root page
  269. // * isCommentDownload:
  270. // * type: boolean
  271. // * description: whether archive data contains comments
  272. // * isAttachmentFileDownload:
  273. // * type: boolean
  274. // * description: whether archive data contains attachments
  275. // * isSubordinatedPageDownload:
  276. // * type: boolean
  277. // * description: whether archive data children pages
  278. // * fileType:
  279. // * type: string
  280. // * description: file type of archive data(.md, .pdf)
  281. // * hierarchyType:
  282. // * type: string
  283. // * description: method of select children pages archive data contains('allSubordinatedPage', 'decideHierarchy')
  284. // * hierarchyValue:
  285. // * type: number
  286. // * description: depth of hierarchy(use when hierarchyType is 'decideHierarchy')
  287. // * responses:
  288. // * 200:
  289. // * description: create page archive
  290. // * content:
  291. // * application/json:
  292. // * schema:
  293. // * $ref: '#/components/schemas/Page'
  294. // */
  295. // router.post('/archive', accessTokenParser, loginRequired, csrf, validator.archive, apiV3FormValidator, async(req, res) => {
  296. // const PageArchive = crowi.model('PageArchive');
  297. // const {
  298. // rootPagePath,
  299. // isCommentDownload,
  300. // isAttachmentFileDownload,
  301. // fileType,
  302. // } = req.body;
  303. // const owner = req.user._id;
  304. // const numOfPages = 1; // TODO 最終的にzipファイルに取り込むページ数を入れる
  305. // const createdPageArchive = PageArchive.create({
  306. // owner,
  307. // fileType,
  308. // rootPagePath,
  309. // numOfPages,
  310. // hasComment: isCommentDownload,
  311. // hasAttachment: isAttachmentFileDownload,
  312. // });
  313. // console.log(createdPageArchive);
  314. // return res.apiv3({ });
  315. // });
  316. // router.get('/count-children-pages', accessTokenParser, loginRequired, async(req, res) => {
  317. // // TO DO implement correct number at another task
  318. // const { pageId } = req.query;
  319. // console.log(pageId);
  320. // const dummy = 6;
  321. // return res.apiv3({ dummy });
  322. // });
  323. return router;
  324. };