comment.js 16 KB

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