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