]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/middlewares/validators/videos.ts
Fix lint
[github/Chocobozzz/PeerTube.git] / server / middlewares / validators / videos.ts
1 import * as express from 'express'
2 import 'express-validator'
3 import { body, param, query } from 'express-validator/check'
4 import { UserRight, VideoPrivacy } from '../../../shared'
5 import { isBooleanValid, isIdOrUUIDValid, isIdValid, isUUIDValid } from '../../helpers/custom-validators/misc'
6 import {
7 isVideoAbuseReasonValid,
8 isVideoCategoryValid,
9 isVideoDescriptionValid,
10 isVideoExist,
11 isVideoFile,
12 isVideoImage,
13 isVideoLanguageValid,
14 isVideoLicenceValid,
15 isVideoNameValid,
16 isVideoPrivacyValid,
17 isVideoRatingTypeValid, isVideoSupportValid,
18 isVideoTagsValid
19 } from '../../helpers/custom-validators/videos'
20 import { getDurationFromVideoFile } from '../../helpers/ffmpeg-utils'
21 import { logger } from '../../helpers/logger'
22 import { CONSTRAINTS_FIELDS } from '../../initializers'
23 import { UserModel } from '../../models/account/user'
24 import { VideoModel } from '../../models/video/video'
25 import { VideoChannelModel } from '../../models/video/video-channel'
26 import { VideoShareModel } from '../../models/video/video-share'
27 import { authenticate } from '../oauth'
28 import { areValidationErrors } from './utils'
29
30 const videosAddValidator = [
31 body('videofile').custom((value, { req }) => isVideoFile(req.files)).withMessage(
32 'This file is not supported. Please, make sure it is of the following type : '
33 + CONSTRAINTS_FIELDS.VIDEOS.EXTNAME.join(', ')
34 ),
35 body('thumbnailfile').custom((value, { req }) => isVideoImage(req.files, 'thumbnailfile')).withMessage(
36 'This thumbnail file is not supported. Please, make sure it is of the following type : '
37 + CONSTRAINTS_FIELDS.VIDEOS.IMAGE.EXTNAME.join(', ')
38 ),
39 body('previewfile').custom((value, { req }) => isVideoImage(req.files, 'previewfile')).withMessage(
40 'This preview file is not supported. Please, make sure it is of the following type : '
41 + CONSTRAINTS_FIELDS.VIDEOS.IMAGE.EXTNAME.join(', ')
42 ),
43 body('name').custom(isVideoNameValid).withMessage('Should have a valid name'),
44 body('category').optional().custom(isVideoCategoryValid).withMessage('Should have a valid category'),
45 body('licence').optional().custom(isVideoLicenceValid).withMessage('Should have a valid licence'),
46 body('language').optional().custom(isVideoLanguageValid).withMessage('Should have a valid language'),
47 body('nsfw').custom(isBooleanValid).withMessage('Should have a valid NSFW attribute'),
48 body('description').optional().custom(isVideoDescriptionValid).withMessage('Should have a valid description'),
49 body('support').optional().custom(isVideoSupportValid).withMessage('Should have a valid support text'),
50 body('channelId').custom(isIdValid).withMessage('Should have correct video channel id'),
51 body('privacy').custom(isVideoPrivacyValid).withMessage('Should have correct video privacy'),
52 body('tags').optional().custom(isVideoTagsValid).withMessage('Should have correct tags'),
53 body('commentsEnabled').custom(isBooleanValid).withMessage('Should have comments enabled boolean'),
54
55 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
56 logger.debug('Checking videosAdd parameters', { parameters: req.body, files: req.files })
57
58 if (areValidationErrors(req, res)) return
59 if (areErrorsInVideoImageFiles(req, res)) return
60
61 const videoFile: Express.Multer.File = req.files['videofile'][0]
62 const user = res.locals.oauth.token.User
63
64 const videoChannel = await VideoChannelModel.loadByIdAndAccount(req.body.channelId, user.Account.id)
65 if (!videoChannel) {
66 res.status(400)
67 .json({ error: 'Unknown video video channel for this account.' })
68 .end()
69
70 return
71 }
72
73 res.locals.videoChannel = videoChannel
74
75 const isAble = await user.isAbleToUploadVideo(videoFile)
76 if (isAble === false) {
77 res.status(403)
78 .json({ error: 'The user video quota is exceeded with this video.' })
79 .end()
80
81 return
82 }
83
84 let duration: number
85
86 try {
87 duration = await getDurationFromVideoFile(videoFile.path)
88 } catch (err) {
89 logger.error('Invalid input file in videosAddValidator.', err)
90 res.status(400)
91 .json({ error: 'Invalid input file.' })
92 .end()
93
94 return
95 }
96
97 videoFile['duration'] = duration
98
99 return next()
100 }
101 ]
102
103 const videosUpdateValidator = [
104 param('id').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'),
105 body('thumbnailfile').custom((value, { req }) => isVideoImage(req.files, 'thumbnailfile')).withMessage(
106 'This thumbnail file is not supported. Please, make sure it is of the following type : '
107 + CONSTRAINTS_FIELDS.VIDEOS.IMAGE.EXTNAME.join(', ')
108 ),
109 body('previewfile').custom((value, { req }) => isVideoImage(req.files, 'previewfile')).withMessage(
110 'This preview file is not supported. Please, make sure it is of the following type : '
111 + CONSTRAINTS_FIELDS.VIDEOS.IMAGE.EXTNAME.join(', ')
112 ),
113 body('name').optional().custom(isVideoNameValid).withMessage('Should have a valid name'),
114 body('category').optional().custom(isVideoCategoryValid).withMessage('Should have a valid category'),
115 body('licence').optional().custom(isVideoLicenceValid).withMessage('Should have a valid licence'),
116 body('language').optional().custom(isVideoLanguageValid).withMessage('Should have a valid language'),
117 body('nsfw').optional().custom(isBooleanValid).withMessage('Should have a valid NSFW attribute'),
118 body('privacy').optional().custom(isVideoPrivacyValid).withMessage('Should have correct video privacy'),
119 body('description').optional().custom(isVideoDescriptionValid).withMessage('Should have a valid description'),
120 body('support').optional().custom(isVideoSupportValid).withMessage('Should have a valid support text'),
121 body('tags').optional().custom(isVideoTagsValid).withMessage('Should have correct tags'),
122 body('commentsEnabled').optional().custom(isBooleanValid).withMessage('Should have comments enabled boolean'),
123
124 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
125 logger.debug('Checking videosUpdate parameters', { parameters: req.body })
126
127 if (areValidationErrors(req, res)) return
128 if (areErrorsInVideoImageFiles(req, res)) return
129 if (!await isVideoExist(req.params.id, res)) return
130
131 const video = res.locals.video
132
133 // We need to make additional checks
134 if (video.isOwned() === false) {
135 return res.status(403)
136 .json({ error: 'Cannot update video of another server' })
137 .end()
138 }
139
140 if (video.VideoChannel.Account.userId !== res.locals.oauth.token.User.id) {
141 return res.status(403)
142 .json({ error: 'Cannot update video of another user' })
143 .end()
144 }
145
146 if (video.privacy !== VideoPrivacy.PRIVATE && req.body.privacy === VideoPrivacy.PRIVATE) {
147 return res.status(409)
148 .json({ error: 'Cannot set "private" a video that was not private anymore.' })
149 .end()
150 }
151
152 return next()
153 }
154 ]
155
156 const videosGetValidator = [
157 param('id').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'),
158
159 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
160 logger.debug('Checking videosGet parameters', { parameters: req.params })
161
162 if (areValidationErrors(req, res)) return
163 if (!await isVideoExist(req.params.id, res)) return
164
165 const video = res.locals.video
166
167 // Video is public, anyone can access it
168 if (video.privacy === VideoPrivacy.PUBLIC) return next()
169
170 // Video is unlisted, check we used the uuid to fetch it
171 if (video.privacy === VideoPrivacy.UNLISTED) {
172 if (isUUIDValid(req.params.id)) return next()
173
174 // Don't leak this unlisted video
175 return res.status(404).end()
176 }
177
178 // Video is private, check the user
179 authenticate(req, res, () => {
180 if (video.VideoChannel.Account.userId !== res.locals.oauth.token.User.id) {
181 return res.status(403)
182 .json({ error: 'Cannot get this private video of another user' })
183 .end()
184 }
185
186 return next()
187 })
188 }
189 ]
190
191 const videosRemoveValidator = [
192 param('id').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'),
193
194 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
195 logger.debug('Checking videosRemove parameters', { parameters: req.params })
196
197 if (areValidationErrors(req, res)) return
198 if (!await isVideoExist(req.params.id, res)) return
199
200 // Check if the user who did the request is able to delete the video
201 if (!checkUserCanDeleteVideo(res.locals.oauth.token.User, res.locals.video, res)) return
202
203 return next()
204 }
205 ]
206
207 const videosSearchValidator = [
208 query('search').not().isEmpty().withMessage('Should have a valid search'),
209
210 (req: express.Request, res: express.Response, next: express.NextFunction) => {
211 logger.debug('Checking videosSearch parameters', { parameters: req.params })
212
213 if (areValidationErrors(req, res)) return
214
215 return next()
216 }
217 ]
218
219 const videoAbuseReportValidator = [
220 param('id').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'),
221 body('reason').custom(isVideoAbuseReasonValid).withMessage('Should have a valid reason'),
222
223 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
224 logger.debug('Checking videoAbuseReport parameters', { parameters: req.body })
225
226 if (areValidationErrors(req, res)) return
227 if (!await isVideoExist(req.params.id, res)) return
228
229 return next()
230 }
231 ]
232
233 const videoRateValidator = [
234 param('id').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'),
235 body('rating').custom(isVideoRatingTypeValid).withMessage('Should have a valid rate type'),
236
237 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
238 logger.debug('Checking videoRate parameters', { parameters: req.body })
239
240 if (areValidationErrors(req, res)) return
241 if (!await isVideoExist(req.params.id, res)) return
242
243 return next()
244 }
245 ]
246
247 const videosShareValidator = [
248 param('id').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'),
249 param('accountId').custom(isIdValid).not().isEmpty().withMessage('Should have a valid account id'),
250
251 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
252 logger.debug('Checking videoShare parameters', { parameters: req.params })
253
254 if (areValidationErrors(req, res)) return
255 if (!await isVideoExist(req.params.id, res)) return
256
257 const share = await VideoShareModel.load(req.params.accountId, res.locals.video.id, undefined)
258 if (!share) {
259 return res.status(404)
260 .end()
261 }
262
263 res.locals.videoShare = share
264 return next()
265 }
266 ]
267
268 // ---------------------------------------------------------------------------
269
270 export {
271 videosAddValidator,
272 videosUpdateValidator,
273 videosGetValidator,
274 videosRemoveValidator,
275 videosSearchValidator,
276 videosShareValidator,
277
278 videoAbuseReportValidator,
279
280 videoRateValidator
281 }
282
283 // ---------------------------------------------------------------------------
284
285 function checkUserCanDeleteVideo (user: UserModel, video: VideoModel, res: express.Response) {
286 // Retrieve the user who did the request
287 if (video.isOwned() === false) {
288 res.status(403)
289 .json({ error: 'Cannot remove video of another server, blacklist it' })
290 .end()
291 return false
292 }
293
294 // Check if the user can delete the video
295 // The user can delete it if he has the right
296 // Or if s/he is the video's account
297 const account = video.VideoChannel.Account
298 if (user.hasRight(UserRight.REMOVE_ANY_VIDEO) === false && account.userId !== user.id) {
299 res.status(403)
300 .json({ error: 'Cannot remove video of another user' })
301 .end()
302 return false
303 }
304
305 return true
306 }
307
308 function areErrorsInVideoImageFiles (req: express.Request, res: express.Response) {
309 // Files are optional
310 if (!req.files) return false
311
312 for (const imageField of [ 'thumbnail', 'preview' ]) {
313 if (!req.files[ imageField ]) continue
314
315 const imageFile = req.files[ imageField ][ 0 ] as Express.Multer.File
316 if (imageFile.size > CONSTRAINTS_FIELDS.VIDEOS.IMAGE.FILE_SIZE.max) {
317 res.status(400)
318 .send({ error: `The size of the ${imageField} is too big (>${CONSTRAINTS_FIELDS.VIDEOS.IMAGE.FILE_SIZE.max}).` })
319 .end()
320 return true
321 }
322 }
323
324 return false
325 }