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 { areValidationErrors } from '../utils'
6 import { isVideoImage } from '../../../helpers/custom-validators/videos'
7 import { CONSTRAINTS_FIELDS } from '../../../initializers/constants'
16 } from '../../../helpers/custom-validators/misc'
18 isVideoPlaylistDescriptionValid,
19 isVideoPlaylistNameValid,
20 isVideoPlaylistPrivacyValid,
21 isVideoPlaylistTimestampValid,
22 isVideoPlaylistTypeValid
23 } from '../../../helpers/custom-validators/video-playlists'
24 import { cleanUpReqFiles } from '../../../helpers/express-utils'
25 import { VideoPlaylistElementModel } from '../../../models/video/video-playlist-element'
26 import { authenticatePromiseIfNeeded } from '../../oauth'
27 import { VideoPlaylistPrivacy } from '../../../../shared/models/videos/playlist/video-playlist-privacy.model'
28 import { VideoPlaylistType } from '../../../../shared/models/videos/playlist/video-playlist-type.model'
29 import { doesVideoChannelIdExist, doesVideoExist, doesVideoPlaylistExist, VideoPlaylistFetchType } from '../../../helpers/middlewares'
30 import { MVideoPlaylist } from '../../../typings/models/video/video-playlist'
31 import { MUserAccountId } from '@server/typings/models'
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 = getPlaylist(res)
72 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, 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 = getPlaylist(res)
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, videoPlaylist, UserRight.REMOVE_ANY_VIDEO_PLAYLIST, res)) {
127 const videoPlaylistsGetValidator = (fetchType: VideoPlaylistFetchType) => {
130 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
132 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
133 logger.debug('Checking videoPlaylistsGetValidator parameters', { parameters: req.params })
135 if (areValidationErrors(req, res)) return
137 if (!await doesVideoPlaylistExist(req.params.playlistId, res, fetchType)) return
139 const videoPlaylist = res.locals.videoPlaylistFull || res.locals.videoPlaylistSummary
141 // Video is unlisted, check we used the uuid to fetch it
142 if (videoPlaylist.privacy === VideoPlaylistPrivacy.UNLISTED) {
143 if (isUUIDValid(req.params.playlistId)) return next()
145 return res.status(404).end()
148 if (videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
149 await authenticatePromiseIfNeeded(req, res)
151 const user = res.locals.oauth ? res.locals.oauth.token.User : null
155 (videoPlaylist.OwnerAccount.id !== user.Account.id && !user.hasRight(UserRight.UPDATE_ANY_VIDEO_PLAYLIST))
157 return res.status(403)
158 .json({ error: 'Cannot get this private video playlist.' })
169 const videoPlaylistsSearchValidator = [
170 query('search').optional().not().isEmpty().withMessage('Should have a valid search'),
172 (req: express.Request, res: express.Response, next: express.NextFunction) => {
173 logger.debug('Checking videoPlaylists search query', { parameters: req.query })
175 if (areValidationErrors(req, res)) return
181 const videoPlaylistsAddVideoValidator = [
183 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
185 .custom(isIdOrUUIDValid).withMessage('Should have a valid video id/uuid'),
186 body('startTimestamp')
188 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid start timestamp'),
189 body('stopTimestamp')
191 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid stop timestamp'),
193 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
194 logger.debug('Checking videoPlaylistsAddVideoValidator parameters', { parameters: req.params })
196 if (areValidationErrors(req, res)) return
198 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
199 if (!await doesVideoExist(req.body.videoId, res, 'only-video')) return
201 const videoPlaylist = getPlaylist(res)
202 const video = res.locals.onlyVideo
204 const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndVideo(videoPlaylist.id, video.id)
205 if (videoPlaylistElement) {
207 .json({ error: 'This video in this playlist already exists' })
213 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) {
221 const videoPlaylistsUpdateOrRemoveVideoValidator = [
223 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
224 param('playlistElementId')
225 .custom(isIdValid).withMessage('Should have an element id/uuid'),
226 body('startTimestamp')
228 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid start timestamp'),
229 body('stopTimestamp')
231 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid stop timestamp'),
233 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
234 logger.debug('Checking videoPlaylistsRemoveVideoValidator parameters', { parameters: req.params })
236 if (areValidationErrors(req, res)) return
238 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
240 const videoPlaylist = getPlaylist(res)
242 const videoPlaylistElement = await VideoPlaylistElementModel.loadById(req.params.playlistElementId)
243 if (!videoPlaylistElement) {
245 .json({ error: 'Video playlist element not found' })
250 res.locals.videoPlaylistElement = videoPlaylistElement
252 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) return
258 const videoPlaylistElementAPGetValidator = [
260 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
262 .custom(isIdOrUUIDValid).withMessage('Should have an video id/uuid'),
264 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
265 logger.debug('Checking videoPlaylistElementAPGetValidator parameters', { parameters: req.params })
267 if (areValidationErrors(req, res)) return
269 const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndVideoForAP(req.params.playlistId, req.params.videoId)
270 if (!videoPlaylistElement) {
272 .json({ error: 'Video playlist element not found' })
278 if (videoPlaylistElement.VideoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
279 return res.status(403).end()
282 res.locals.videoPlaylistElementAP = videoPlaylistElement
288 const videoPlaylistsReorderVideosValidator = [
290 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
291 body('startPosition')
292 .isInt({ min: 1 }).withMessage('Should have a valid start position'),
293 body('insertAfterPosition')
294 .isInt({ min: 0 }).withMessage('Should have a valid insert after position'),
295 body('reorderLength')
297 .isInt({ min: 1 }).withMessage('Should have a valid range length'),
299 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
300 logger.debug('Checking videoPlaylistsReorderVideosValidator parameters', { parameters: req.params })
302 if (areValidationErrors(req, res)) return
304 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
306 const videoPlaylist = getPlaylist(res)
307 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) return
309 const nextPosition = await VideoPlaylistElementModel.getNextPositionOf(videoPlaylist.id)
310 const startPosition: number = req.body.startPosition
311 const insertAfterPosition: number = req.body.insertAfterPosition
312 const reorderLength: number = req.body.reorderLength
314 if (startPosition >= nextPosition || insertAfterPosition >= nextPosition) {
316 .json({ error: `Start position or insert after position exceed the playlist limits (max: ${nextPosition - 1})` })
322 if (reorderLength && reorderLength + startPosition > nextPosition) {
324 .json({ error: `Reorder length with this start position exceeds the playlist limits (max: ${nextPosition - startPosition})` })
334 const commonVideoPlaylistFiltersValidator = [
335 query('playlistType')
337 .custom(isVideoPlaylistTypeValid).withMessage('Should have a valid playlist type'),
339 (req: express.Request, res: express.Response, next: express.NextFunction) => {
340 logger.debug('Checking commonVideoPlaylistFiltersValidator parameters', { parameters: req.params })
342 if (areValidationErrors(req, res)) return
348 const doVideosInPlaylistExistValidator = [
350 .customSanitizer(toIntArray)
351 .custom(v => isArrayOf(v, isIdValid)).withMessage('Should have a valid video ids array'),
353 (req: express.Request, res: express.Response, next: express.NextFunction) => {
354 logger.debug('Checking areVideosInPlaylistExistValidator parameters', { parameters: req.query })
356 if (areValidationErrors(req, res)) return
362 // ---------------------------------------------------------------------------
365 videoPlaylistsAddValidator,
366 videoPlaylistsUpdateValidator,
367 videoPlaylistsDeleteValidator,
368 videoPlaylistsGetValidator,
369 videoPlaylistsSearchValidator,
371 videoPlaylistsAddVideoValidator,
372 videoPlaylistsUpdateOrRemoveVideoValidator,
373 videoPlaylistsReorderVideosValidator,
375 videoPlaylistElementAPGetValidator,
377 commonVideoPlaylistFiltersValidator,
379 doVideosInPlaylistExistValidator
382 // ---------------------------------------------------------------------------
384 function getCommonPlaylistEditAttributes () {
386 body('thumbnailfile')
387 .custom((value, { req }) => isVideoImage(req.files, 'thumbnailfile'))
389 'This thumbnail file is not supported or too large. Please, make sure it is of the following type: ' +
390 CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.IMAGE.EXTNAME.join(', ')
395 .customSanitizer(toValueOrNull)
396 .custom(isVideoPlaylistDescriptionValid).withMessage('Should have a valid description'),
399 .customSanitizer(toIntOrNull)
400 .custom(isVideoPlaylistPrivacyValid).withMessage('Should have correct playlist privacy'),
401 body('videoChannelId')
403 .customSanitizer(toIntOrNull)
404 ] as (ValidationChain | express.Handler)[]
407 function checkUserCanManageVideoPlaylist (user: MUserAccountId, videoPlaylist: MVideoPlaylist, right: UserRight, res: express.Response) {
408 if (videoPlaylist.isOwned() === false) {
410 .json({ error: 'Cannot manage video playlist of another server.' })
416 // Check if the user can manage the video playlist
417 // The user can delete it if s/he is an admin
418 // Or if s/he is the video playlist's owner
419 if (user.hasRight(right) === false && videoPlaylist.ownerAccountId !== user.Account.id) {
421 .json({ error: 'Cannot manage video playlist of another user' })
430 function getPlaylist (res: express.Response) {
431 return res.locals.videoPlaylistFull || res.locals.videoPlaylistSummary