comment.js 16 KB

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