Upgrade express validator to v4
[oweals/peertube.git] / server / middlewares / validators / videos.ts
1 import { body, param, query } from 'express-validator/check'
2 import * as express from 'express'
3 import * as Promise from 'bluebird'
4 import * as validator from 'validator'
5
6 import { database as db } from '../../initializers/database'
7 import { checkErrors } from './utils'
8 import { CONSTRAINTS_FIELDS, SEARCHABLE_COLUMNS } from '../../initializers'
9 import {
10   logger,
11   isVideoDurationValid,
12   isVideoFile,
13   isVideoNameValid,
14   isVideoCategoryValid,
15   isVideoLicenceValid,
16   isVideoDescriptionValid,
17   isVideoLanguageValid,
18   isVideoTagsValid,
19   isVideoNSFWValid,
20   isVideoIdOrUUIDValid,
21   isVideoAbuseReasonValid,
22   isVideoRatingTypeValid
23 } from '../../helpers'
24 import { VideoInstance } from '../../models'
25
26 const videosAddValidator = [
27   body('videofile').custom((value, { req }) => isVideoFile(req.files)).withMessage('Should have a valid file'),
28   body('name').custom(isVideoNameValid).withMessage('Should have a valid name'),
29   body('category').custom(isVideoCategoryValid).withMessage('Should have a valid category'),
30   body('licence').custom(isVideoLicenceValid).withMessage('Should have a valid licence'),
31   body('language').optional().custom(isVideoLanguageValid).withMessage('Should have a valid language'),
32   body('nsfw').custom(isVideoNSFWValid).withMessage('Should have a valid NSFW attribute'),
33   body('description').custom(isVideoDescriptionValid).withMessage('Should have a valid description'),
34   body('tags').optional().custom(isVideoTagsValid).withMessage('Should have correct tags'),
35
36   (req: express.Request, res: express.Response, next: express.NextFunction) => {
37     logger.debug('Checking videosAdd parameters', { parameters: req.body, files: req.files })
38
39     checkErrors(req, res, () => {
40       const videoFile: Express.Multer.File = req.files['videofile'][0]
41       const user = res.locals.oauth.token.User
42
43       user.isAbleToUploadVideo(videoFile)
44         .then(isAble => {
45           if (isAble === false) {
46             res.status(403)
47                .json({ error: 'The user video quota is exceeded with this video.' })
48                .end()
49
50             return undefined
51           }
52
53           return db.Video.getDurationFromFile(videoFile.path)
54             .catch(err => {
55               logger.error('Invalid input file in videosAddValidator.', err)
56               res.status(400)
57                  .json({ error: 'Invalid input file.' })
58                  .end()
59
60               return undefined
61             })
62         })
63         .then(duration => {
64           // Previous test failed, abort
65           if (duration === undefined) return
66
67           if (!isVideoDurationValid('' + duration)) {
68             return res.status(400)
69                       .json({
70                         error: 'Duration of the video file is too big (max: ' + CONSTRAINTS_FIELDS.VIDEOS.DURATION.max + 's).'
71                       })
72                       .end()
73           }
74
75           videoFile['duration'] = duration
76           next()
77         })
78         .catch(err => {
79           logger.error('Error in video add validator', err)
80           res.sendStatus(500)
81
82           return undefined
83         })
84     })
85   }
86 ]
87
88 const videosUpdateValidator = [
89   param('id').custom(isVideoIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'),
90   body('name').optional().custom(isVideoNameValid).withMessage('Should have a valid name'),
91   body('category').optional().custom(isVideoCategoryValid).withMessage('Should have a valid category'),
92   body('licence').optional().custom(isVideoLicenceValid).withMessage('Should have a valid licence'),
93   body('language').optional().custom(isVideoLanguageValid).withMessage('Should have a valid language'),
94   body('nsfw').optional().custom(isVideoNSFWValid).withMessage('Should have a valid NSFW attribute'),
95   body('description').optional().custom(isVideoDescriptionValid).withMessage('Should have a valid description'),
96   body('tags').optional().custom(isVideoTagsValid).withMessage('Should have correct tags'),
97
98   (req: express.Request, res: express.Response, next: express.NextFunction) => {
99     logger.debug('Checking videosUpdate parameters', { parameters: req.body })
100
101     checkErrors(req, res, () => {
102       checkVideoExists(req.params.id, res, () => {
103         // We need to make additional checks
104         if (res.locals.video.isOwned() === false) {
105           return res.status(403)
106                     .json({ error: 'Cannot update video of another pod' })
107                     .end()
108         }
109
110         if (res.locals.video.Author.userId !== res.locals.oauth.token.User.id) {
111           return res.status(403)
112                     .json({ error: 'Cannot update video of another user' })
113                     .end()
114         }
115
116         next()
117       })
118     })
119   }
120 ]
121
122 const videosGetValidator = [
123   param('id').custom(isVideoIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'),
124
125   (req: express.Request, res: express.Response, next: express.NextFunction) => {
126     logger.debug('Checking videosGet parameters', { parameters: req.params })
127
128     checkErrors(req, res, () => {
129       checkVideoExists(req.params.id, res, next)
130     })
131   }
132 ]
133
134 const videosRemoveValidator = [
135   param('id').custom(isVideoIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'),
136
137   (req: express.Request, res: express.Response, next: express.NextFunction) => {
138     logger.debug('Checking videosRemove parameters', { parameters: req.params })
139
140     checkErrors(req, res, () => {
141       checkVideoExists(req.params.id, res, () => {
142         // Check if the user who did the request is able to delete the video
143         checkUserCanDeleteVideo(res.locals.oauth.token.User.id, res, () => {
144           next()
145         })
146       })
147     })
148   }
149 ]
150
151 const videosSearchValidator = [
152   param('value').not().isEmpty().withMessage('Should have a valid search'),
153   query('field').optional().isIn(SEARCHABLE_COLUMNS.VIDEOS).withMessage('Should have correct searchable column'),
154
155   (req: express.Request, res: express.Response, next: express.NextFunction) => {
156     logger.debug('Checking videosSearch parameters', { parameters: req.params })
157
158     checkErrors(req, res, next)
159   }
160 ]
161
162 const videoAbuseReportValidator = [
163   param('id').custom(isVideoIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'),
164   body('reason').custom(isVideoAbuseReasonValid).withMessage('Should have a valid reason'),
165
166   (req: express.Request, res: express.Response, next: express.NextFunction) => {
167     logger.debug('Checking videoAbuseReport parameters', { parameters: req.body })
168
169     checkErrors(req, res, () => {
170       checkVideoExists(req.params.id, res, next)
171     })
172   }
173 ]
174
175 const videoRateValidator = [
176   param('id').custom(isVideoIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'),
177   body('rating').custom(isVideoRatingTypeValid).withMessage('Should have a valid rate type'),
178
179   (req: express.Request, res: express.Response, next: express.NextFunction) => {
180     logger.debug('Checking videoRate parameters', { parameters: req.body })
181
182     checkErrors(req, res, () => {
183       checkVideoExists(req.params.id, res, next)
184     })
185   }
186 ]
187
188 const videosBlacklistValidator = [
189   param('id').custom(isVideoIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'),
190
191   (req: express.Request, res: express.Response, next: express.NextFunction) => {
192     logger.debug('Checking videosBlacklist parameters', { parameters: req.params })
193
194     checkErrors(req, res, () => {
195       checkVideoExists(req.params.id, res, () => {
196         checkVideoIsBlacklistable(req, res, next)
197       })
198     })
199   }
200 ]
201
202 // ---------------------------------------------------------------------------
203
204 export {
205   videosAddValidator,
206   videosUpdateValidator,
207   videosGetValidator,
208   videosRemoveValidator,
209   videosSearchValidator,
210
211   videoAbuseReportValidator,
212
213   videoRateValidator,
214
215   videosBlacklistValidator
216 }
217
218 // ---------------------------------------------------------------------------
219
220 function checkVideoExists (id: string, res: express.Response, callback: () => void) {
221   let promise: Promise<VideoInstance>
222   if (validator.isInt(id)) {
223     promise = db.Video.loadAndPopulateAuthorAndPodAndTags(+id)
224   } else { // UUID
225     promise = db.Video.loadByUUIDAndPopulateAuthorAndPodAndTags(id)
226   }
227
228   promise.then(video => {
229     if (!video) {
230       return res.status(404)
231                 .json({ error: 'Video not found' })
232                 .end()
233     }
234
235     res.locals.video = video
236     callback()
237   })
238   .catch(err => {
239     logger.error('Error in video request validator.', err)
240     return res.sendStatus(500)
241   })
242 }
243
244 function checkUserCanDeleteVideo (userId: number, res: express.Response, callback: () => void) {
245   // Retrieve the user who did the request
246   db.User.loadById(userId)
247     .then(user => {
248       if (res.locals.video.isOwned() === false) {
249         return res.status(403)
250                   .json({ error: 'Cannot remove video of another pod, blacklist it' })
251                   .end()
252       }
253
254       // Check if the user can delete the video
255       // The user can delete it if s/he is an admin
256       // Or if s/he is the video's author
257       if (user.isAdmin() === false && res.locals.video.Author.userId !== res.locals.oauth.token.User.id) {
258         return res.status(403)
259                   .json({ error: 'Cannot remove video of another user' })
260                   .end()
261       }
262
263       // If we reach this comment, we can delete the video
264       callback()
265     })
266     .catch(err => {
267       logger.error('Error in video request validator.', err)
268       return res.sendStatus(500)
269     })
270 }
271
272 function checkVideoIsBlacklistable (req: express.Request, res: express.Response, callback: () => void) {
273   if (res.locals.video.isOwned() === true) {
274     return res.status(403)
275               .json({ error: 'Cannot blacklist a local video' })
276               .end()
277   }
278
279   callback()
280 }