comment.js 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. module.exports = function(crowi, app) {
  2. const logger = require('@alias/logger')('growi:routes:comment');
  3. const Comment = crowi.model('Comment');
  4. const User = crowi.model('User');
  5. const Page = crowi.model('Page');
  6. const ApiResponse = require('../util/apiResponse');
  7. const globalNotificationService = crowi.getGlobalNotificationService();
  8. const { body } = require('express-validator/check');
  9. const mongoose = require('mongoose');
  10. const ObjectId = mongoose.Types.ObjectId;
  11. const actions = {};
  12. const api = {};
  13. actions.api = api;
  14. api.validators = {};
  15. /**
  16. * @api {get} /comments.get Get comments of the page of the revision
  17. * @apiName GetComments
  18. * @apiGroup Comment
  19. *
  20. * @apiParam {String} page_id Page Id.
  21. * @apiParam {String} revision_id Revision Id.
  22. */
  23. api.get = async function(req, res) {
  24. const pageId = req.query.page_id;
  25. const revisionId = req.query.revision_id;
  26. // check whether accessible
  27. const isAccessible = await Page.isAccessiblePageByViewer(pageId, req.user);
  28. if (!isAccessible) {
  29. return res.json(ApiResponse.error('Current user is not accessible to this page.'));
  30. }
  31. let fetcher = null;
  32. try {
  33. if (revisionId) {
  34. fetcher = Comment.getCommentsByRevisionId(revisionId);
  35. }
  36. else {
  37. fetcher = Comment.getCommentsByPageId(pageId);
  38. }
  39. }
  40. catch (err) {
  41. return res.json(ApiResponse.error(err));
  42. }
  43. const comments = await fetcher.populate(
  44. { path: 'creator', select: User.USER_PUBLIC_FIELDS, populate: User.IMAGE_POPULATION },
  45. );
  46. res.json(ApiResponse.success({ comments }));
  47. };
  48. api.validators.add = function() {
  49. const validator = [
  50. body('commentForm.page_id').exists(),
  51. body('commentForm.revision_id').exists(),
  52. body('commentForm.comment').exists(),
  53. body('commentForm.comment_position').isInt(),
  54. body('commentForm.is_markdown').isBoolean(),
  55. body('commentForm.replyTo').exists().custom((value) => {
  56. if (value === '') {
  57. return undefined;
  58. }
  59. return ObjectId(value);
  60. }),
  61. body('slackNotificationForm.isSlackEnabled').isBoolean().exists(),
  62. ];
  63. return validator;
  64. };
  65. /**
  66. * @api {post} /comments.add Post comment for the page
  67. * @apiName PostComment
  68. * @apiGroup Comment
  69. *
  70. * @apiParam {String} page_id Page Id.
  71. * @apiParam {String} revision_id Revision Id.
  72. * @apiParam {String} comment Comment body
  73. * @apiParam {Number} comment_position=-1 Line number of the comment
  74. */
  75. api.add = async function(req, res) {
  76. const { commentForm, slackNotificationForm } = req.body;
  77. const { validationResult } = require('express-validator/check');
  78. const errors = validationResult(req.body);
  79. if (!errors.isEmpty()) {
  80. return res.json(ApiResponse.error('コメントを入力してください。'));
  81. }
  82. const pageId = commentForm.page_id;
  83. const revisionId = commentForm.revision_id;
  84. const comment = commentForm.comment;
  85. const position = commentForm.comment_position || -1;
  86. const isMarkdown = commentForm.is_markdown;
  87. const replyTo = commentForm.replyTo;
  88. // check whether accessible
  89. const isAccessible = await Page.isAccessiblePageByViewer(pageId, req.user);
  90. if (!isAccessible) {
  91. return res.json(ApiResponse.error('Current user is not accessible to this page.'));
  92. }
  93. const createdComment = await Comment.create(pageId, req.user._id, revisionId, comment, position, isMarkdown, replyTo)
  94. .catch((err) => {
  95. return res.json(ApiResponse.error(err));
  96. });
  97. // update page
  98. const page = await Page.findOneAndUpdate({ _id: pageId }, {
  99. lastUpdateUser: req.user,
  100. updatedAt: new Date(),
  101. });
  102. res.json(ApiResponse.success({ comment: createdComment }));
  103. const path = page.path;
  104. // global notification
  105. globalNotificationService.notifyComment(createdComment, path);
  106. // slack notification
  107. if (slackNotificationForm.isSlackEnabled) {
  108. const user = await User.findUserByUsername(req.user.username);
  109. const channels = slackNotificationForm.slackChannels;
  110. if (channels) {
  111. page.updateSlackChannel(channels).catch((err) => {
  112. logger.error('Error occured in updating slack channels: ', err);
  113. });
  114. const promises = channels.split(',').map((chan) => {
  115. return crowi.slack.postComment(createdComment, user, chan, path);
  116. });
  117. Promise.all(promises)
  118. .catch((err) => {
  119. logger.error('Error occured in sending slack notification: ', err);
  120. });
  121. }
  122. }
  123. };
  124. /**
  125. * @api {post} /comments.remove Remove specified comment
  126. * @apiName RemoveComment
  127. * @apiGroup Comment
  128. *
  129. * @apiParam {String} comment_id Comment Id.
  130. */
  131. api.remove = async function(req, res) {
  132. const commentId = req.body.comment_id;
  133. if (!commentId) {
  134. return Promise.resolve(res.json(ApiResponse.error('\'comment_id\' is undefined')));
  135. }
  136. try {
  137. const comment = await Comment.findById(commentId).exec();
  138. if (comment == null) {
  139. throw new Error('This comment does not exist.');
  140. }
  141. // check whether accessible
  142. const pageId = comment.page;
  143. const isAccessible = await Page.isAccessiblePageByViewer(pageId, req.user);
  144. if (!isAccessible) {
  145. throw new Error('Current user is not accessible to this page.');
  146. }
  147. await comment.removeWithReplies();
  148. await Page.updateCommentCount(comment.page);
  149. }
  150. catch (err) {
  151. return res.json(ApiResponse.error(err));
  152. }
  153. return res.json(ApiResponse.success({}));
  154. };
  155. return actions;
  156. };