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/constants'
9 import { isArrayOf, isIdOrUUIDValid, isIdValid, isUUIDValid, toIntArray, toValueOrNull } from '../../../helpers/custom-validators/misc'
11 doesVideoPlaylistExist,
12 isVideoPlaylistDescriptionValid,
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 { authenticatePromiseIfNeeded } from '../../oauth'
23 import { VideoPlaylistPrivacy } from '../../../../shared/models/videos/playlist/video-playlist-privacy.model'
24 import { VideoPlaylistType } from '../../../../shared/models/videos/playlist/video-playlist-type.model'
26 const videoPlaylistsAddValidator = getCommonPlaylistEditAttributes().concat([
27 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
28 logger.debug('Checking videoPlaylistsAddValidator parameters', { parameters: req.body })
30 if (areValidationErrors(req, res)) return cleanUpReqFiles(req)
32 const body: VideoPlaylistCreate = req.body
33 if (body.videoChannelId && !await doesVideoChannelIdExist(body.videoChannelId, res)) return cleanUpReqFiles(req)
35 if (body.privacy === VideoPlaylistPrivacy.PUBLIC && !body.videoChannelId) {
37 return res.status(400)
38 .json({ error: 'Cannot set "public" a playlist that is not assigned to a channel.' })
45 const videoPlaylistsUpdateValidator = getCommonPlaylistEditAttributes().concat([
47 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
49 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
50 logger.debug('Checking videoPlaylistsUpdateValidator parameters', { parameters: req.body })
52 if (areValidationErrors(req, res)) return cleanUpReqFiles(req)
54 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return cleanUpReqFiles(req)
56 const videoPlaylist = res.locals.videoPlaylist
58 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, res.locals.videoPlaylist, UserRight.REMOVE_ANY_VIDEO_PLAYLIST, res)) {
59 return cleanUpReqFiles(req)
62 const body: VideoPlaylistUpdate = req.body
64 if (videoPlaylist.privacy !== VideoPlaylistPrivacy.PRIVATE && body.privacy === VideoPlaylistPrivacy.PRIVATE) {
66 return res.status(400)
67 .json({ error: 'Cannot set "private" a video playlist that was not private.' })
70 const newPrivacy = body.privacy || videoPlaylist.privacy
71 if (newPrivacy === VideoPlaylistPrivacy.PUBLIC &&
73 (!videoPlaylist.videoChannelId && !body.videoChannelId) ||
74 body.videoChannelId === null
78 return res.status(400)
79 .json({ error: 'Cannot set "public" a playlist that is not assigned to a channel.' })
82 if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) {
84 return res.status(400)
85 .json({ error: 'Cannot update a watch later playlist.' })
88 if (body.videoChannelId && !await doesVideoChannelIdExist(body.videoChannelId, res)) return cleanUpReqFiles(req)
94 const videoPlaylistsDeleteValidator = [
96 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
98 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
99 logger.debug('Checking videoPlaylistsDeleteValidator parameters', { parameters: req.params })
101 if (areValidationErrors(req, res)) return
103 if (!await doesVideoPlaylistExist(req.params.playlistId, res)) return
105 const videoPlaylist = res.locals.videoPlaylist
106 if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) {
107 return res.status(400)
108 .json({ error: 'Cannot delete a watch later playlist.' })
111 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, res.locals.videoPlaylist, UserRight.REMOVE_ANY_VIDEO_PLAYLIST, res)) {
119 const videoPlaylistsGetValidator = [
121 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
123 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
124 logger.debug('Checking videoPlaylistsGetValidator parameters', { parameters: req.params })
126 if (areValidationErrors(req, res)) return
128 if (!await doesVideoPlaylistExist(req.params.playlistId, res)) return
130 const videoPlaylist = res.locals.videoPlaylist
132 // Video is unlisted, check we used the uuid to fetch it
133 if (videoPlaylist.privacy === VideoPlaylistPrivacy.UNLISTED) {
134 if (isUUIDValid(req.params.playlistId)) return next()
136 return res.status(404).end()
139 if (videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
140 await authenticatePromiseIfNeeded(req, res)
142 const user = res.locals.oauth ? res.locals.oauth.token.User : null
145 (videoPlaylist.OwnerAccount.userId !== user.id && !user.hasRight(UserRight.UPDATE_ANY_VIDEO_PLAYLIST))
147 return res.status(403)
148 .json({ error: 'Cannot get this private video playlist.' })
158 const videoPlaylistsAddVideoValidator = [
160 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
162 .custom(isIdOrUUIDValid).withMessage('Should have a valid video id/uuid'),
163 body('startTimestamp')
165 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid start timestamp'),
166 body('stopTimestamp')
168 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid stop timestamp'),
170 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
171 logger.debug('Checking videoPlaylistsAddVideoValidator parameters', { parameters: req.params })
173 if (areValidationErrors(req, res)) return
175 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
176 if (!await doesVideoExist(req.body.videoId, res, 'only-video')) return
178 const videoPlaylist = res.locals.videoPlaylist
179 const video = res.locals.video
181 const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndVideo(videoPlaylist.id, video.id)
182 if (videoPlaylistElement) {
184 .json({ error: 'This video in this playlist already exists' })
190 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, res.locals.videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) {
198 const videoPlaylistsUpdateOrRemoveVideoValidator = [
200 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
202 .custom(isIdOrUUIDValid).withMessage('Should have an video id/uuid'),
203 body('startTimestamp')
205 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid start timestamp'),
206 body('stopTimestamp')
208 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid stop timestamp'),
210 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
211 logger.debug('Checking videoPlaylistsRemoveVideoValidator parameters', { parameters: req.params })
213 if (areValidationErrors(req, res)) return
215 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
216 if (!await doesVideoExist(req.params.videoId, res, 'id')) return
218 const videoPlaylist = res.locals.videoPlaylist
219 const video = res.locals.video
221 const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndVideo(videoPlaylist.id, video.id)
222 if (!videoPlaylistElement) {
224 .json({ error: 'Video playlist element not found' })
229 res.locals.videoPlaylistElement = videoPlaylistElement
231 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) return
237 const videoPlaylistElementAPGetValidator = [
239 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
241 .custom(isIdOrUUIDValid).withMessage('Should have an video id/uuid'),
243 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
244 logger.debug('Checking videoPlaylistElementAPGetValidator parameters', { parameters: req.params })
246 if (areValidationErrors(req, res)) return
248 const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndVideoForAP(req.params.playlistId, req.params.videoId)
249 if (!videoPlaylistElement) {
251 .json({ error: 'Video playlist element not found' })
257 if (videoPlaylistElement.VideoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
258 return res.status(403).end()
261 res.locals.videoPlaylistElement = videoPlaylistElement
267 const videoPlaylistsReorderVideosValidator = [
269 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
270 body('startPosition')
271 .isInt({ min: 1 }).withMessage('Should have a valid start position'),
272 body('insertAfterPosition')
273 .isInt({ min: 0 }).withMessage('Should have a valid insert after position'),
274 body('reorderLength')
276 .isInt({ min: 1 }).withMessage('Should have a valid range length'),
278 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
279 logger.debug('Checking videoPlaylistsReorderVideosValidator parameters', { parameters: req.params })
281 if (areValidationErrors(req, res)) return
283 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
285 const videoPlaylist = res.locals.videoPlaylist
286 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) return
288 const nextPosition = await VideoPlaylistElementModel.getNextPositionOf(videoPlaylist.id)
289 const startPosition: number = req.body.startPosition
290 const insertAfterPosition: number = req.body.insertAfterPosition
291 const reorderLength: number = req.body.reorderLength
293 if (startPosition >= nextPosition || insertAfterPosition >= nextPosition) {
295 .json({ error: `Start position or insert after position exceed the playlist limits (max: ${nextPosition - 1})` })
301 if (reorderLength && reorderLength + startPosition > nextPosition) {
303 .json({ error: `Reorder length with this start position exceeds the playlist limits (max: ${nextPosition - startPosition})` })
313 const commonVideoPlaylistFiltersValidator = [
314 query('playlistType')
316 .custom(isVideoPlaylistTypeValid).withMessage('Should have a valid playlist type'),
318 (req: express.Request, res: express.Response, next: express.NextFunction) => {
319 logger.debug('Checking commonVideoPlaylistFiltersValidator parameters', { parameters: req.params })
321 if (areValidationErrors(req, res)) return
327 const doVideosInPlaylistExistValidator = [
329 .customSanitizer(toIntArray)
330 .custom(v => isArrayOf(v, isIdValid)).withMessage('Should have a valid video ids array'),
332 (req: express.Request, res: express.Response, next: express.NextFunction) => {
333 logger.debug('Checking areVideosInPlaylistExistValidator parameters', { parameters: req.query })
335 if (areValidationErrors(req, res)) return
341 // ---------------------------------------------------------------------------
344 videoPlaylistsAddValidator,
345 videoPlaylistsUpdateValidator,
346 videoPlaylistsDeleteValidator,
347 videoPlaylistsGetValidator,
349 videoPlaylistsAddVideoValidator,
350 videoPlaylistsUpdateOrRemoveVideoValidator,
351 videoPlaylistsReorderVideosValidator,
353 videoPlaylistElementAPGetValidator,
355 commonVideoPlaylistFiltersValidator,
357 doVideosInPlaylistExistValidator
360 // ---------------------------------------------------------------------------
362 function getCommonPlaylistEditAttributes () {
364 body('thumbnailfile')
365 .custom((value, { req }) => isVideoImage(req.files, 'thumbnailfile')).withMessage(
366 'This thumbnail file is not supported or too large. Please, make sure it is of the following type: '
367 + CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.IMAGE.EXTNAME.join(', ')
371 .custom(isVideoPlaylistNameValid).withMessage('Should have a valid display name'),
374 .customSanitizer(toValueOrNull)
375 .custom(isVideoPlaylistDescriptionValid).withMessage('Should have a valid description'),
379 .custom(isVideoPlaylistPrivacyValid).withMessage('Should have correct playlist privacy'),
380 body('videoChannelId')
382 .customSanitizer(toValueOrNull)
384 ] as (ValidationChain | express.Handler)[]
387 function checkUserCanManageVideoPlaylist (user: UserModel, videoPlaylist: VideoPlaylistModel, right: UserRight, res: express.Response) {
388 if (videoPlaylist.isOwned() === false) {
390 .json({ error: 'Cannot manage video playlist of another server.' })
396 // Check if the user can manage the video playlist
397 // The user can delete it if s/he is an admin
398 // Or if s/he is the video playlist's owner
399 if (user.hasRight(right) === false && videoPlaylist.ownerAccountId !== user.Account.id) {
401 .json({ error: 'Cannot manage video playlist of another user' })