comment.js 15 KB

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