1 import * as express from 'express'
2 import { body, param, query, ValidationChain } from 'express-validator/check'
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 { doesVideoExist, isVideoImage } from '../../../helpers/custom-validators/videos'
8 import { CONSTRAINTS_FIELDS } from '../../../initializers'
9 import { isArrayOf, isIdOrUUIDValid, isIdValid, isUUIDValid, toIntArray, toValueOrNull } from '../../../helpers/custom-validators/misc'
11 isVideoPlaylistDescriptionValid,
12 doesVideoPlaylistExist,
13 isVideoPlaylistNameValid,
14 isVideoPlaylistPrivacyValid,
15 isVideoPlaylistTimestampValid,
16 isVideoPlaylistTypeValid
17 } from '../../../helpers/custom-validators/video-playlists'
18 import { VideoPlaylistModel } from '../../../models/video/video-playlist'
19 import { cleanUpReqFiles } from '../../../helpers/express-utils'
20 import { doesVideoChannelIdExist } from '../../../helpers/custom-validators/video-channels'
21 import { VideoPlaylistElementModel } from '../../../models/video/video-playlist-element'
22 import { VideoModel } from '../../../models/video/video'
23 import { authenticatePromiseIfNeeded } from '../../oauth'
24 import { VideoPlaylistPrivacy } from '../../../../shared/models/videos/playlist/video-playlist-privacy.model'
25 import { VideoPlaylistType } from '../../../../shared/models/videos/playlist/video-playlist-type.model'
27 const videoPlaylistsAddValidator = getCommonPlaylistEditAttributes().concat([
28 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
29 logger.debug('Checking videoPlaylistsAddValidator parameters', { parameters: req.body })
31 if (areValidationErrors(req, res)) return cleanUpReqFiles(req)
33 const body: VideoPlaylistCreate = req.body
34 if (body.videoChannelId && !await doesVideoChannelIdExist(body.videoChannelId, res)) return cleanUpReqFiles(req)
36 if (body.privacy === VideoPlaylistPrivacy.PUBLIC && !body.videoChannelId) {
38 return res.status(400)
39 .json({ error: 'Cannot set "public" a playlist that is not assigned to a channel.' })
46 const videoPlaylistsUpdateValidator = getCommonPlaylistEditAttributes().concat([
48 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
50 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
51 logger.debug('Checking videoPlaylistsUpdateValidator parameters', { parameters: req.body })
53 if (areValidationErrors(req, res)) return cleanUpReqFiles(req)
55 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return cleanUpReqFiles(req)
57 const videoPlaylist = res.locals.videoPlaylist
59 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, res.locals.videoPlaylist, UserRight.REMOVE_ANY_VIDEO_PLAYLIST, res)) {
60 return cleanUpReqFiles(req)
63 const body: VideoPlaylistUpdate = req.body
65 if (videoPlaylist.privacy !== VideoPlaylistPrivacy.PRIVATE && body.privacy === VideoPlaylistPrivacy.PRIVATE) {
67 return res.status(400)
68 .json({ error: 'Cannot set "private" a video playlist that was not private.' })
71 const newPrivacy = body.privacy || videoPlaylist.privacy
72 if (newPrivacy === VideoPlaylistPrivacy.PUBLIC &&
74 (!videoPlaylist.videoChannelId && !body.videoChannelId) ||
75 body.videoChannelId === null
79 return res.status(400)
80 .json({ error: 'Cannot set "public" a playlist that is not assigned to a channel.' })
83 if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) {
85 return res.status(400)
86 .json({ error: 'Cannot update a watch later playlist.' })
89 if (body.videoChannelId && !await doesVideoChannelIdExist(body.videoChannelId, res)) return cleanUpReqFiles(req)
95 const videoPlaylistsDeleteValidator = [
97 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
99 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
100 logger.debug('Checking videoPlaylistsDeleteValidator parameters', { parameters: req.params })
102 if (areValidationErrors(req, res)) return
104 if (!await doesVideoPlaylistExist(req.params.playlistId, res)) return
106 const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
107 if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) {
108 return res.status(400)
109 .json({ error: 'Cannot delete a watch later playlist.' })
112 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, res.locals.videoPlaylist, UserRight.REMOVE_ANY_VIDEO_PLAYLIST, res)) {
120 const videoPlaylistsGetValidator = [
122 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
124 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
125 logger.debug('Checking videoPlaylistsGetValidator parameters', { parameters: req.params })
127 if (areValidationErrors(req, res)) return
129 if (!await doesVideoPlaylistExist(req.params.playlistId, res)) return
131 const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
133 // Video is unlisted, check we used the uuid to fetch it
134 if (videoPlaylist.privacy === VideoPlaylistPrivacy.UNLISTED) {
135 if (isUUIDValid(req.params.playlistId)) return next()
137 return res.status(404).end()
140 if (videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
141 await authenticatePromiseIfNeeded(req, res)
143 const user: UserModel = res.locals.oauth ? res.locals.oauth.token.User : null
147 (videoPlaylist.OwnerAccount.userId !== user.id && !user.hasRight(UserRight.UPDATE_ANY_VIDEO_PLAYLIST))
149 return res.status(403)
150 .json({ error: 'Cannot get this private video playlist.' })
160 const videoPlaylistsAddVideoValidator = [
162 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
164 .custom(isIdOrUUIDValid).withMessage('Should have a valid video id/uuid'),
165 body('startTimestamp')
167 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid start timestamp'),
168 body('stopTimestamp')
170 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid stop timestamp'),
172 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
173 logger.debug('Checking videoPlaylistsAddVideoValidator parameters', { parameters: req.params })
175 if (areValidationErrors(req, res)) return
177 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
178 if (!await doesVideoExist(req.body.videoId, res, 'only-video')) return
180 const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
181 const video: VideoModel = res.locals.video
183 const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndVideo(videoPlaylist.id, video.id)
184 if (videoPlaylistElement) {
186 .json({ error: 'This video in this playlist already exists' })
192 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, res.locals.videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) {
200 const videoPlaylistsUpdateOrRemoveVideoValidator = [
202 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
204 .custom(isIdOrUUIDValid).withMessage('Should have an video id/uuid'),
205 body('startTimestamp')
207 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid start timestamp'),
208 body('stopTimestamp')
210 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid stop timestamp'),
212 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
213 logger.debug('Checking videoPlaylistsRemoveVideoValidator parameters', { parameters: req.params })
215 if (areValidationErrors(req, res)) return
217 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
218 if (!await doesVideoExist(req.params.videoId, res, 'id')) return
220 const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
221 const video: VideoModel = res.locals.video
223 const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndVideo(videoPlaylist.id, video.id)
224 if (!videoPlaylistElement) {
226 .json({ error: 'Video playlist element not found' })
231 res.locals.videoPlaylistElement = videoPlaylistElement
233 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) return
239 const videoPlaylistElementAPGetValidator = [
241 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
243 .custom(isIdOrUUIDValid).withMessage('Should have an video id/uuid'),
245 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
246 logger.debug('Checking videoPlaylistElementAPGetValidator parameters', { parameters: req.params })
248 if (areValidationErrors(req, res)) return
250 const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndVideoForAP(req.params.playlistId, req.params.videoId)
251 if (!videoPlaylistElement) {
253 .json({ error: 'Video playlist element not found' })
259 if (videoPlaylistElement.VideoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
260 return res.status(403).end()
263 res.locals.videoPlaylistElement = videoPlaylistElement
269 const videoPlaylistsReorderVideosValidator = [
271 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
272 body('startPosition')
273 .isInt({ min: 1 }).withMessage('Should have a valid start position'),
274 body('insertAfterPosition')
275 .isInt({ min: 0 }).withMessage('Should have a valid insert after position'),
276 body('reorderLength')
278 .isInt({ min: 1 }).withMessage('Should have a valid range length'),
280 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
281 logger.debug('Checking videoPlaylistsReorderVideosValidator parameters', { parameters: req.params })
283 if (areValidationErrors(req, res)) return
285 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
287 const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
288 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) return
290 const nextPosition = await VideoPlaylistElementModel.getNextPositionOf(videoPlaylist.id)
291 const startPosition: number = req.body.startPosition
292 const insertAfterPosition: number = req.body.insertAfterPosition
293 const reorderLength: number = req.body.reorderLength
295 if (startPosition >= nextPosition || insertAfterPosition >= nextPosition) {
297 .json({ error: `Start position or insert after position exceed the playlist limits (max: ${nextPosition - 1})` })
303 if (reorderLength && reorderLength + startPosition > nextPosition) {
305 .json({ error: `Reorder length with this start position exceeds the playlist limits (max: ${nextPosition - startPosition})` })
315 const commonVideoPlaylistFiltersValidator = [
316 query('playlistType')
318 .custom(isVideoPlaylistTypeValid).withMessage('Should have a valid playlist type'),
320 (req: express.Request, res: express.Response, next: express.NextFunction) => {
321 logger.debug('Checking commonVideoPlaylistFiltersValidator parameters', { parameters: req.params })
323 if (areValidationErrors(req, res)) return
329 const doVideosInPlaylistExistValidator = [
331 .customSanitizer(toIntArray)
332 .custom(v => isArrayOf(v, isIdValid)).withMessage('Should have a valid video ids array'),
334 (req: express.Request, res: express.Response, next: express.NextFunction) => {
335 logger.debug('Checking areVideosInPlaylistExistValidator parameters', { parameters: req.query })
337 if (areValidationErrors(req, res)) return
343 // ---------------------------------------------------------------------------
346 videoPlaylistsAddValidator,
347 videoPlaylistsUpdateValidator,
348 videoPlaylistsDeleteValidator,
349 videoPlaylistsGetValidator,
351 videoPlaylistsAddVideoValidator,
352 videoPlaylistsUpdateOrRemoveVideoValidator,
353 videoPlaylistsReorderVideosValidator,
355 videoPlaylistElementAPGetValidator,
357 commonVideoPlaylistFiltersValidator,
359 doVideosInPlaylistExistValidator
362 // ---------------------------------------------------------------------------
364 function getCommonPlaylistEditAttributes () {
366 body('thumbnailfile')
367 .custom((value, { req }) => isVideoImage(req.files, 'thumbnailfile')).withMessage(
368 'This thumbnail file is not supported or too large. Please, make sure it is of the following type: '
369 + CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.IMAGE.EXTNAME.join(', ')
373 .custom(isVideoPlaylistNameValid).withMessage('Should have a valid display name'),
376 .customSanitizer(toValueOrNull)
377 .custom(isVideoPlaylistDescriptionValid).withMessage('Should have a valid description'),
381 .custom(isVideoPlaylistPrivacyValid).withMessage('Should have correct playlist privacy'),
382 body('videoChannelId')
384 .customSanitizer(toValueOrNull)
386 ] as (ValidationChain | express.Handler)[]
389 function checkUserCanManageVideoPlaylist (user: UserModel, videoPlaylist: VideoPlaylistModel, right: UserRight, res: express.Response) {
390 if (videoPlaylist.isOwned() === false) {
392 .json({ error: 'Cannot manage video playlist of another server.' })
398 // Check if the user can manage the video playlist
399 // The user can delete it if s/he is an admin
400 // Or if s/he is the video playlist's owner
401 if (user.hasRight(right) === false && videoPlaylist.ownerAccountId !== user.Account.id) {
403 .json({ error: 'Cannot manage video playlist of another user' })