comment.js 15 KB

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