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 { doesVideoChannelIdExist, doesVideoExist, doesVideoPlaylistExist, VideoPlaylistFetchType } from '../../../helpers/middlewares'
29 import { CONSTRAINTS_FIELDS } from '../../../initializers/constants'
30 import { VideoPlaylistElementModel } from '../../../models/video/video-playlist-element'
31 import { MVideoPlaylist } from '../../../types/models/video/video-playlist'
32 import { authenticatePromiseIfNeeded } from '../../auth'
33 import { areValidationErrors } from '../utils'
35 const videoPlaylistsAddValidator = getCommonPlaylistEditAttributes().concat([
37 .custom(isVideoPlaylistNameValid).withMessage('Should have a valid display name'),
39 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
40 logger.debug('Checking videoPlaylistsAddValidator parameters', { parameters: req.body })
42 if (areValidationErrors(req, res)) return cleanUpReqFiles(req)
44 const body: VideoPlaylistCreate = req.body
45 if (body.videoChannelId && !await doesVideoChannelIdExist(body.videoChannelId, res)) return cleanUpReqFiles(req)
47 if (body.privacy === VideoPlaylistPrivacy.PUBLIC && !body.videoChannelId) {
49 return res.status(HttpStatusCode.BAD_REQUEST_400)
50 .json({ error: 'Cannot set "public" a playlist that is not assigned to a channel.' })
57 const videoPlaylistsUpdateValidator = getCommonPlaylistEditAttributes().concat([
59 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
63 .custom(isVideoPlaylistNameValid).withMessage('Should have a valid display name'),
65 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
66 logger.debug('Checking videoPlaylistsUpdateValidator parameters', { parameters: req.body })
68 if (areValidationErrors(req, res)) return cleanUpReqFiles(req)
70 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return cleanUpReqFiles(req)
72 const videoPlaylist = getPlaylist(res)
74 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.REMOVE_ANY_VIDEO_PLAYLIST, res)) {
75 return cleanUpReqFiles(req)
78 const body: VideoPlaylistUpdate = req.body
80 const newPrivacy = body.privacy || videoPlaylist.privacy
81 if (newPrivacy === VideoPlaylistPrivacy.PUBLIC &&
83 (!videoPlaylist.videoChannelId && !body.videoChannelId) ||
84 body.videoChannelId === null
88 return res.status(HttpStatusCode.BAD_REQUEST_400)
89 .json({ error: 'Cannot set "public" a playlist that is not assigned to a channel.' })
92 if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) {
94 return res.status(HttpStatusCode.BAD_REQUEST_400)
95 .json({ error: 'Cannot update a watch later playlist.' })
98 if (body.videoChannelId && !await doesVideoChannelIdExist(body.videoChannelId, res)) return cleanUpReqFiles(req)
104 const videoPlaylistsDeleteValidator = [
106 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
108 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
109 logger.debug('Checking videoPlaylistsDeleteValidator parameters', { parameters: req.params })
111 if (areValidationErrors(req, res)) return
113 if (!await doesVideoPlaylistExist(req.params.playlistId, res)) return
115 const videoPlaylist = getPlaylist(res)
116 if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) {
117 return res.status(HttpStatusCode.BAD_REQUEST_400)
118 .json({ error: 'Cannot delete a watch later playlist.' })
121 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.REMOVE_ANY_VIDEO_PLAYLIST, res)) {
129 const videoPlaylistsGetValidator = (fetchType: VideoPlaylistFetchType) => {
132 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
134 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
135 logger.debug('Checking videoPlaylistsGetValidator parameters', { parameters: req.params })
137 if (areValidationErrors(req, res)) return
139 if (!await doesVideoPlaylistExist(req.params.playlistId, res, fetchType)) return
141 const videoPlaylist = res.locals.videoPlaylistFull || res.locals.videoPlaylistSummary
143 // Video is unlisted, check we used the uuid to fetch it
144 if (videoPlaylist.privacy === VideoPlaylistPrivacy.UNLISTED) {
145 if (isUUIDValid(req.params.playlistId)) return next()
147 return res.status(HttpStatusCode.NOT_FOUND_404).end()
150 if (videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
151 await authenticatePromiseIfNeeded(req, res)
153 const user = res.locals.oauth ? res.locals.oauth.token.User : null
157 (videoPlaylist.OwnerAccount.id !== user.Account.id && !user.hasRight(UserRight.UPDATE_ANY_VIDEO_PLAYLIST))
159 return res.status(HttpStatusCode.FORBIDDEN_403)
160 .json({ error: 'Cannot get this private video playlist.' })
171 const videoPlaylistsSearchValidator = [
172 query('search').optional().not().isEmpty().withMessage('Should have a valid search'),
174 (req: express.Request, res: express.Response, next: express.NextFunction) => {
175 logger.debug('Checking videoPlaylists search query', { parameters: req.query })
177 if (areValidationErrors(req, res)) return
183 const videoPlaylistsAddVideoValidator = [
185 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
187 .custom(isIdOrUUIDValid).withMessage('Should have a valid video id/uuid'),
188 body('startTimestamp')
190 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid start timestamp'),
191 body('stopTimestamp')
193 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid stop timestamp'),
195 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
196 logger.debug('Checking videoPlaylistsAddVideoValidator parameters', { parameters: req.params })
198 if (areValidationErrors(req, res)) return
200 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
201 if (!await doesVideoExist(req.body.videoId, res, 'only-video')) return
203 const videoPlaylist = getPlaylist(res)
205 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) {
213 const videoPlaylistsUpdateOrRemoveVideoValidator = [
215 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
216 param('playlistElementId')
217 .custom(isIdValid).withMessage('Should have an element id/uuid'),
218 body('startTimestamp')
220 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid start timestamp'),
221 body('stopTimestamp')
223 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid stop timestamp'),
225 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
226 logger.debug('Checking videoPlaylistsRemoveVideoValidator parameters', { parameters: req.params })
228 if (areValidationErrors(req, res)) return
230 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
232 const videoPlaylist = getPlaylist(res)
234 const videoPlaylistElement = await VideoPlaylistElementModel.loadById(req.params.playlistElementId)
235 if (!videoPlaylistElement) {
236 res.status(HttpStatusCode.NOT_FOUND_404)
237 .json({ error: 'Video playlist element not found' })
242 res.locals.videoPlaylistElement = videoPlaylistElement
244 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) return
250 const videoPlaylistElementAPGetValidator = [
252 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
253 param('playlistElementId')
254 .custom(isIdValid).withMessage('Should have an playlist element id'),
256 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
257 logger.debug('Checking videoPlaylistElementAPGetValidator parameters', { parameters: req.params })
259 if (areValidationErrors(req, res)) return
261 const playlistElementId = parseInt(req.params.playlistElementId + '', 10)
262 const playlistId = req.params.playlistId
264 const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndElementIdForAP(playlistId, playlistElementId)
265 if (!videoPlaylistElement) {
266 res.status(HttpStatusCode.NOT_FOUND_404)
267 .json({ error: 'Video playlist element not found' })
273 if (videoPlaylistElement.VideoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
274 return res.status(HttpStatusCode.FORBIDDEN_403).end()
277 res.locals.videoPlaylistElementAP = videoPlaylistElement
283 const videoPlaylistsReorderVideosValidator = [
285 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
286 body('startPosition')
287 .isInt({ min: 1 }).withMessage('Should have a valid start position'),
288 body('insertAfterPosition')
289 .isInt({ min: 0 }).withMessage('Should have a valid insert after position'),
290 body('reorderLength')
292 .isInt({ min: 1 }).withMessage('Should have a valid range length'),
294 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
295 logger.debug('Checking videoPlaylistsReorderVideosValidator parameters', { parameters: req.params })
297 if (areValidationErrors(req, res)) return
299 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
301 const videoPlaylist = getPlaylist(res)
302 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) return
304 const nextPosition = await VideoPlaylistElementModel.getNextPositionOf(videoPlaylist.id)
305 const startPosition: number = req.body.startPosition
306 const insertAfterPosition: number = req.body.insertAfterPosition
307 const reorderLength: number = req.body.reorderLength
309 if (startPosition >= nextPosition || insertAfterPosition >= nextPosition) {
310 res.status(HttpStatusCode.BAD_REQUEST_400)
311 .json({ error: `Start position or insert after position exceed the playlist limits (max: ${nextPosition - 1})` })
317 if (reorderLength && reorderLength + startPosition > nextPosition) {
318 res.status(HttpStatusCode.BAD_REQUEST_400)
319 .json({ error: `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) {
404 res.status(HttpStatusCode.FORBIDDEN_403)
405 .json({ error: '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) {
415 res.status(HttpStatusCode.FORBIDDEN_403)
416 .json({ error: 'Cannot manage video playlist of another user' })
425 function getPlaylist (res: express.Response) {
426 return res.locals.videoPlaylistFull || res.locals.videoPlaylistSummary