1 import * as express from 'express'
2 import 'express-validator'
3 import { body, param, query, ValidationChain } from 'express-validator/check'
4 import { UserRight, VideoChangeOwnershipStatus, VideoPrivacy } from '../../../../shared'
14 } from '../../../helpers/custom-validators/misc'
16 checkUserCanManageVideo,
17 isScheduleVideoUpdatePrivacyValid,
19 isVideoChannelOfAccountExist,
20 isVideoDescriptionValid,
31 } from '../../../helpers/custom-validators/videos'
32 import { getDurationFromVideoFile } from '../../../helpers/ffmpeg-utils'
33 import { logger } from '../../../helpers/logger'
34 import { CONSTRAINTS_FIELDS } from '../../../initializers'
35 import { authenticate } from '../../oauth'
36 import { areValidationErrors } from '../utils'
37 import { cleanUpReqFiles } from '../../../helpers/express-utils'
38 import { VideoModel } from '../../../models/video/video'
39 import { UserModel } from '../../../models/account/user'
40 import { checkUserCanTerminateOwnershipChange, doesChangeVideoOwnershipExist } from '../../../helpers/custom-validators/video-ownership'
41 import { VideoChangeOwnershipAccept } from '../../../../shared/models/videos/video-change-ownership-accept.model'
42 import { VideoChangeOwnershipModel } from '../../../models/video/video-change-ownership'
43 import { AccountModel } from '../../../models/account/account'
44 import { VideoFetchType } from '../../../helpers/video'
45 import { isNSFWQueryValid, isNumberArray, isStringArray } from '../../../helpers/custom-validators/search'
47 const videosAddValidator = getCommonVideoAttributes().concat([
49 .custom((value, { req }) => isVideoFile(req.files)).withMessage(
50 'This file is not supported or too large. Please, make sure it is of the following type: '
51 + CONSTRAINTS_FIELDS.VIDEOS.EXTNAME.join(', ')
53 body('name').custom(isVideoNameValid).withMessage('Should have a valid name'),
56 .custom(isIdValid).withMessage('Should have correct video channel id'),
58 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
59 logger.debug('Checking videosAdd parameters', { parameters: req.body, files: req.files })
61 if (areValidationErrors(req, res)) return cleanUpReqFiles(req)
62 if (areErrorsInScheduleUpdate(req, res)) return cleanUpReqFiles(req)
64 const videoFile: Express.Multer.File = req.files['videofile'][0]
65 const user = res.locals.oauth.token.User
67 if (!await isVideoChannelOfAccountExist(req.body.channelId, user, res)) return cleanUpReqFiles(req)
69 const isAble = await user.isAbleToUploadVideo(videoFile)
70 if (isAble === false) {
72 .json({ error: 'The user video quota is exceeded with this video.' })
74 return cleanUpReqFiles(req)
80 duration = await getDurationFromVideoFile(videoFile.path)
82 logger.error('Invalid input file in videosAddValidator.', { err })
84 .json({ error: 'Invalid input file.' })
86 return cleanUpReqFiles(req)
89 videoFile['duration'] = duration
95 const videosUpdateValidator = getCommonVideoAttributes().concat([
96 param('id').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'),
99 .custom(isVideoNameValid).withMessage('Should have a valid name'),
103 .custom(isIdValid).withMessage('Should have correct video channel id'),
105 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
106 logger.debug('Checking videosUpdate parameters', { parameters: req.body })
108 if (areValidationErrors(req, res)) return cleanUpReqFiles(req)
109 if (areErrorsInScheduleUpdate(req, res)) return cleanUpReqFiles(req)
110 if (!await isVideoExist(req.params.id, res)) return cleanUpReqFiles(req)
112 const video = res.locals.video
114 // Check if the user who did the request is able to update the video
115 const user = res.locals.oauth.token.User
116 if (!checkUserCanManageVideo(user, res.locals.video, UserRight.UPDATE_ANY_VIDEO, res)) return cleanUpReqFiles(req)
118 if (video.privacy !== VideoPrivacy.PRIVATE && req.body.privacy === VideoPrivacy.PRIVATE) {
120 return res.status(409)
121 .json({ error: 'Cannot set "private" a video that was not private.' })
124 if (req.body.channelId && !await isVideoChannelOfAccountExist(req.body.channelId, user, res)) return cleanUpReqFiles(req)
130 const videosCustomGetValidator = (fetchType: VideoFetchType) => {
132 param('id').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'),
134 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
135 logger.debug('Checking videosGet parameters', { parameters: req.params })
137 if (areValidationErrors(req, res)) return
138 if (!await isVideoExist(req.params.id, res, fetchType)) return
140 const video: VideoModel = res.locals.video
142 // Video private or blacklisted
143 if (video.privacy === VideoPrivacy.PRIVATE || video.VideoBlacklist) {
144 return authenticate(req, res, () => {
145 const user: UserModel = res.locals.oauth.token.User
147 // Only the owner or a user that have blacklist rights can see the video
148 if (video.VideoChannel.Account.userId !== user.id && !user.hasRight(UserRight.MANAGE_VIDEO_BLACKLIST)) {
149 return res.status(403)
150 .json({ error: 'Cannot get this private or blacklisted video.' })
157 // Video is public, anyone can access it
158 if (video.privacy === VideoPrivacy.PUBLIC) return next()
160 // Video is unlisted, check we used the uuid to fetch it
161 if (video.privacy === VideoPrivacy.UNLISTED) {
162 if (isUUIDValid(req.params.id)) return next()
164 // Don't leak this unlisted video
165 return res.status(404).end()
171 const videosGetValidator = videosCustomGetValidator('all')
173 const videosRemoveValidator = [
174 param('id').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'),
176 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
177 logger.debug('Checking videosRemove parameters', { parameters: req.params })
179 if (areValidationErrors(req, res)) return
180 if (!await isVideoExist(req.params.id, res)) return
182 // Check if the user who did the request is able to delete the video
183 if (!checkUserCanManageVideo(res.locals.oauth.token.User, res.locals.video, UserRight.REMOVE_ANY_VIDEO, res)) return
189 const videosChangeOwnershipValidator = [
190 param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'),
192 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
193 logger.debug('Checking changeOwnership parameters', { parameters: req.params })
195 if (areValidationErrors(req, res)) return
196 if (!await isVideoExist(req.params.videoId, res)) return
198 // Check if the user who did the request is able to change the ownership of the video
199 if (!checkUserCanManageVideo(res.locals.oauth.token.User, res.locals.video, UserRight.CHANGE_VIDEO_OWNERSHIP, res)) return
201 const nextOwner = await AccountModel.loadLocalByName(req.body.username)
204 .json({ error: 'Changing video ownership to a remote account is not supported yet' })
208 res.locals.nextOwner = nextOwner
214 const videosTerminateChangeOwnershipValidator = [
215 param('id').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'),
217 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
218 logger.debug('Checking changeOwnership parameters', { parameters: req.params })
220 if (areValidationErrors(req, res)) return
221 if (!await doesChangeVideoOwnershipExist(req.params.id, res)) return
223 // Check if the user who did the request is able to change the ownership of the video
224 if (!checkUserCanTerminateOwnershipChange(res.locals.oauth.token.User, res.locals.videoChangeOwnership, res)) return
228 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
229 const videoChangeOwnership = res.locals.videoChangeOwnership as VideoChangeOwnershipModel
231 if (videoChangeOwnership.status === VideoChangeOwnershipStatus.WAITING) {
235 .json({ error: 'Ownership already accepted or refused' })
242 const videosAcceptChangeOwnershipValidator = [
243 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
244 const body = req.body as VideoChangeOwnershipAccept
245 if (!await isVideoChannelOfAccountExist(body.channelId, res.locals.oauth.token.User, res)) return
247 const user = res.locals.oauth.token.User
248 const videoChangeOwnership = res.locals.videoChangeOwnership as VideoChangeOwnershipModel
249 const isAble = await user.isAbleToUploadVideo(videoChangeOwnership.Video.getOriginalFile())
250 if (isAble === false) {
252 .json({ error: 'The user video quota is exceeded with this video.' })
261 function getCommonVideoAttributes () {
263 body('thumbnailfile')
264 .custom((value, { req }) => isVideoImage(req.files, 'thumbnailfile')).withMessage(
265 'This thumbnail file is not supported or too large. Please, make sure it is of the following type: '
266 + CONSTRAINTS_FIELDS.VIDEOS.IMAGE.EXTNAME.join(', ')
269 .custom((value, { req }) => isVideoImage(req.files, 'previewfile')).withMessage(
270 'This preview file is not supported or too large. Please, make sure it is of the following type: '
271 + CONSTRAINTS_FIELDS.VIDEOS.IMAGE.EXTNAME.join(', ')
276 .customSanitizer(toIntOrNull)
277 .custom(isVideoCategoryValid).withMessage('Should have a valid category'),
280 .customSanitizer(toIntOrNull)
281 .custom(isVideoLicenceValid).withMessage('Should have a valid licence'),
284 .customSanitizer(toValueOrNull)
285 .custom(isVideoLanguageValid).withMessage('Should have a valid language'),
289 .custom(isBooleanValid).withMessage('Should have a valid NSFW attribute'),
290 body('waitTranscoding')
293 .custom(isBooleanValid).withMessage('Should have a valid wait transcoding attribute'),
297 .custom(isVideoPrivacyValid).withMessage('Should have correct video privacy'),
300 .customSanitizer(toValueOrNull)
301 .custom(isVideoDescriptionValid).withMessage('Should have a valid description'),
304 .customSanitizer(toValueOrNull)
305 .custom(isVideoSupportValid).withMessage('Should have a valid support text'),
308 .customSanitizer(toValueOrNull)
309 .custom(isVideoTagsValid).withMessage('Should have correct tags'),
310 body('commentsEnabled')
313 .custom(isBooleanValid).withMessage('Should have comments enabled boolean'),
315 body('scheduleUpdate')
317 .customSanitizer(toValueOrNull),
318 body('scheduleUpdate.updateAt')
320 .custom(isDateValid).withMessage('Should have a valid schedule update date'),
321 body('scheduleUpdate.privacy')
324 .custom(isScheduleVideoUpdatePrivacyValid).withMessage('Should have correct schedule update privacy')
325 ] as (ValidationChain | express.Handler)[]
328 const commonVideosFiltersValidator = [
329 query('categoryOneOf')
331 .customSanitizer(toArray)
332 .custom(isNumberArray).withMessage('Should have a valid one of category array'),
333 query('licenceOneOf')
335 .customSanitizer(toArray)
336 .custom(isNumberArray).withMessage('Should have a valid one of licence array'),
337 query('languageOneOf')
339 .customSanitizer(toArray)
340 .custom(isStringArray).withMessage('Should have a valid one of language array'),
343 .customSanitizer(toArray)
344 .custom(isStringArray).withMessage('Should have a valid one of tags array'),
347 .customSanitizer(toArray)
348 .custom(isStringArray).withMessage('Should have a valid all of tags array'),
351 .custom(isNSFWQueryValid).withMessage('Should have a valid NSFW attribute'),
354 .custom(isVideoFilterValid).withMessage('Should have a valid filter attribute'),
356 (req: express.Request, res: express.Response, next: express.NextFunction) => {
357 logger.debug('Checking commons video filters query', { parameters: req.query })
359 if (areValidationErrors(req, res)) return
361 const user: UserModel = res.locals.oauth ? res.locals.oauth.token.User : undefined
362 if (req.query.filter === 'all-local' && (!user || user.hasRight(UserRight.SEE_ALL_VIDEOS) === false)) {
364 .json({ error: 'You are not allowed to see all local videos.' })
373 // ---------------------------------------------------------------------------
377 videosUpdateValidator,
379 videosCustomGetValidator,
380 videosRemoveValidator,
382 videosChangeOwnershipValidator,
383 videosTerminateChangeOwnershipValidator,
384 videosAcceptChangeOwnershipValidator,
386 getCommonVideoAttributes,
388 commonVideosFiltersValidator
391 // ---------------------------------------------------------------------------
393 function areErrorsInScheduleUpdate (req: express.Request, res: express.Response) {
394 if (req.body.scheduleUpdate) {
395 if (!req.body.scheduleUpdate.updateAt) {
397 .json({ error: 'Schedule update at is mandatory.' })