comment.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. import { Comment, CommentEvent, commentEvent } from '~/features/comment/server';
  2. import { SupportedAction, SupportedTargetModel, SupportedEventModel } from '~/interfaces/activity';
  3. import loggerFactory from '~/utils/logger';
  4. import { GlobalNotificationSettingEvent } from '../models';
  5. import { preNotifyService } from '../service/pre-notify';
  6. /**
  7. * @swagger
  8. * tags:
  9. * name: Comments
  10. */
  11. const { serializeUserSecurely } = require('../models/serializers/user-serializer');
  12. /**
  13. * @swagger
  14. *
  15. * components:
  16. * schemas:
  17. * Comment:
  18. * description: Comment
  19. * type: object
  20. * properties:
  21. * _id:
  22. * type: string
  23. * description: revision ID
  24. * example: 5e079a0a0afa6700170a75fb
  25. * __v:
  26. * type: number
  27. * description: DB record version
  28. * example: 0
  29. * page:
  30. * $ref: '#/components/schemas/Page/properties/_id'
  31. * creator:
  32. * $ref: '#/components/schemas/User/properties/_id'
  33. * revision:
  34. * $ref: '#/components/schemas/Revision/properties/_id'
  35. * comment:
  36. * type: string
  37. * description: comment
  38. * example: good
  39. * commentPosition:
  40. * type: number
  41. * description: comment position
  42. * example: 0
  43. * createdAt:
  44. * type: string
  45. * description: date created at
  46. * example: 2010-01-01T00:00:00.000Z
  47. */
  48. module.exports = function(crowi, app) {
  49. const logger = loggerFactory('growi:routes:comment');
  50. const User = crowi.model('User');
  51. const Page = crowi.model('Page');
  52. const GlobalNotificationSetting = crowi.model('GlobalNotificationSetting');
  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. let createdComment;
  224. try {
  225. createdComment = await Comment.add(pageId, req.user._id, revisionId, comment, position, replyTo);
  226. commentEvent.emit(CommentEvent.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. const getAdditionalTargetUsers = async(activity) => {
  248. const mentionedUsers = await crowi.commentService.getMentionedUsers(activity.event);
  249. return mentionedUsers;
  250. };
  251. activityEvent.emit('update', res.locals.activity._id, parameters, page, preNotifyService.generatePreNotify, getAdditionalTargetUsers);
  252. res.json(ApiResponse.success({ comment: createdComment }));
  253. // global notification
  254. try {
  255. await globalNotificationService.fire(GlobalNotificationSettingEvent.COMMENT, page, req.user, {
  256. comment: createdComment,
  257. });
  258. }
  259. catch (err) {
  260. logger.error('Comment notification failed', err);
  261. }
  262. // slack notification
  263. if (slackNotificationForm.isSlackEnabled) {
  264. const { slackChannels } = slackNotificationForm;
  265. try {
  266. const results = await userNotificationService.fire(page, req.user, slackChannels, 'comment', {}, createdComment);
  267. results.forEach((result) => {
  268. if (result.status === 'rejected') {
  269. logger.error('Create user notification failed', result.reason);
  270. }
  271. });
  272. }
  273. catch (err) {
  274. logger.error('Create user notification failed', err);
  275. }
  276. }
  277. };
  278. /**
  279. * @swagger
  280. *
  281. * /comments.update:
  282. * post:
  283. * tags: [Comments, CrowiCompatibles]
  284. * operationId: updateComment
  285. * summary: /comments.update
  286. * description: Update comment dody
  287. * requestBody:
  288. * content:
  289. * application/json:
  290. * schema:
  291. * properties:
  292. * form:
  293. * type: object
  294. * properties:
  295. * commentForm:
  296. * type: object
  297. * properties:
  298. * page_id:
  299. * $ref: '#/components/schemas/Page/properties/_id'
  300. * revision_id:
  301. * $ref: '#/components/schemas/Revision/properties/_id'
  302. * comment_id:
  303. * $ref: '#/components/schemas/Comment/properties/_id'
  304. * comment:
  305. * $ref: '#/components/schemas/Comment/properties/comment'
  306. * required:
  307. * - form
  308. * responses:
  309. * 200:
  310. * description: Succeeded to update comment dody.
  311. * content:
  312. * application/json:
  313. * schema:
  314. * properties:
  315. * ok:
  316. * $ref: '#/components/schemas/V1Response/properties/ok'
  317. * comment:
  318. * $ref: '#/components/schemas/Comment'
  319. * 403:
  320. * $ref: '#/components/responses/403'
  321. * 500:
  322. * $ref: '#/components/responses/500'
  323. */
  324. /**
  325. * @api {post} /comments.update Update comment dody
  326. * @apiName UpdateComment
  327. * @apiGroup Comment
  328. */
  329. api.update = async function(req, res) {
  330. const { commentForm } = req.body;
  331. const commentStr = commentForm.comment;
  332. const commentId = commentForm.comment_id;
  333. const revision = commentForm.revision_id;
  334. if (commentStr === '') {
  335. return res.json(ApiResponse.error('Comment text is required'));
  336. }
  337. if (commentId == null) {
  338. return res.json(ApiResponse.error('\'comment_id\' is undefined'));
  339. }
  340. let updatedComment;
  341. try {
  342. const comment = await Comment.findById(commentId).exec();
  343. if (comment == null) {
  344. throw new Error('This comment does not exist.');
  345. }
  346. // check whether accessible
  347. const pageId = comment.page;
  348. const isAccessible = await Page.isAccessiblePageByViewer(pageId, req.user);
  349. if (!isAccessible) {
  350. throw new Error('Current user is not accessible to this page.');
  351. }
  352. if (req.user.id !== comment.creator.toString()) {
  353. throw new Error('Current user is not operatable to this comment.');
  354. }
  355. updatedComment = await Comment.findOneAndUpdate(
  356. { _id: commentId },
  357. { $set: { comment: commentStr, revision } },
  358. );
  359. commentEvent.emit(CommentEvent.UPDATE, updatedComment);
  360. }
  361. catch (err) {
  362. logger.error(err);
  363. return res.json(ApiResponse.error(err));
  364. }
  365. const parameters = { action: SupportedAction.ACTION_COMMENT_UPDATE };
  366. activityEvent.emit('update', res.locals.activity._id, parameters);
  367. res.json(ApiResponse.success({ comment: updatedComment }));
  368. // process notification if needed
  369. };
  370. /**
  371. * @swagger
  372. *
  373. * /comments.remove:
  374. * post:
  375. * tags: [Comments, CrowiCompatibles]
  376. * operationId: removeComment
  377. * summary: /comments.remove
  378. * description: Remove specified comment
  379. * requestBody:
  380. * content:
  381. * application/json:
  382. * schema:
  383. * properties:
  384. * comment_id:
  385. * $ref: '#/components/schemas/Comment/properties/_id'
  386. * required:
  387. * - comment_id
  388. * responses:
  389. * 200:
  390. * description: Succeeded to remove specified comment.
  391. * content:
  392. * application/json:
  393. * schema:
  394. * properties:
  395. * ok:
  396. * $ref: '#/components/schemas/V1Response/properties/ok'
  397. * comment:
  398. * $ref: '#/components/schemas/Comment'
  399. * 403:
  400. * $ref: '#/components/responses/403'
  401. * 500:
  402. * $ref: '#/components/responses/500'
  403. */
  404. /**
  405. * @api {post} /comments.remove Remove specified comment
  406. * @apiName RemoveComment
  407. * @apiGroup Comment
  408. *
  409. * @apiParam {String} comment_id Comment Id.
  410. */
  411. api.remove = async function(req, res) {
  412. const commentId = req.body.comment_id;
  413. if (!commentId) {
  414. return Promise.resolve(res.json(ApiResponse.error('\'comment_id\' is undefined')));
  415. }
  416. try {
  417. const comment = await Comment.findById(commentId).exec();
  418. if (comment == null) {
  419. throw new Error('This comment does not exist.');
  420. }
  421. // check whether accessible
  422. const pageId = comment.page;
  423. const isAccessible = await Page.isAccessiblePageByViewer(pageId, req.user);
  424. if (!isAccessible) {
  425. throw new Error('Current user is not accessible to this page.');
  426. }
  427. if (req.user.id !== comment.creator.toString()) {
  428. throw new Error('Current user is not operatable to this comment.');
  429. }
  430. await comment.removeWithReplies(comment);
  431. await Page.updateCommentCount(comment.page);
  432. commentEvent.emit(CommentEvent.DELETE, comment);
  433. }
  434. catch (err) {
  435. return res.json(ApiResponse.error(err));
  436. }
  437. const parameters = { action: SupportedAction.ACTION_COMMENT_REMOVE };
  438. activityEvent.emit('update', res.locals.activity._id, parameters);
  439. return res.json(ApiResponse.success({}));
  440. };
  441. return actions;
  442. };