comment.js 15 KB

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