]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/comment.ts
44d64776c60a351232c4ea9b3cf547a2f3c28b81
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / comment.ts
1 import express from 'express'
2 import { ResultList, ThreadsResultList, UserRight, VideoCommentCreate } from '../../../../shared/models'
3 import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes'
4 import { VideoCommentThreads } from '../../../../shared/models/videos/comment/video-comment.model'
5 import { auditLoggerFactory, CommentAuditView, getAuditIdFromRes } from '../../../helpers/audit-logger'
6 import { getFormattedObjects } from '../../../helpers/utils'
7 import { sequelizeTypescript } from '../../../initializers/database'
8 import { Notifier } from '../../../lib/notifier'
9 import { Hooks } from '../../../lib/plugins/hooks'
10 import { buildFormattedCommentTree, createVideoComment, removeComment } from '../../../lib/video-comment'
11 import {
12 asyncMiddleware,
13 asyncRetryTransactionMiddleware,
14 authenticate,
15 ensureUserHasRight,
16 optionalAuthenticate,
17 paginationValidator,
18 setDefaultPagination,
19 setDefaultSort
20 } from '../../../middlewares'
21 import {
22 addVideoCommentReplyValidator,
23 addVideoCommentThreadValidator,
24 listVideoCommentsValidator,
25 listVideoCommentThreadsValidator,
26 listVideoThreadCommentsValidator,
27 removeVideoCommentValidator,
28 videoCommentsValidator,
29 videoCommentThreadsSortValidator
30 } from '../../../middlewares/validators'
31 import { AccountModel } from '../../../models/account/account'
32 import { VideoCommentModel } from '../../../models/video/video-comment'
33
34 const auditLogger = auditLoggerFactory('comments')
35 const videoCommentRouter = express.Router()
36
37 videoCommentRouter.get('/:videoId/comment-threads',
38 paginationValidator,
39 videoCommentThreadsSortValidator,
40 setDefaultSort,
41 setDefaultPagination,
42 asyncMiddleware(listVideoCommentThreadsValidator),
43 optionalAuthenticate,
44 asyncMiddleware(listVideoThreads)
45 )
46 videoCommentRouter.get('/:videoId/comment-threads/:threadId',
47 asyncMiddleware(listVideoThreadCommentsValidator),
48 optionalAuthenticate,
49 asyncMiddleware(listVideoThreadComments)
50 )
51
52 videoCommentRouter.post('/:videoId/comment-threads',
53 authenticate,
54 asyncMiddleware(addVideoCommentThreadValidator),
55 asyncRetryTransactionMiddleware(addVideoCommentThread)
56 )
57 videoCommentRouter.post('/:videoId/comments/:commentId',
58 authenticate,
59 asyncMiddleware(addVideoCommentReplyValidator),
60 asyncRetryTransactionMiddleware(addVideoCommentReply)
61 )
62 videoCommentRouter.delete('/:videoId/comments/:commentId',
63 authenticate,
64 asyncMiddleware(removeVideoCommentValidator),
65 asyncRetryTransactionMiddleware(removeVideoComment)
66 )
67
68 videoCommentRouter.get('/comments',
69 authenticate,
70 ensureUserHasRight(UserRight.SEE_ALL_COMMENTS),
71 paginationValidator,
72 videoCommentsValidator,
73 setDefaultSort,
74 setDefaultPagination,
75 listVideoCommentsValidator,
76 asyncMiddleware(listComments)
77 )
78
79 // ---------------------------------------------------------------------------
80
81 export {
82 videoCommentRouter
83 }
84
85 // ---------------------------------------------------------------------------
86
87 async function listComments (req: express.Request, res: express.Response) {
88 const options = {
89 start: req.query.start,
90 count: req.query.count,
91 sort: req.query.sort,
92
93 isLocal: req.query.isLocal,
94 onLocalVideo: req.query.onLocalVideo,
95 search: req.query.search,
96 searchAccount: req.query.searchAccount,
97 searchVideo: req.query.searchVideo
98 }
99
100 const resultList = await VideoCommentModel.listCommentsForApi(options)
101
102 return res.json({
103 total: resultList.total,
104 data: resultList.data.map(c => c.toFormattedAdminJSON())
105 })
106 }
107
108 async function listVideoThreads (req: express.Request, res: express.Response) {
109 const video = res.locals.onlyVideo
110 const user = res.locals.oauth ? res.locals.oauth.token.User : undefined
111
112 let resultList: ThreadsResultList<VideoCommentModel>
113
114 if (video.commentsEnabled === true) {
115 const apiOptions = await Hooks.wrapObject({
116 videoId: video.id,
117 isVideoOwned: video.isOwned(),
118 start: req.query.start,
119 count: req.query.count,
120 sort: req.query.sort,
121 user
122 }, 'filter:api.video-threads.list.params')
123
124 resultList = await Hooks.wrapPromiseFun(
125 VideoCommentModel.listThreadsForApi,
126 apiOptions,
127 'filter:api.video-threads.list.result'
128 )
129 } else {
130 resultList = {
131 total: 0,
132 totalNotDeletedComments: 0,
133 data: []
134 }
135 }
136
137 return res.json({
138 ...getFormattedObjects(resultList.data, resultList.total),
139 totalNotDeletedComments: resultList.totalNotDeletedComments
140 } as VideoCommentThreads)
141 }
142
143 async function listVideoThreadComments (req: express.Request, res: express.Response) {
144 const video = res.locals.onlyVideo
145 const user = res.locals.oauth ? res.locals.oauth.token.User : undefined
146
147 let resultList: ResultList<VideoCommentModel>
148
149 if (video.commentsEnabled === true) {
150 const apiOptions = await Hooks.wrapObject({
151 videoId: video.id,
152 isVideoOwned: video.isOwned(),
153 threadId: res.locals.videoCommentThread.id,
154 user
155 }, 'filter:api.video-thread-comments.list.params')
156
157 resultList = await Hooks.wrapPromiseFun(
158 VideoCommentModel.listThreadCommentsForApi,
159 apiOptions,
160 'filter:api.video-thread-comments.list.result'
161 )
162 } else {
163 resultList = {
164 total: 0,
165 data: []
166 }
167 }
168
169 if (resultList.data.length === 0) {
170 return res.fail({
171 status: HttpStatusCode.NOT_FOUND_404,
172 message: 'No comments were found'
173 })
174 }
175
176 return res.json(buildFormattedCommentTree(resultList))
177 }
178
179 async function addVideoCommentThread (req: express.Request, res: express.Response) {
180 const videoCommentInfo: VideoCommentCreate = req.body
181
182 const comment = await sequelizeTypescript.transaction(async t => {
183 const account = await AccountModel.load(res.locals.oauth.token.User.Account.id, t)
184
185 return createVideoComment({
186 text: videoCommentInfo.text,
187 inReplyToComment: null,
188 video: res.locals.videoAll,
189 account
190 }, t)
191 })
192
193 Notifier.Instance.notifyOnNewComment(comment)
194 auditLogger.create(getAuditIdFromRes(res), new CommentAuditView(comment.toFormattedJSON()))
195
196 Hooks.runAction('action:api.video-thread.created', { comment, req, res })
197
198 return res.json({ comment: comment.toFormattedJSON() })
199 }
200
201 async function addVideoCommentReply (req: express.Request, res: express.Response) {
202 const videoCommentInfo: VideoCommentCreate = req.body
203
204 const comment = await sequelizeTypescript.transaction(async t => {
205 const account = await AccountModel.load(res.locals.oauth.token.User.Account.id, t)
206
207 return createVideoComment({
208 text: videoCommentInfo.text,
209 inReplyToComment: res.locals.videoCommentFull,
210 video: res.locals.videoAll,
211 account
212 }, t)
213 })
214
215 Notifier.Instance.notifyOnNewComment(comment)
216 auditLogger.create(getAuditIdFromRes(res), new CommentAuditView(comment.toFormattedJSON()))
217
218 Hooks.runAction('action:api.video-comment-reply.created', { comment, req, res })
219
220 return res.json({ comment: comment.toFormattedJSON() })
221 }
222
223 async function removeVideoComment (req: express.Request, res: express.Response) {
224 const videoCommentInstance = res.locals.videoCommentFull
225
226 await removeComment(videoCommentInstance, req, res)
227
228 auditLogger.delete(getAuditIdFromRes(res), new CommentAuditView(videoCommentInstance.toFormattedJSON()))
229
230 return res.type('json')
231 .status(HttpStatusCode.NO_CONTENT_204)
232 .end()
233 }