comment.js 14 KB

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