comment.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. import loggerFactory from '~/utils/logger';
  2. /**
  3. * @swagger
  4. * tags:
  5. * name: Comments
  6. */
  7. const { serializeUserSecurely } = require('../models/serializers/user-serializer');
  8. /**
  9. * @swagger
  10. *
  11. * components:
  12. * schemas:
  13. * Comment:
  14. * description: Comment
  15. * type: object
  16. * properties:
  17. * _id:
  18. * type: string
  19. * description: revision ID
  20. * example: 5e079a0a0afa6700170a75fb
  21. * __v:
  22. * type: number
  23. * description: DB record version
  24. * example: 0
  25. * page:
  26. * $ref: '#/components/schemas/Page/properties/_id'
  27. * creator:
  28. * $ref: '#/components/schemas/User/properties/_id'
  29. * revision:
  30. * $ref: '#/components/schemas/Revision/properties/_id'
  31. * comment:
  32. * type: string
  33. * description: comment
  34. * example: good
  35. * commentPosition:
  36. * type: number
  37. * description: comment position
  38. * example: 0
  39. * createdAt:
  40. * type: string
  41. * description: date created at
  42. * example: 2010-01-01T00:00:00.000Z
  43. */
  44. module.exports = function(crowi, app) {
  45. const logger = loggerFactory('growi:routes:comment');
  46. const Comment = crowi.model('Comment');
  47. const User = crowi.model('User');
  48. const Page = crowi.model('Page');
  49. const GlobalNotificationSetting = crowi.model('GlobalNotificationSetting');
  50. const ApiResponse = require('../util/apiResponse');
  51. const globalNotificationService = crowi.getGlobalNotificationService();
  52. const userNotificationService = crowi.getUserNotificationService();
  53. const { body } = require('express-validator');
  54. const mongoose = require('mongoose');
  55. const ObjectId = mongoose.Types.ObjectId;
  56. const actions = {};
  57. const api = {};
  58. actions.api = api;
  59. api.validators = {};
  60. /**
  61. * @swagger
  62. *
  63. * /comments.get:
  64. * get:
  65. * tags: [Comments, CrowiCompatibles]
  66. * operationId: getComments
  67. * summary: /comments.get
  68. * description: Get comments of the page of the revision
  69. * parameters:
  70. * - in: query
  71. * name: page_id
  72. * schema:
  73. * $ref: '#/components/schemas/Page/properties/_id'
  74. * - in: query
  75. * name: revision_id
  76. * schema:
  77. * $ref: '#/components/schemas/Revision/properties/_id'
  78. * responses:
  79. * 200:
  80. * description: Succeeded to get comments of the page of the revision.
  81. * content:
  82. * application/json:
  83. * schema:
  84. * properties:
  85. * ok:
  86. * $ref: '#/components/schemas/V1Response/properties/ok'
  87. * comments:
  88. * type: array
  89. * items:
  90. * $ref: '#/components/schemas/Comment'
  91. * 403:
  92. * $ref: '#/components/responses/403'
  93. * 500:
  94. * $ref: '#/components/responses/500'
  95. */
  96. /**
  97. * @api {get} /comments.get Get comments of the page of the revision
  98. * @apiName GetComments
  99. * @apiGroup Comment
  100. *
  101. * @apiParam {String} page_id Page Id.
  102. * @apiParam {String} revision_id Revision Id.
  103. */
  104. api.get = async function(req, res) {
  105. const pageId = req.query.page_id;
  106. const revisionId = req.query.revision_id;
  107. // check whether accessible
  108. const isAccessible = await Page.isAccessiblePageByViewer(pageId, req.user);
  109. if (!isAccessible) {
  110. return res.json(ApiResponse.error('Current user is not accessible to this page.'));
  111. }
  112. let fetcher = null;
  113. try {
  114. if (revisionId) {
  115. fetcher = Comment.getCommentsByRevisionId(revisionId);
  116. }
  117. else {
  118. fetcher = Comment.getCommentsByPageId(pageId);
  119. }
  120. }
  121. catch (err) {
  122. return res.json(ApiResponse.error(err));
  123. }
  124. const comments = await fetcher.populate('creator');
  125. comments.forEach((comment) => {
  126. if (comment.creator != null && comment.creator instanceof User) {
  127. comment.creator = serializeUserSecurely(comment.creator);
  128. }
  129. });
  130. res.json(ApiResponse.success({ comments }));
  131. };
  132. api.validators.add = function() {
  133. const validator = [
  134. body('commentForm.page_id').exists(),
  135. body('commentForm.revision_id').exists(),
  136. body('commentForm.comment').exists(),
  137. body('commentForm.comment_position').isInt(),
  138. body('commentForm.is_markdown').isBoolean(),
  139. body('commentForm.replyTo').exists().custom((value) => {
  140. if (value === '') {
  141. return undefined;
  142. }
  143. return ObjectId(value);
  144. }),
  145. body('slackNotificationForm.isSlackEnabled').isBoolean().exists(),
  146. ];
  147. return validator;
  148. };
  149. /**
  150. * @swagger
  151. *
  152. * /comments.add:
  153. * post:
  154. * tags: [Comments, CrowiCompatibles]
  155. * operationId: addComment
  156. * summary: /comments.add
  157. * description: Post comment for the page
  158. * requestBody:
  159. * content:
  160. * application/json:
  161. * schema:
  162. * properties:
  163. * commentForm:
  164. * type: object
  165. * properties:
  166. * page_id:
  167. * $ref: '#/components/schemas/Page/properties/_id'
  168. * revision_id:
  169. * $ref: '#/components/schemas/Revision/properties/_id'
  170. * comment:
  171. * $ref: '#/components/schemas/Comment/properties/comment'
  172. * comment_position:
  173. * $ref: '#/components/schemas/Comment/properties/commentPosition'
  174. * required:
  175. * - commentForm
  176. * responses:
  177. * 200:
  178. * description: Succeeded to post comment for the page.
  179. * content:
  180. * application/json:
  181. * schema:
  182. * properties:
  183. * ok:
  184. * $ref: '#/components/schemas/V1Response/properties/ok'
  185. * comment:
  186. * $ref: '#/components/schemas/Comment'
  187. * 403:
  188. * $ref: '#/components/responses/403'
  189. * 500:
  190. * $ref: '#/components/responses/500'
  191. */
  192. /**
  193. * @api {post} /comments.add Post comment for the page
  194. * @apiName PostComment
  195. * @apiGroup Comment
  196. *
  197. * @apiParam {String} page_id Page Id.
  198. * @apiParam {String} revision_id Revision Id.
  199. * @apiParam {String} comment Comment body
  200. * @apiParam {Number} comment_position=-1 Line number of the comment
  201. */
  202. api.add = async function(req, res) {
  203. const { commentForm, slackNotificationForm } = req.body;
  204. const { validationResult } = require('express-validator');
  205. const errors = validationResult(req.body);
  206. if (!errors.isEmpty()) {
  207. return res.json(ApiResponse.error('コメントを入力してください。'));
  208. }
  209. const pageId = commentForm.page_id;
  210. const revisionId = commentForm.revision_id;
  211. const comment = commentForm.comment;
  212. const position = commentForm.comment_position || -1;
  213. const isMarkdown = commentForm.is_markdown;
  214. const replyTo = commentForm.replyTo;
  215. const commentEvent = crowi.event('comment');
  216. // check whether accessible
  217. const isAccessible = await Page.isAccessiblePageByViewer(pageId, req.user);
  218. if (!isAccessible) {
  219. return res.json(ApiResponse.error('Current user is not accessible to this page.'));
  220. }
  221. let createdComment;
  222. try {
  223. createdComment = await Comment.create(pageId, req.user._id, revisionId, comment, position, isMarkdown, replyTo);
  224. commentEvent.emit('create', createdComment);
  225. }
  226. catch (err) {
  227. logger.error(err);
  228. return res.json(ApiResponse.error(err));
  229. }
  230. // update page
  231. const page = await Page.findOneAndUpdate(
  232. { _id: pageId },
  233. {
  234. lastUpdateUser: req.user,
  235. updatedAt: new Date(),
  236. },
  237. );
  238. res.json(ApiResponse.success({ comment: createdComment }));
  239. // global notification
  240. try {
  241. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.COMMENT, page, req.user, {
  242. comment: createdComment,
  243. });
  244. }
  245. catch (err) {
  246. logger.error('Comment notification failed', err);
  247. }
  248. // slack notification
  249. if (slackNotificationForm.isSlackEnabled) {
  250. const { slackChannels } = slackNotificationForm;
  251. try {
  252. const results = await userNotificationService.fire(page, req.user, slackChannels, 'comment', {}, createdComment);
  253. results.forEach((result) => {
  254. if (result.status === 'rejected') {
  255. logger.error('Create user notification failed', result.reason);
  256. }
  257. });
  258. }
  259. catch (err) {
  260. logger.error('Create user notification failed', err);
  261. }
  262. }
  263. };
  264. /**
  265. * @swagger
  266. *
  267. * /comments.update:
  268. * post:
  269. * tags: [Comments, CrowiCompatibles]
  270. * operationId: updateComment
  271. * summary: /comments.update
  272. * description: Update comment dody
  273. * requestBody:
  274. * content:
  275. * application/json:
  276. * schema:
  277. * properties:
  278. * form:
  279. * type: object
  280. * properties:
  281. * commentForm:
  282. * type: object
  283. * properties:
  284. * page_id:
  285. * $ref: '#/components/schemas/Page/properties/_id'
  286. * revision_id:
  287. * $ref: '#/components/schemas/Revision/properties/_id'
  288. * comment_id:
  289. * $ref: '#/components/schemas/Comment/properties/_id'
  290. * comment:
  291. * $ref: '#/components/schemas/Comment/properties/comment'
  292. * required:
  293. * - form
  294. * responses:
  295. * 200:
  296. * description: Succeeded to update comment dody.
  297. * content:
  298. * application/json:
  299. * schema:
  300. * properties:
  301. * ok:
  302. * $ref: '#/components/schemas/V1Response/properties/ok'
  303. * comment:
  304. * $ref: '#/components/schemas/Comment'
  305. * 403:
  306. * $ref: '#/components/responses/403'
  307. * 500:
  308. * $ref: '#/components/responses/500'
  309. */
  310. /**
  311. * @api {post} /comments.update Update comment dody
  312. * @apiName UpdateComment
  313. * @apiGroup Comment
  314. */
  315. api.update = async function(req, res) {
  316. const { commentForm } = req.body;
  317. const commentStr = commentForm.comment;
  318. const isMarkdown = commentForm.is_markdown;
  319. const commentId = commentForm.comment_id;
  320. const revision = commentForm.revision_id;
  321. const commentEvent = crowi.event('comment');
  322. if (commentStr === '') {
  323. return res.json(ApiResponse.error('Comment text is required'));
  324. }
  325. if (commentId == null) {
  326. return res.json(ApiResponse.error('\'comment_id\' is undefined'));
  327. }
  328. let updatedComment;
  329. try {
  330. const comment = await Comment.findById(commentId).exec();
  331. if (comment == null) {
  332. throw new Error('This comment does not exist.');
  333. }
  334. // check whether accessible
  335. const pageId = comment.page;
  336. const isAccessible = await Page.isAccessiblePageByViewer(pageId, req.user);
  337. if (!isAccessible) {
  338. throw new Error('Current user is not accessible to this page.');
  339. }
  340. if (req.user.id !== comment.creator.toString()) {
  341. throw new Error('Current user is not operatable to this comment.');
  342. }
  343. updatedComment = await Comment.findOneAndUpdate(
  344. { _id: commentId },
  345. { $set: { comment: commentStr, isMarkdown, revision } },
  346. );
  347. commentEvent.emit('create', updatedComment);
  348. }
  349. catch (err) {
  350. logger.error(err);
  351. return res.json(ApiResponse.error(err));
  352. }
  353. res.json(ApiResponse.success({ comment: updatedComment }));
  354. // process notification if needed
  355. };
  356. /**
  357. * @swagger
  358. *
  359. * /comments.remove:
  360. * post:
  361. * tags: [Comments, CrowiCompatibles]
  362. * operationId: removeComment
  363. * summary: /comments.remove
  364. * description: Remove specified comment
  365. * requestBody:
  366. * content:
  367. * application/json:
  368. * schema:
  369. * properties:
  370. * comment_id:
  371. * $ref: '#/components/schemas/Comment/properties/_id'
  372. * required:
  373. * - comment_id
  374. * responses:
  375. * 200:
  376. * description: Succeeded to remove specified comment.
  377. * content:
  378. * application/json:
  379. * schema:
  380. * properties:
  381. * ok:
  382. * $ref: '#/components/schemas/V1Response/properties/ok'
  383. * comment:
  384. * $ref: '#/components/schemas/Comment'
  385. * 403:
  386. * $ref: '#/components/responses/403'
  387. * 500:
  388. * $ref: '#/components/responses/500'
  389. */
  390. /**
  391. * @api {post} /comments.remove Remove specified comment
  392. * @apiName RemoveComment
  393. * @apiGroup Comment
  394. *
  395. * @apiParam {String} comment_id Comment Id.
  396. */
  397. api.remove = async function(req, res) {
  398. const commentEvent = crowi.event('comment');
  399. const commentId = req.body.comment_id;
  400. if (!commentId) {
  401. return Promise.resolve(res.json(ApiResponse.error('\'comment_id\' is undefined')));
  402. }
  403. try {
  404. const comment = await Comment.findById(commentId).exec();
  405. if (comment == null) {
  406. throw new Error('This comment does not exist.');
  407. }
  408. // check whether accessible
  409. const pageId = comment.page;
  410. const isAccessible = await Page.isAccessiblePageByViewer(pageId, req.user);
  411. if (!isAccessible) {
  412. throw new Error('Current user is not accessible to this page.');
  413. }
  414. if (req.user.id !== comment.creator.toString()) {
  415. throw new Error('Current user is not operatable to this comment.');
  416. }
  417. await comment.removeWithReplies();
  418. await Page.updateCommentCount(comment.page);
  419. commentEvent.emit('delete', comment);
  420. }
  421. catch (err) {
  422. return res.json(ApiResponse.error(err));
  423. }
  424. return res.json(ApiResponse.success({}));
  425. };
  426. return actions;
  427. };