comment.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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/check');
  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. // [TODO][user-profile-cache][GW-1775] change how to get profile image data in client side.
  122. const comments = await fetcher.populate(
  123. { path: 'creator', select: User.USER_PUBLIC_FIELDS },
  124. );
  125. res.json(ApiResponse.success({ comments }));
  126. };
  127. api.validators.add = function() {
  128. const validator = [
  129. body('commentForm.page_id').exists(),
  130. body('commentForm.revision_id').exists(),
  131. body('commentForm.comment').exists(),
  132. body('commentForm.comment_position').isInt(),
  133. body('commentForm.is_markdown').isBoolean(),
  134. body('commentForm.replyTo').exists().custom((value) => {
  135. if (value === '') {
  136. return undefined;
  137. }
  138. return ObjectId(value);
  139. }),
  140. body('slackNotificationForm.isSlackEnabled').isBoolean().exists(),
  141. ];
  142. return validator;
  143. };
  144. /**
  145. * @swagger
  146. *
  147. * /comments.add:
  148. * post:
  149. * tags: [Comments, CrowiCompatibles]
  150. * operationId: addComment
  151. * summary: /comments.add
  152. * description: Post comment for the page
  153. * requestBody:
  154. * content:
  155. * application/json:
  156. * schema:
  157. * properties:
  158. * commentForm:
  159. * type: object
  160. * properties:
  161. * page_id:
  162. * $ref: '#/components/schemas/Page/properties/_id'
  163. * revision_id:
  164. * $ref: '#/components/schemas/Revision/properties/_id'
  165. * comment:
  166. * $ref: '#/components/schemas/Comment/properties/comment'
  167. * comment_position:
  168. * $ref: '#/components/schemas/Comment/properties/commentPosition'
  169. * required:
  170. * - commentForm
  171. * responses:
  172. * 200:
  173. * description: Succeeded to post comment for the page.
  174. * content:
  175. * application/json:
  176. * schema:
  177. * properties:
  178. * ok:
  179. * $ref: '#/components/schemas/V1Response/properties/ok'
  180. * comment:
  181. * $ref: '#/components/schemas/Comment'
  182. * 403:
  183. * $ref: '#/components/responses/403'
  184. * 500:
  185. * $ref: '#/components/responses/500'
  186. */
  187. /**
  188. * @api {post} /comments.add Post comment for the page
  189. * @apiName PostComment
  190. * @apiGroup Comment
  191. *
  192. * @apiParam {String} page_id Page Id.
  193. * @apiParam {String} revision_id Revision Id.
  194. * @apiParam {String} comment Comment body
  195. * @apiParam {Number} comment_position=-1 Line number of the comment
  196. */
  197. api.add = async function(req, res) {
  198. const { commentForm, slackNotificationForm } = req.body;
  199. const { validationResult } = require('express-validator/check');
  200. const errors = validationResult(req.body);
  201. if (!errors.isEmpty()) {
  202. return res.json(ApiResponse.error('コメントを入力してください。'));
  203. }
  204. const pageId = commentForm.page_id;
  205. const revisionId = commentForm.revision_id;
  206. const comment = commentForm.comment;
  207. const position = commentForm.comment_position || -1;
  208. const isMarkdown = commentForm.is_markdown;
  209. const replyTo = commentForm.replyTo;
  210. // check whether accessible
  211. const isAccessible = await Page.isAccessiblePageByViewer(pageId, req.user);
  212. if (!isAccessible) {
  213. return res.json(ApiResponse.error('Current user is not accessible to this page.'));
  214. }
  215. let createdComment;
  216. try {
  217. createdComment = await Comment.create(pageId, req.user._id, revisionId, comment, position, isMarkdown, replyTo);
  218. await Comment.populate(createdComment, [
  219. { path: 'creator', model: 'User', select: User.USER_PUBLIC_FIELDS },
  220. ]);
  221. }
  222. catch (err) {
  223. logger.error(err);
  224. return res.json(ApiResponse.error(err));
  225. }
  226. // update page
  227. const page = await Page.findOneAndUpdate(
  228. { _id: pageId },
  229. {
  230. lastUpdateUser: req.user,
  231. updatedAt: new Date(),
  232. },
  233. );
  234. res.json(ApiResponse.success({ comment: createdComment }));
  235. const path = page.path;
  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 user = await User.findUserByUsername(req.user.username);
  248. const channelsStr = slackNotificationForm.slackChannels || null;
  249. page.updateSlackChannel(channelsStr).catch((err) => {
  250. logger.error('Error occured in updating slack channels: ', err);
  251. });
  252. const channels = channelsStr != null ? channelsStr.split(',') : [null];
  253. const promises = channels.map((chan) => {
  254. return crowi.slack.postComment(createdComment, user, chan, path);
  255. });
  256. Promise.all(promises)
  257. .catch((err) => {
  258. logger.error('Error occured in sending slack notification: ', err);
  259. });
  260. }
  261. };
  262. /**
  263. * @swagger
  264. *
  265. * /comments.update:
  266. * post:
  267. * tags: [Comments, CrowiCompatibles]
  268. * operationId: updateComment
  269. * summary: /comments.update
  270. * description: Update comment dody
  271. * requestBody:
  272. * content:
  273. * application/json:
  274. * schema:
  275. * properties:
  276. * form:
  277. * type: object
  278. * properties:
  279. * commentForm:
  280. * type: object
  281. * properties:
  282. * page_id:
  283. * $ref: '#/components/schemas/Page/properties/_id'
  284. * revision_id:
  285. * $ref: '#/components/schemas/Revision/properties/_id'
  286. * comment:
  287. * $ref: '#/components/schemas/Comment/properties/comment'
  288. * comment_position:
  289. * $ref: '#/components/schemas/Comment/properties/commentPosition'
  290. * required:
  291. * - form
  292. * responses:
  293. * 200:
  294. * description: Succeeded to update comment dody.
  295. * content:
  296. * application/json:
  297. * schema:
  298. * properties:
  299. * ok:
  300. * $ref: '#/components/schemas/V1Response/properties/ok'
  301. * comment:
  302. * $ref: '#/components/schemas/Comment'
  303. * 403:
  304. * $ref: '#/components/responses/403'
  305. * 500:
  306. * $ref: '#/components/responses/500'
  307. */
  308. /**
  309. * @api {post} /comments.update Update comment dody
  310. * @apiName UpdateComment
  311. * @apiGroup Comment
  312. */
  313. api.update = async function(req, res) {
  314. const { commentForm } = req.body;
  315. const pageId = commentForm.page_id;
  316. const comment = commentForm.comment;
  317. const isMarkdown = commentForm.is_markdown;
  318. const commentId = commentForm.comment_id;
  319. const author = commentForm.author;
  320. if (comment === '') {
  321. return res.json(ApiResponse.error('Comment text is required'));
  322. }
  323. if (commentId == null) {
  324. return res.json(ApiResponse.error('\'comment_id\' is undefined'));
  325. }
  326. if (author !== req.user.username) {
  327. return res.json(ApiResponse.error('Only the author can edit'));
  328. }
  329. // check whether accessible
  330. const isAccessible = await Page.isAccessiblePageByViewer(pageId, req.user);
  331. if (!isAccessible) {
  332. return res.json(ApiResponse.error('Current user is not accessible to this page.'));
  333. }
  334. let updatedComment;
  335. try {
  336. updatedComment = await Comment.updateCommentsByPageId(comment, isMarkdown, commentId);
  337. }
  338. catch (err) {
  339. logger.error(err);
  340. return res.json(ApiResponse.error(err));
  341. }
  342. res.json(ApiResponse.success({ comment: updatedComment }));
  343. // process notification if needed
  344. };
  345. /**
  346. * @swagger
  347. *
  348. * /comments.remove:
  349. * post:
  350. * tags: [Comments, CrowiCompatibles]
  351. * operationId: removeComment
  352. * summary: /comments.remove
  353. * description: Remove specified comment
  354. * requestBody:
  355. * content:
  356. * application/json:
  357. * schema:
  358. * properties:
  359. * comment_id:
  360. * $ref: '#/components/schemas/Comment/properties/_id'
  361. * required:
  362. * - comment_id
  363. * responses:
  364. * 200:
  365. * description: Succeeded to remove specified comment.
  366. * content:
  367. * application/json:
  368. * schema:
  369. * properties:
  370. * ok:
  371. * $ref: '#/components/schemas/V1Response/properties/ok'
  372. * comment:
  373. * $ref: '#/components/schemas/Comment'
  374. * 403:
  375. * $ref: '#/components/responses/403'
  376. * 500:
  377. * $ref: '#/components/responses/500'
  378. */
  379. /**
  380. * @api {post} /comments.remove Remove specified comment
  381. * @apiName RemoveComment
  382. * @apiGroup Comment
  383. *
  384. * @apiParam {String} comment_id Comment Id.
  385. */
  386. api.remove = async function(req, res) {
  387. const commentId = req.body.comment_id;
  388. if (!commentId) {
  389. return Promise.resolve(res.json(ApiResponse.error('\'comment_id\' is undefined')));
  390. }
  391. try {
  392. const comment = await Comment.findById(commentId).exec();
  393. if (comment == null) {
  394. throw new Error('This comment does not exist.');
  395. }
  396. // check whether accessible
  397. const pageId = comment.page;
  398. const isAccessible = await Page.isAccessiblePageByViewer(pageId, req.user);
  399. if (!isAccessible) {
  400. throw new Error('Current user is not accessible to this page.');
  401. }
  402. await comment.removeWithReplies();
  403. await Page.updateCommentCount(comment.page);
  404. }
  405. catch (err) {
  406. return res.json(ApiResponse.error(err));
  407. }
  408. return res.json(ApiResponse.success({}));
  409. };
  410. return actions;
  411. };