comment.js 16 KB

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