comment.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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 GlobalNotificationSetting = crowi.model('GlobalNotificationSetting');
  7. const ApiResponse = require('../util/apiResponse');
  8. const globalNotificationService = crowi.getGlobalNotificationService();
  9. const { body } = require('express-validator/check');
  10. const mongoose = require('mongoose');
  11. const ObjectId = mongoose.Types.ObjectId;
  12. const actions = {};
  13. const api = {};
  14. actions.api = api;
  15. api.validators = {};
  16. /**
  17. * @api {get} /comments.get Get comments of the page of the revision
  18. * @apiName GetComments
  19. * @apiGroup Comment
  20. *
  21. * @apiParam {String} page_id Page Id.
  22. * @apiParam {String} revision_id Revision Id.
  23. */
  24. api.get = async function(req, res) {
  25. const pageId = req.query.page_id;
  26. const revisionId = req.query.revision_id;
  27. // check whether accessible
  28. const isAccessible = await Page.isAccessiblePageByViewer(pageId, req.user);
  29. if (!isAccessible) {
  30. return res.json(ApiResponse.error('Current user is not accessible to this page.'));
  31. }
  32. let fetcher = null;
  33. try {
  34. if (revisionId) {
  35. fetcher = Comment.getCommentsByRevisionId(revisionId);
  36. }
  37. else {
  38. fetcher = Comment.getCommentsByPageId(pageId);
  39. }
  40. }
  41. catch (err) {
  42. return res.json(ApiResponse.error(err));
  43. }
  44. const comments = await fetcher.populate(
  45. { path: 'creator', select: User.USER_PUBLIC_FIELDS, populate: User.IMAGE_POPULATION },
  46. );
  47. res.json(ApiResponse.success({ comments }));
  48. };
  49. api.validators.add = function() {
  50. const validator = [
  51. body('commentForm.page_id').exists(),
  52. body('commentForm.revision_id').exists(),
  53. body('commentForm.comment').exists(),
  54. body('commentForm.comment_position').isInt(),
  55. body('commentForm.is_markdown').isBoolean(),
  56. body('commentForm.replyTo').exists().custom((value) => {
  57. if (value === '') {
  58. return undefined;
  59. }
  60. return ObjectId(value);
  61. }),
  62. body('slackNotificationForm.isSlackEnabled').isBoolean().exists(),
  63. ];
  64. return validator;
  65. };
  66. /**
  67. * @api {post} /comments.add Post comment for the page
  68. * @apiName PostComment
  69. * @apiGroup Comment
  70. *
  71. * @apiParam {String} page_id Page Id.
  72. * @apiParam {String} revision_id Revision Id.
  73. * @apiParam {String} comment Comment body
  74. * @apiParam {Number} comment_position=-1 Line number of the comment
  75. */
  76. api.add = async function(req, res) {
  77. const { commentForm, slackNotificationForm } = req.body;
  78. const { validationResult } = require('express-validator/check');
  79. const errors = validationResult(req.body);
  80. if (!errors.isEmpty()) {
  81. return res.json(ApiResponse.error('コメントを入力してください。'));
  82. }
  83. const pageId = commentForm.page_id;
  84. const revisionId = commentForm.revision_id;
  85. const comment = commentForm.comment;
  86. const position = commentForm.comment_position || -1;
  87. const isMarkdown = commentForm.is_markdown;
  88. const replyTo = commentForm.replyTo;
  89. // check whether accessible
  90. const isAccessible = await Page.isAccessiblePageByViewer(pageId, req.user);
  91. if (!isAccessible) {
  92. return res.json(ApiResponse.error('Current user is not accessible to this page.'));
  93. }
  94. let createdComment;
  95. try {
  96. createdComment = await Comment.create(pageId, req.user._id, revisionId, comment, position, isMarkdown, replyTo);
  97. await Comment.populate(createdComment, [
  98. { path: 'creator', model: 'User', select: User.USER_PUBLIC_FIELDS },
  99. ]);
  100. }
  101. catch (err) {
  102. logger.error(err);
  103. return res.json(ApiResponse.error(err));
  104. }
  105. // update page
  106. const page = await Page.findOneAndUpdate(
  107. { _id: pageId },
  108. {
  109. lastUpdateUser: req.user,
  110. updatedAt: new Date(),
  111. },
  112. );
  113. res.json(ApiResponse.success({ comment: createdComment }));
  114. const path = page.path;
  115. // global notification
  116. globalNotificationService.fire(GlobalNotificationSetting.EVENT.COMMENT, path, req.user, {
  117. comment: createdComment,
  118. });
  119. // slack notification
  120. if (slackNotificationForm.isSlackEnabled) {
  121. const user = await User.findUserByUsername(req.user.username);
  122. const channelsStr = slackNotificationForm.slackChannels || null;
  123. page.updateSlackChannel(channelsStr).catch((err) => {
  124. logger.error('Error occured in updating slack channels: ', err);
  125. });
  126. const channels = channelsStr != null ? channelsStr.split(',') : [null];
  127. const promises = channels.map((chan) => {
  128. return crowi.slack.postComment(createdComment, user, chan, path);
  129. });
  130. Promise.all(promises)
  131. .catch((err) => {
  132. logger.error('Error occured in sending slack notification: ', err);
  133. });
  134. }
  135. };
  136. /**
  137. * @api {post} /comments.update Update comment dody
  138. * @apiName UpdateComment
  139. * @apiGroup Comment
  140. */
  141. api.update = async function(req, res) {
  142. const { commentForm } = req.body;
  143. const pageId = commentForm.page_id;
  144. const revisionId = commentForm.revision_id;
  145. const comment = commentForm.comment;
  146. const isMarkdown = commentForm.is_markdown;
  147. const commentId = commentForm.comment_id;
  148. const author = commentForm.author;
  149. if (comment === '') {
  150. return res.json(ApiResponse.error('Comment text is required'));
  151. }
  152. if (commentId == null) {
  153. return res.json(ApiResponse.error('\'comment_id\' is undefined'));
  154. }
  155. if (author !== req.user.username) {
  156. return res.json(ApiResponse.error('Only the author can edit'));
  157. }
  158. // check whether accessible
  159. const isAccessible = await Page.isAccessiblePageByViewer(pageId, req.user._id, revisionId, comment, isMarkdown, req.user);
  160. if (!isAccessible) {
  161. return res.json(ApiResponse.error('Current user is not accessible to this page.'));
  162. }
  163. let updatedComment;
  164. try {
  165. updatedComment = await Comment.updateCommentsByPageId(comment, isMarkdown, commentId);
  166. }
  167. catch (err) {
  168. logger.error(err);
  169. return res.json(ApiResponse.error(err));
  170. }
  171. res.json(ApiResponse.success({ comment: updatedComment }));
  172. // process notification if needed
  173. };
  174. /**
  175. * @api {post} /comments.remove Remove specified comment
  176. * @apiName RemoveComment
  177. * @apiGroup Comment
  178. *
  179. * @apiParam {String} comment_id Comment Id.
  180. */
  181. api.remove = async function(req, res) {
  182. const commentId = req.body.comment_id;
  183. if (!commentId) {
  184. return Promise.resolve(res.json(ApiResponse.error('\'comment_id\' is undefined')));
  185. }
  186. try {
  187. const comment = await Comment.findById(commentId).exec();
  188. if (comment == null) {
  189. throw new Error('This comment does not exist.');
  190. }
  191. // check whether accessible
  192. const pageId = comment.page;
  193. const isAccessible = await Page.isAccessiblePageByViewer(pageId, req.user);
  194. if (!isAccessible) {
  195. throw new Error('Current user is not accessible to this page.');
  196. }
  197. await comment.removeWithReplies();
  198. await Page.updateCommentCount(comment.page);
  199. }
  200. catch (err) {
  201. return res.json(ApiResponse.error(err));
  202. }
  203. return res.json(ApiResponse.success({}));
  204. };
  205. return actions;
  206. };