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