1 import * as express from 'express'
2 import { body, param, query, ValidationChain } from 'express-validator'
3 import { UserRight, VideoPlaylistCreate, VideoPlaylistUpdate } from '../../../../shared'
4 import { logger } from '../../../helpers/logger'
5 import { UserModel } from '../../../models/account/user'
6 import { areValidationErrors } from '../utils'
7 import { isVideoImage } from '../../../helpers/custom-validators/videos'
8 import { CONSTRAINTS_FIELDS } from '../../../initializers/constants'
17 } from '../../../helpers/custom-validators/misc'
19 isVideoPlaylistDescriptionValid,
20 isVideoPlaylistNameValid,
21 isVideoPlaylistPrivacyValid,
22 isVideoPlaylistTimestampValid,
23 isVideoPlaylistTypeValid
24 } from '../../../helpers/custom-validators/video-playlists'
25 import { VideoPlaylistModel } from '../../../models/video/video-playlist'
26 import { cleanUpReqFiles } from '../../../helpers/express-utils'
27 import { VideoPlaylistElementModel } from '../../../models/video/video-playlist-element'
28 import { authenticatePromiseIfNeeded } from '../../oauth'
29 import { VideoPlaylistPrivacy } from '../../../../shared/models/videos/playlist/video-playlist-privacy.model'
30 import { VideoPlaylistType } from '../../../../shared/models/videos/playlist/video-playlist-type.model'
31 import { doesVideoChannelIdExist, doesVideoExist, doesVideoPlaylistExist } from '../../../helpers/middlewares'
33 const videoPlaylistsAddValidator = getCommonPlaylistEditAttributes().concat([
35 .custom(isVideoPlaylistNameValid).withMessage('Should have a valid display name'),
37 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
38 logger.debug('Checking videoPlaylistsAddValidator parameters', { parameters: req.body })
40 if (areValidationErrors(req, res)) return cleanUpReqFiles(req)
42 const body: VideoPlaylistCreate = req.body
43 if (body.videoChannelId && !await doesVideoChannelIdExist(body.videoChannelId, res)) return cleanUpReqFiles(req)
45 if (body.privacy === VideoPlaylistPrivacy.PUBLIC && !body.videoChannelId) {
47 return res.status(400)
48 .json({ error: 'Cannot set "public" a playlist that is not assigned to a channel.' })
55 const videoPlaylistsUpdateValidator = getCommonPlaylistEditAttributes().concat([
57 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
61 .custom(isVideoPlaylistNameValid).withMessage('Should have a valid display name'),
63 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
64 logger.debug('Checking videoPlaylistsUpdateValidator parameters', { parameters: req.body })
66 if (areValidationErrors(req, res)) return cleanUpReqFiles(req)
68 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return cleanUpReqFiles(req)
70 const videoPlaylist = res.locals.videoPlaylist
72 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, res.locals.videoPlaylist, UserRight.REMOVE_ANY_VIDEO_PLAYLIST, res)) {
73 return cleanUpReqFiles(req)
76 const body: VideoPlaylistUpdate = req.body
78 const newPrivacy = body.privacy || videoPlaylist.privacy
79 if (newPrivacy === VideoPlaylistPrivacy.PUBLIC &&
81 (!videoPlaylist.videoChannelId && !body.videoChannelId) ||
82 body.videoChannelId === null
86 return res.status(400)
87 .json({ error: 'Cannot set "public" a playlist that is not assigned to a channel.' })
90 if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) {
92 return res.status(400)
93 .json({ error: 'Cannot update a watch later playlist.' })
96 if (body.videoChannelId && !await doesVideoChannelIdExist(body.videoChannelId, res)) return cleanUpReqFiles(req)
102 const videoPlaylistsDeleteValidator = [
104 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
106 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
107 logger.debug('Checking videoPlaylistsDeleteValidator parameters', { parameters: req.params })
109 if (areValidationErrors(req, res)) return
111 if (!await doesVideoPlaylistExist(req.params.playlistId, res)) return
113 const videoPlaylist = res.locals.videoPlaylist
114 if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) {
115 return res.status(400)
116 .json({ error: 'Cannot delete a watch later playlist.' })
119 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, res.locals.videoPlaylist, UserRight.REMOVE_ANY_VIDEO_PLAYLIST, res)) {
127 const videoPlaylistsGetValidator = [
129 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
131 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
132 logger.debug('Checking videoPlaylistsGetValidator parameters', { parameters: req.params })
134 if (areValidationErrors(req, res)) return
136 if (!await doesVideoPlaylistExist(req.params.playlistId, res)) return
138 const videoPlaylist = res.locals.videoPlaylist
140 // Video is unlisted, check we used the uuid to fetch it
141 if (videoPlaylist.privacy === VideoPlaylistPrivacy.UNLISTED) {
142 if (isUUIDValid(req.params.playlistId)) return next()
144 return res.status(404).end()
147 if (videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
148 await authenticatePromiseIfNeeded(req, res)
150 const user = res.locals.oauth ? res.locals.oauth.token.User : null
154 (videoPlaylist.OwnerAccount.id !== user.Account.id && !user.hasRight(UserRight.UPDATE_ANY_VIDEO_PLAYLIST))
156 return res.status(403)
157 .json({ error: 'Cannot get this private video playlist.' })
167 const videoPlaylistsAddVideoValidator = [
169 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
171 .custom(isIdOrUUIDValid).withMessage('Should have a valid video id/uuid'),
172 body('startTimestamp')
174 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid start timestamp'),
175 body('stopTimestamp')
177 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid stop timestamp'),
179 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
180 logger.debug('Checking videoPlaylistsAddVideoValidator parameters', { parameters: req.params })
182 if (areValidationErrors(req, res)) return
184 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
185 if (!await doesVideoExist(req.body.videoId, res, 'only-video')) return
187 const videoPlaylist = res.locals.videoPlaylist
188 const video = res.locals.video
190 const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndVideo(videoPlaylist.id, video.id)
191 if (videoPlaylistElement) {
193 .json({ error: 'This video in this playlist already exists' })
199 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, res.locals.videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) {
207 const videoPlaylistsUpdateOrRemoveVideoValidator = [
209 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
210 param('playlistElementId')
211 .custom(isIdValid).withMessage('Should have an element id/uuid'),
212 body('startTimestamp')
214 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid start timestamp'),
215 body('stopTimestamp')
217 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid stop timestamp'),
219 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
220 logger.debug('Checking videoPlaylistsRemoveVideoValidator parameters', { parameters: req.params })
222 if (areValidationErrors(req, res)) return
224 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
226 const videoPlaylist = res.locals.videoPlaylist
228 const videoPlaylistElement = await VideoPlaylistElementModel.loadById(req.params.playlistElementId)
229 if (!videoPlaylistElement) {
231 .json({ error: 'Video playlist element not found' })
236 res.locals.videoPlaylistElement = videoPlaylistElement
238 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) return
244 const videoPlaylistElementAPGetValidator = [
246 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
248 .custom(isIdOrUUIDValid).withMessage('Should have an video id/uuid'),
250 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
251 logger.debug('Checking videoPlaylistElementAPGetValidator parameters', { parameters: req.params })
253 if (areValidationErrors(req, res)) return
255 const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndVideoForAP(req.params.playlistId, req.params.videoId)
256 if (!videoPlaylistElement) {
258 .json({ error: 'Video playlist element not found' })
264 if (videoPlaylistElement.VideoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
265 return res.status(403).end()
268 res.locals.videoPlaylistElement = videoPlaylistElement
274 const videoPlaylistsReorderVideosValidator = [
276 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
277 body('startPosition')
278 .isInt({ min: 1 }).withMessage('Should have a valid start position'),
279 body('insertAfterPosition')
280 .isInt({ min: 0 }).withMessage('Should have a valid insert after position'),
281 body('reorderLength')
283 .isInt({ min: 1 }).withMessage('Should have a valid range length'),
285 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
286 logger.debug('Checking videoPlaylistsReorderVideosValidator parameters', { parameters: req.params })
288 if (areValidationErrors(req, res)) return
290 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
292 const videoPlaylist = res.locals.videoPlaylist
293 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) return
295 const nextPosition = await VideoPlaylistElementModel.getNextPositionOf(videoPlaylist.id)
296 const startPosition: number = req.body.startPosition
297 const insertAfterPosition: number = req.body.insertAfterPosition
298 const reorderLength: number = req.body.reorderLength
300 if (startPosition >= nextPosition || insertAfterPosition >= nextPosition) {
302 .json({ error: `Start position or insert after position exceed the playlist limits (max: ${nextPosition - 1})` })
308 if (reorderLength && reorderLength + startPosition > nextPosition) {
310 .json({ error: `Reorder length with this start position exceeds the playlist limits (max: ${nextPosition - startPosition})` })
320 const commonVideoPlaylistFiltersValidator = [
321 query('playlistType')
323 .custom(isVideoPlaylistTypeValid).withMessage('Should have a valid playlist type'),
325 (req: express.Request, res: express.Response, next: express.NextFunction) => {
326 logger.debug('Checking commonVideoPlaylistFiltersValidator parameters', { parameters: req.params })
328 if (areValidationErrors(req, res)) return
334 const doVideosInPlaylistExistValidator = [
336 .customSanitizer(toIntArray)
337 .custom(v => isArrayOf(v, isIdValid)).withMessage('Should have a valid video ids array'),
339 (req: express.Request, res: express.Response, next: express.NextFunction) => {
340 logger.debug('Checking areVideosInPlaylistExistValidator parameters', { parameters: req.query })
342 if (areValidationErrors(req, res)) return
348 // ---------------------------------------------------------------------------
351 videoPlaylistsAddValidator,
352 videoPlaylistsUpdateValidator,
353 videoPlaylistsDeleteValidator,
354 videoPlaylistsGetValidator,
356 videoPlaylistsAddVideoValidator,
357 videoPlaylistsUpdateOrRemoveVideoValidator,
358 videoPlaylistsReorderVideosValidator,
360 videoPlaylistElementAPGetValidator,
362 commonVideoPlaylistFiltersValidator,
364 doVideosInPlaylistExistValidator
367 // ---------------------------------------------------------------------------
369 function getCommonPlaylistEditAttributes () {
371 body('thumbnailfile')
372 .custom((value, { req }) => isVideoImage(req.files, 'thumbnailfile')).withMessage(
373 'This thumbnail file is not supported or too large. Please, make sure it is of the following type: '
374 + CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.IMAGE.EXTNAME.join(', ')
379 .customSanitizer(toValueOrNull)
380 .custom(isVideoPlaylistDescriptionValid).withMessage('Should have a valid description'),
383 .customSanitizer(toIntOrNull)
384 .custom(isVideoPlaylistPrivacyValid).withMessage('Should have correct playlist privacy'),
385 body('videoChannelId')
387 .customSanitizer(toIntOrNull)
388 ] as (ValidationChain | express.Handler)[]
391 function checkUserCanManageVideoPlaylist (user: UserModel, videoPlaylist: VideoPlaylistModel, right: UserRight, res: express.Response) {
392 if (videoPlaylist.isOwned() === false) {
394 .json({ error: 'Cannot manage video playlist of another server.' })
400 // Check if the user can manage the video playlist
401 // The user can delete it if s/he is an admin
402 // Or if s/he is the video playlist's owner
403 if (user.hasRight(right) === false && videoPlaylist.ownerAccountId !== user.Account.id) {
405 .json({ error: 'Cannot manage video playlist of another user' })