comment.js 16 KB

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