1 import * as express from 'express'
2 import { body, param, query, ValidationChain } from 'express-validator'
3 import { ExpressPromiseHandler } from '@server/types/express'
4 import { MUserAccountId } from '@server/types/models'
5 import { UserRight, VideoPlaylistCreate, VideoPlaylistUpdate } from '../../../../shared'
6 import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
7 import { VideoPlaylistPrivacy } from '../../../../shared/models/videos/playlist/video-playlist-privacy.model'
8 import { VideoPlaylistType } from '../../../../shared/models/videos/playlist/video-playlist-type.model'
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 { isVideoImage } from '../../../helpers/custom-validators/videos'
26 import { cleanUpReqFiles } from '../../../helpers/express-utils'
27 import { logger } from '../../../helpers/logger'
28 import { CONSTRAINTS_FIELDS } from '../../../initializers/constants'
29 import { VideoPlaylistElementModel } from '../../../models/video/video-playlist-element'
30 import { MVideoPlaylist } from '../../../types/models/video/video-playlist'
31 import { authenticatePromiseIfNeeded } from '../../auth'
32 import { areValidationErrors, doesVideoChannelIdExist, doesVideoExist, doesVideoPlaylistExist, VideoPlaylistFetchType } from '../shared'
34 const videoPlaylistsAddValidator = getCommonPlaylistEditAttributes().concat([
36 .custom(isVideoPlaylistNameValid).withMessage('Should have a valid display name'),
38 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
39 logger.debug('Checking videoPlaylistsAddValidator parameters', { parameters: req.body })
41 if (areValidationErrors(req, res)) return cleanUpReqFiles(req)
43 const body: VideoPlaylistCreate = req.body
44 if (body.videoChannelId && !await doesVideoChannelIdExist(body.videoChannelId, res)) return cleanUpReqFiles(req)
46 if (body.privacy === VideoPlaylistPrivacy.PUBLIC && !body.videoChannelId) {
49 return res.fail({ message: 'Cannot set "public" a playlist that is not assigned to a channel.' })
56 const videoPlaylistsUpdateValidator = getCommonPlaylistEditAttributes().concat([
58 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
62 .custom(isVideoPlaylistNameValid).withMessage('Should have a valid display name'),
64 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
65 logger.debug('Checking videoPlaylistsUpdateValidator parameters', { parameters: req.body })
67 if (areValidationErrors(req, res)) return cleanUpReqFiles(req)
69 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return cleanUpReqFiles(req)
71 const videoPlaylist = getPlaylist(res)
73 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.REMOVE_ANY_VIDEO_PLAYLIST, res)) {
74 return cleanUpReqFiles(req)
77 const body: VideoPlaylistUpdate = req.body
79 const newPrivacy = body.privacy || videoPlaylist.privacy
80 if (newPrivacy === VideoPlaylistPrivacy.PUBLIC &&
82 (!videoPlaylist.videoChannelId && !body.videoChannelId) ||
83 body.videoChannelId === null
88 return res.fail({ message: 'Cannot set "public" a playlist that is not assigned to a channel.' })
91 if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) {
94 return res.fail({ message: 'Cannot update a watch later playlist.' })
97 if (body.videoChannelId && !await doesVideoChannelIdExist(body.videoChannelId, res)) return cleanUpReqFiles(req)
103 const videoPlaylistsDeleteValidator = [
105 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
107 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
108 logger.debug('Checking videoPlaylistsDeleteValidator parameters', { parameters: req.params })
110 if (areValidationErrors(req, res)) return
112 if (!await doesVideoPlaylistExist(req.params.playlistId, res)) return
114 const videoPlaylist = getPlaylist(res)
115 if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) {
116 return res.fail({ message: '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()
146 status: HttpStatusCode.NOT_FOUND_404,
147 message: 'Playlist not found'
151 if (videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
152 await authenticatePromiseIfNeeded(req, res)
154 const user = res.locals.oauth ? res.locals.oauth.token.User : null
158 (videoPlaylist.OwnerAccount.id !== user.Account.id && !user.hasRight(UserRight.UPDATE_ANY_VIDEO_PLAYLIST))
161 status: HttpStatusCode.FORBIDDEN_403,
162 message: 'Cannot get this private video playlist.'
174 const videoPlaylistsSearchValidator = [
175 query('search').optional().not().isEmpty().withMessage('Should have a valid search'),
177 (req: express.Request, res: express.Response, next: express.NextFunction) => {
178 logger.debug('Checking videoPlaylists search query', { parameters: req.query })
180 if (areValidationErrors(req, res)) return
186 const videoPlaylistsAddVideoValidator = [
188 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
190 .custom(isIdOrUUIDValid).withMessage('Should have a valid video id/uuid'),
191 body('startTimestamp')
193 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid start timestamp'),
194 body('stopTimestamp')
196 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid stop timestamp'),
198 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
199 logger.debug('Checking videoPlaylistsAddVideoValidator parameters', { parameters: req.params })
201 if (areValidationErrors(req, res)) return
203 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
204 if (!await doesVideoExist(req.body.videoId, res, 'only-video')) return
206 const videoPlaylist = getPlaylist(res)
208 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) {
216 const videoPlaylistsUpdateOrRemoveVideoValidator = [
218 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
219 param('playlistElementId')
220 .custom(isIdValid).withMessage('Should have an element id/uuid'),
221 body('startTimestamp')
223 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid start timestamp'),
224 body('stopTimestamp')
226 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid stop timestamp'),
228 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
229 logger.debug('Checking videoPlaylistsRemoveVideoValidator parameters', { parameters: req.params })
231 if (areValidationErrors(req, res)) return
233 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
235 const videoPlaylist = getPlaylist(res)
237 const videoPlaylistElement = await VideoPlaylistElementModel.loadById(req.params.playlistElementId)
238 if (!videoPlaylistElement) {
240 status: HttpStatusCode.NOT_FOUND_404,
241 message: 'Video playlist element not found'
245 res.locals.videoPlaylistElement = videoPlaylistElement
247 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) return
253 const videoPlaylistElementAPGetValidator = [
255 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
256 param('playlistElementId')
257 .custom(isIdValid).withMessage('Should have an playlist element id'),
259 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
260 logger.debug('Checking videoPlaylistElementAPGetValidator parameters', { parameters: req.params })
262 if (areValidationErrors(req, res)) return
264 const playlistElementId = parseInt(req.params.playlistElementId + '', 10)
265 const playlistId = req.params.playlistId
267 const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndElementIdForAP(playlistId, playlistElementId)
268 if (!videoPlaylistElement) {
270 status: HttpStatusCode.NOT_FOUND_404,
271 message: 'Video playlist element not found'
276 if (videoPlaylistElement.VideoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
278 status: HttpStatusCode.FORBIDDEN_403,
279 message: 'Cannot get this private video playlist.'
283 res.locals.videoPlaylistElementAP = videoPlaylistElement
289 const videoPlaylistsReorderVideosValidator = [
291 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
292 body('startPosition')
293 .isInt({ min: 1 }).withMessage('Should have a valid start position'),
294 body('insertAfterPosition')
295 .isInt({ min: 0 }).withMessage('Should have a valid insert after position'),
296 body('reorderLength')
298 .isInt({ min: 1 }).withMessage('Should have a valid range length'),
300 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
301 logger.debug('Checking videoPlaylistsReorderVideosValidator parameters', { parameters: req.params })
303 if (areValidationErrors(req, res)) return
305 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
307 const videoPlaylist = getPlaylist(res)
308 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) return
310 const nextPosition = await VideoPlaylistElementModel.getNextPositionOf(videoPlaylist.id)
311 const startPosition: number = req.body.startPosition
312 const insertAfterPosition: number = req.body.insertAfterPosition
313 const reorderLength: number = req.body.reorderLength
315 if (startPosition >= nextPosition || insertAfterPosition >= nextPosition) {
316 res.fail({ message: `Start position or insert after position exceed the playlist limits (max: ${nextPosition - 1})` })
320 if (reorderLength && reorderLength + startPosition > nextPosition) {
321 res.fail({ message: `Reorder length with this start position exceeds the playlist limits (max: ${nextPosition - startPosition})` })
329 const commonVideoPlaylistFiltersValidator = [
330 query('playlistType')
332 .custom(isVideoPlaylistTypeValid).withMessage('Should have a valid playlist type'),
334 (req: express.Request, res: express.Response, next: express.NextFunction) => {
335 logger.debug('Checking commonVideoPlaylistFiltersValidator parameters', { parameters: req.params })
337 if (areValidationErrors(req, res)) return
343 const doVideosInPlaylistExistValidator = [
345 .customSanitizer(toIntArray)
346 .custom(v => isArrayOf(v, isIdValid)).withMessage('Should have a valid video ids array'),
348 (req: express.Request, res: express.Response, next: express.NextFunction) => {
349 logger.debug('Checking areVideosInPlaylistExistValidator parameters', { parameters: req.query })
351 if (areValidationErrors(req, res)) return
357 // ---------------------------------------------------------------------------
360 videoPlaylistsAddValidator,
361 videoPlaylistsUpdateValidator,
362 videoPlaylistsDeleteValidator,
363 videoPlaylistsGetValidator,
364 videoPlaylistsSearchValidator,
366 videoPlaylistsAddVideoValidator,
367 videoPlaylistsUpdateOrRemoveVideoValidator,
368 videoPlaylistsReorderVideosValidator,
370 videoPlaylistElementAPGetValidator,
372 commonVideoPlaylistFiltersValidator,
374 doVideosInPlaylistExistValidator
377 // ---------------------------------------------------------------------------
379 function getCommonPlaylistEditAttributes () {
381 body('thumbnailfile')
382 .custom((value, { req }) => isVideoImage(req.files, 'thumbnailfile'))
384 'This thumbnail file is not supported or too large. Please, make sure it is of the following type: ' +
385 CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.IMAGE.EXTNAME.join(', ')
390 .customSanitizer(toValueOrNull)
391 .custom(isVideoPlaylistDescriptionValid).withMessage('Should have a valid description'),
394 .customSanitizer(toIntOrNull)
395 .custom(isVideoPlaylistPrivacyValid).withMessage('Should have correct playlist privacy'),
396 body('videoChannelId')
398 .customSanitizer(toIntOrNull)
399 ] as (ValidationChain | ExpressPromiseHandler)[]
402 function checkUserCanManageVideoPlaylist (user: MUserAccountId, videoPlaylist: MVideoPlaylist, right: UserRight, res: express.Response) {
403 if (videoPlaylist.isOwned() === false) {
405 status: HttpStatusCode.FORBIDDEN_403,
406 message: 'Cannot manage video playlist of another server.'
411 // Check if the user can manage the video playlist
412 // The user can delete it if s/he is an admin
413 // Or if s/he is the video playlist's owner
414 if (user.hasRight(right) === false && videoPlaylist.ownerAccountId !== user.Account.id) {
416 status: HttpStatusCode.FORBIDDEN_403,
417 message: 'Cannot manage video playlist of another user'
425 function getPlaylist (res: express.Response) {
426 return res.locals.videoPlaylistFull || res.locals.videoPlaylistSummary