comment.js 16 KB

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