comment.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. /**
  2. * @swagger
  3. * tags:
  4. * name: Comments
  5. */
  6. /**
  7. * @swagger
  8. *
  9. * components:
  10. * schemas:
  11. * Comment:
  12. * description: Comment
  13. * type: object
  14. * properties:
  15. * _id:
  16. * type: string
  17. * description: revision ID
  18. * example: 5e079a0a0afa6700170a75fb
  19. * __v:
  20. * type: number
  21. * description: DB record version
  22. * example: 0
  23. * page:
  24. * $ref: '#/components/schemas/Page/properties/_id'
  25. * creator:
  26. * $ref: '#/components/schemas/User/properties/_id'
  27. * revision:
  28. * $ref: '#/components/schemas/Revision/properties/_id'
  29. * comment:
  30. * type: string
  31. * description: comment
  32. * example: good
  33. * commentPosition:
  34. * type: number
  35. * description: comment position
  36. * example: 0
  37. * createdAt:
  38. * type: string
  39. * description: date created at
  40. * example: 2010-01-01T00:00:00.000Z
  41. */
  42. module.exports = function(crowi, app) {
  43. const logger = require('@alias/logger')('growi:routes:comment');
  44. const Comment = crowi.model('Comment');
  45. const User = crowi.model('User');
  46. const Page = crowi.model('Page');
  47. const GlobalNotificationSetting = crowi.model('GlobalNotificationSetting');
  48. const ApiResponse = require('../util/apiResponse');
  49. const globalNotificationService = crowi.getGlobalNotificationService();
  50. const { body } = require('express-validator');
  51. const mongoose = require('mongoose');
  52. const ObjectId = mongoose.Types.ObjectId;
  53. const actions = {};
  54. const api = {};
  55. actions.api = api;
  56. api.validators = {};
  57. /**
  58. * @swagger
  59. *
  60. * /comments.get:
  61. * get:
  62. * tags: [Comments, CrowiCompatibles]
  63. * operationId: getComments
  64. * summary: /comments.get
  65. * description: Get comments of the page of the revision
  66. * parameters:
  67. * - in: query
  68. * name: page_id
  69. * schema:
  70. * $ref: '#/components/schemas/Page/properties/_id'
  71. * - in: query
  72. * name: revision_id
  73. * schema:
  74. * $ref: '#/components/schemas/Revision/properties/_id'
  75. * responses:
  76. * 200:
  77. * description: Succeeded to get comments of the page of the revision.
  78. * content:
  79. * application/json:
  80. * schema:
  81. * properties:
  82. * ok:
  83. * $ref: '#/components/schemas/V1Response/properties/ok'
  84. * comments:
  85. * type: array
  86. * items:
  87. * $ref: '#/components/schemas/Comment'
  88. * 403:
  89. * $ref: '#/components/responses/403'
  90. * 500:
  91. * $ref: '#/components/responses/500'
  92. */
  93. /**
  94. * @api {get} /comments.get Get comments of the page of the revision
  95. * @apiName GetComments
  96. * @apiGroup Comment
  97. *
  98. * @apiParam {String} page_id Page Id.
  99. * @apiParam {String} revision_id Revision Id.
  100. */
  101. api.get = async function(req, res) {
  102. const pageId = req.query.page_id;
  103. const revisionId = req.query.revision_id;
  104. // check whether accessible
  105. const isAccessible = await Page.isAccessiblePageByViewer(pageId, req.user);
  106. if (!isAccessible) {
  107. return res.json(ApiResponse.error('Current user is not accessible to this page.'));
  108. }
  109. let fetcher = null;
  110. try {
  111. if (revisionId) {
  112. fetcher = Comment.getCommentsByRevisionId(revisionId);
  113. }
  114. else {
  115. fetcher = Comment.getCommentsByPageId(pageId);
  116. }
  117. }
  118. catch (err) {
  119. return res.json(ApiResponse.error(err));
  120. }
  121. const comments = await fetcher.populate(
  122. { path: 'creator', select: User.USER_PUBLIC_FIELDS },
  123. );
  124. res.json(ApiResponse.success({ comments }));
  125. };
  126. api.validators.add = function() {
  127. const validator = [
  128. body('commentForm.page_id').exists(),
  129. body('commentForm.revision_id').exists(),
  130. body('commentForm.comment').exists(),
  131. body('commentForm.comment_position').isInt(),
  132. body('commentForm.is_markdown').isBoolean(),
  133. body('commentForm.replyTo').exists().custom((value) => {
  134. if (value === '') {
  135. return undefined;
  136. }
  137. return ObjectId(value);
  138. }),
  139. body('slackNotificationForm.isSlackEnabled').isBoolean().exists(),
  140. ];
  141. return validator;
  142. };
  143. /**
  144. * @swagger
  145. *
  146. * /comments.add:
  147. * post:
  148. * tags: [Comments, CrowiCompatibles]
  149. * operationId: addComment
  150. * summary: /comments.add
  151. * description: Post comment for the page
  152. * requestBody:
  153. * content:
  154. * application/json:
  155. * schema:
  156. * properties:
  157. * commentForm:
  158. * type: object
  159. * properties:
  160. * page_id:
  161. * $ref: '#/components/schemas/Page/properties/_id'
  162. * revision_id:
  163. * $ref: '#/components/schemas/Revision/properties/_id'
  164. * comment:
  165. * $ref: '#/components/schemas/Comment/properties/comment'
  166. * comment_position:
  167. * $ref: '#/components/schemas/Comment/properties/commentPosition'
  168. * required:
  169. * - commentForm
  170. * responses:
  171. * 200:
  172. * description: Succeeded to post comment for the page.
  173. * content:
  174. * application/json:
  175. * schema:
  176. * properties:
  177. * ok:
  178. * $ref: '#/components/schemas/V1Response/properties/ok'
  179. * comment:
  180. * $ref: '#/components/schemas/Comment'
  181. * 403:
  182. * $ref: '#/components/responses/403'
  183. * 500:
  184. * $ref: '#/components/responses/500'
  185. */
  186. /**
  187. * @api {post} /comments.add Post comment for the page
  188. * @apiName PostComment
  189. * @apiGroup Comment
  190. *
  191. * @apiParam {String} page_id Page Id.
  192. * @apiParam {String} revision_id Revision Id.
  193. * @apiParam {String} comment Comment body
  194. * @apiParam {Number} comment_position=-1 Line number of the comment
  195. */
  196. api.add = async function(req, res) {
  197. const { commentForm, slackNotificationForm } = req.body;
  198. const { validationResult } = require('express-validator');
  199. const errors = validationResult(req.body);
  200. if (!errors.isEmpty()) {
  201. return res.json(ApiResponse.error('コメントを入力してください。'));
  202. }
  203. const pageId = commentForm.page_id;
  204. const revisionId = commentForm.revision_id;
  205. const comment = commentForm.comment;
  206. const position = commentForm.comment_position || -1;
  207. const isMarkdown = commentForm.is_markdown;
  208. const replyTo = commentForm.replyTo;
  209. // check whether accessible
  210. const isAccessible = await Page.isAccessiblePageByViewer(pageId, req.user);
  211. if (!isAccessible) {
  212. return res.json(ApiResponse.error('Current user is not accessible to this page.'));
  213. }
  214. let createdComment;
  215. try {
  216. createdComment = await Comment.create(pageId, req.user._id, revisionId, comment, position, isMarkdown, replyTo);
  217. await Comment.populate(createdComment, [
  218. { path: 'creator', model: 'User', select: User.USER_PUBLIC_FIELDS },
  219. ]);
  220. }
  221. catch (err) {
  222. logger.error(err);
  223. return res.json(ApiResponse.error(err));
  224. }
  225. // update page
  226. const page = await Page.findOneAndUpdate(
  227. { _id: pageId },
  228. {
  229. lastUpdateUser: req.user,
  230. updatedAt: new Date(),
  231. },
  232. );
  233. res.json(ApiResponse.success({ comment: createdComment }));
  234. const path = page.path;
  235. // global notification
  236. try {
  237. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.COMMENT, page, req.user, {
  238. comment: createdComment,
  239. });
  240. }
  241. catch (err) {
  242. logger.error('Comment notification failed', err);
  243. }
  244. // slack notification
  245. if (slackNotificationForm.isSlackEnabled) {
  246. const user = await User.findUserByUsername(req.user.username);
  247. const channelsStr = slackNotificationForm.slackChannels || null;
  248. page.updateSlackChannel(channelsStr).catch((err) => {
  249. logger.error('Error occured in updating slack channels: ', err);
  250. });
  251. const channels = channelsStr != null ? channelsStr.split(',') : [null];
  252. const promises = channels.map((chan) => {
  253. return crowi.slack.postComment(createdComment, user, chan, path);
  254. });
  255. Promise.all(promises)
  256. .catch((err) => {
  257. logger.error('Error occured in sending slack notification: ', 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. };