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