Move models to typescript-sequelize
[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 { getDurationFromVideoFile, logger } from '../../helpers'
6 import { isIdOrUUIDValid, isIdValid } from '../../helpers/custom-validators/misc'
7 import {
8   isVideoAbuseReasonValid,
9   isVideoCategoryValid,
10   isVideoDescriptionValid,
11   isVideoExist,
12   isVideoFile,
13   isVideoLanguageValid,
14   isVideoLicenceValid,
15   isVideoNameValid,
16   isVideoNSFWValid,
17   isVideoPrivacyValid,
18   isVideoRatingTypeValid,
19   isVideoTagsValid
20 } from '../../helpers/custom-validators/videos'
21 import { CONSTRAINTS_FIELDS } from '../../initializers'
22 import { UserModel } from '../../models/account/user'
23 import { VideoModel } from '../../models/video/video'
24 import { VideoChannelModel } from '../../models/video/video-channel'
25 import { VideoShareModel } from '../../models/video/video-share'
26 import { authenticate } from '../oauth'
27 import { areValidationErrors } from './utils'
28
29 const videosAddValidator = [
30   body('videofile').custom((value, { req }) => isVideoFile(req.files)).withMessage(
31     'This file is not supported. Please, make sure it is of the following type : '
32     + CONSTRAINTS_FIELDS.VIDEOS.EXTNAME.join(', ')
33   ),
34   body('name').custom(isVideoNameValid).withMessage('Should have a valid name'),
35   body('category').optional().custom(isVideoCategoryValid).withMessage('Should have a valid category'),
36   body('licence').optional().custom(isVideoLicenceValid).withMessage('Should have a valid licence'),
37   body('language').optional().custom(isVideoLanguageValid).withMessage('Should have a valid language'),
38   body('nsfw').custom(isVideoNSFWValid).withMessage('Should have a valid NSFW attribute'),
39   body('description').optional().custom(isVideoDescriptionValid).withMessage('Should have a valid description'),
40   body('channelId').custom(isIdValid).withMessage('Should have correct video channel id'),
41   body('privacy').custom(isVideoPrivacyValid).withMessage('Should have correct video privacy'),
42   body('tags').optional().custom(isVideoTagsValid).withMessage('Should have correct tags'),
43
44   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
45     logger.debug('Checking videosAdd parameters', { parameters: req.body, files: req.files })
46
47     if (areValidationErrors(req, res)) return
48
49     const videoFile: Express.Multer.File = req.files['videofile'][0]
50     const user = res.locals.oauth.token.User
51
52     const videoChannel = await VideoChannelModel.loadByIdAndAccount(req.body.channelId, user.Account.id)
53     if (!videoChannel) {
54       res.status(400)
55         .json({ error: 'Unknown video video channel for this account.' })
56         .end()
57
58       return
59     }
60
61     res.locals.videoChannel = videoChannel
62
63     const isAble = await user.isAbleToUploadVideo(videoFile)
64     if (isAble === false) {
65       res.status(403)
66          .json({ error: 'The user video quota is exceeded with this video.' })
67          .end()
68
69       return
70     }
71
72     let duration: number
73
74     try {
75       duration = await getDurationFromVideoFile(videoFile.path)
76     } catch (err) {
77       logger.error('Invalid input file in videosAddValidator.', err)
78       res.status(400)
79          .json({ error: 'Invalid input file.' })
80          .end()
81
82       return
83     }
84
85     videoFile['duration'] = duration
86
87     return next()
88   }
89 ]
90
91 const videosUpdateValidator = [
92   param('id').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'),
93   body('name').optional().custom(isVideoNameValid).withMessage('Should have a valid name'),
94   body('category').optional().custom(isVideoCategoryValid).withMessage('Should have a valid category'),
95   body('licence').optional().custom(isVideoLicenceValid).withMessage('Should have a valid licence'),
96   body('language').optional().custom(isVideoLanguageValid).withMessage('Should have a valid language'),
97   body('nsfw').optional().custom(isVideoNSFWValid).withMessage('Should have a valid NSFW attribute'),
98   body('privacy').optional().custom(isVideoPrivacyValid).withMessage('Should have correct video privacy'),
99   body('description').optional().custom(isVideoDescriptionValid).withMessage('Should have a valid description'),
100   body('tags').optional().custom(isVideoTagsValid).withMessage('Should have correct tags'),
101
102   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
103     logger.debug('Checking videosUpdate parameters', { parameters: req.body })
104
105     if (areValidationErrors(req, res)) return
106     if (!await isVideoExist(req.params.id, res)) return
107
108     const video = res.locals.video
109
110     // We need to make additional checks
111     if (video.isOwned() === false) {
112       return res.status(403)
113                 .json({ error: 'Cannot update video of another server' })
114                 .end()
115     }
116
117     if (video.VideoChannel.Account.userId !== res.locals.oauth.token.User.id) {
118       return res.status(403)
119                 .json({ error: 'Cannot update video of another user' })
120                 .end()
121     }
122
123     if (video.privacy !== VideoPrivacy.PRIVATE && req.body.privacy === VideoPrivacy.PRIVATE) {
124       return res.status(409)
125         .json({ error: 'Cannot set "private" a video that was not private anymore.' })
126         .end()
127     }
128
129     return next()
130   }
131 ]
132
133 const videosGetValidator = [
134   param('id').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'),
135
136   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
137     logger.debug('Checking videosGet parameters', { parameters: req.params })
138
139     if (areValidationErrors(req, res)) return
140     if (!await isVideoExist(req.params.id, res)) return
141
142     const video = res.locals.video
143
144     // Video is not private, anyone can access it
145     if (video.privacy !== VideoPrivacy.PRIVATE) return next()
146
147     authenticate(req, res, () => {
148       if (video.VideoChannel.Account.userId !== res.locals.oauth.token.User.id) {
149         return res.status(403)
150           .json({ error: 'Cannot get this private video of another user' })
151           .end()
152       }
153
154       return next()
155     })
156   }
157 ]
158
159 const videosRemoveValidator = [
160   param('id').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'),
161
162   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
163     logger.debug('Checking videosRemove parameters', { parameters: req.params })
164
165     if (areValidationErrors(req, res)) return
166     if (!await isVideoExist(req.params.id, res)) return
167
168     // Check if the user who did the request is able to delete the video
169     if (!checkUserCanDeleteVideo(res.locals.oauth.token.User, res.locals.video, res)) return
170
171     return next()
172   }
173 ]
174
175 const videosSearchValidator = [
176   query('search').not().isEmpty().withMessage('Should have a valid search'),
177
178   (req: express.Request, res: express.Response, next: express.NextFunction) => {
179     logger.debug('Checking videosSearch parameters', { parameters: req.params })
180
181     if (areValidationErrors(req, res)) return
182
183     return next()
184   }
185 ]
186
187 const videoAbuseReportValidator = [
188   param('id').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'),
189   body('reason').custom(isVideoAbuseReasonValid).withMessage('Should have a valid reason'),
190
191   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
192     logger.debug('Checking videoAbuseReport parameters', { parameters: req.body })
193
194     if (areValidationErrors(req, res)) return
195     if (!await isVideoExist(req.params.id, res)) return
196
197     return next()
198   }
199 ]
200
201 const videoRateValidator = [
202   param('id').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'),
203   body('rating').custom(isVideoRatingTypeValid).withMessage('Should have a valid rate type'),
204
205   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
206     logger.debug('Checking videoRate parameters', { parameters: req.body })
207
208     if (areValidationErrors(req, res)) return
209     if (!await isVideoExist(req.params.id, res)) return
210
211     return next()
212   }
213 ]
214
215 const videosShareValidator = [
216   param('id').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'),
217   param('accountId').custom(isIdValid).not().isEmpty().withMessage('Should have a valid account id'),
218
219   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
220     logger.debug('Checking videoShare parameters', { parameters: req.params })
221
222     if (areValidationErrors(req, res)) return
223     if (!await isVideoExist(req.params.id, res)) return
224
225     const share = await VideoShareModel.load(req.params.accountId, res.locals.video.id, undefined)
226     if (!share) {
227       return res.status(404)
228         .end()
229     }
230
231     res.locals.videoShare = share
232     return next()
233   }
234 ]
235
236 // ---------------------------------------------------------------------------
237
238 export {
239   videosAddValidator,
240   videosUpdateValidator,
241   videosGetValidator,
242   videosRemoveValidator,
243   videosSearchValidator,
244   videosShareValidator,
245
246   videoAbuseReportValidator,
247
248   videoRateValidator
249 }
250
251 // ---------------------------------------------------------------------------
252
253 function checkUserCanDeleteVideo (user: UserModel, video: VideoModel, res: express.Response) {
254   // Retrieve the user who did the request
255   if (video.isOwned() === false) {
256     res.status(403)
257               .json({ error: 'Cannot remove video of another server, blacklist it' })
258               .end()
259     return false
260   }
261
262   // Check if the user can delete the video
263   // The user can delete it if s/he is an admin
264   // Or if s/he is the video's account
265   const account = video.VideoChannel.Account
266   if (user.hasRight(UserRight.REMOVE_ANY_VIDEO) === false && account.userId !== user.id) {
267     res.status(403)
268               .json({ error: 'Cannot remove video of another user' })
269               .end()
270     return false
271   }
272
273   return true
274 }