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) {
50 return res.fail({ message: '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
89 return res.fail({ message: 'Cannot set "public" a playlist that is not assigned to a channel.' })
92 if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) {
95 return res.fail({ message: '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.fail({ message: 'Cannot delete a watch later playlist.' })
120 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.REMOVE_ANY_VIDEO_PLAYLIST, res)) {
128 const videoPlaylistsGetValidator = (fetchType: VideoPlaylistFetchType) => {
131 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
133 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
134 logger.debug('Checking videoPlaylistsGetValidator parameters', { parameters: req.params })
136 if (areValidationErrors(req, res)) return
138 if (!await doesVideoPlaylistExist(req.params.playlistId, res, fetchType)) return
140 const videoPlaylist = res.locals.videoPlaylistFull || res.locals.videoPlaylistSummary
142 // Video is unlisted, check we used the uuid to fetch it
143 if (videoPlaylist.privacy === VideoPlaylistPrivacy.UNLISTED) {
144 if (isUUIDValid(req.params.playlistId)) return next()
147 status: HttpStatusCode.NOT_FOUND_404,
148 message: 'Playlist not found'
152 if (videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
153 await authenticatePromiseIfNeeded(req, res)
155 const user = res.locals.oauth ? res.locals.oauth.token.User : null
159 (videoPlaylist.OwnerAccount.id !== user.Account.id && !user.hasRight(UserRight.UPDATE_ANY_VIDEO_PLAYLIST))
162 status: HttpStatusCode.FORBIDDEN_403,
163 message: 'Cannot get this private video playlist.'
175 const videoPlaylistsSearchValidator = [
176 query('search').optional().not().isEmpty().withMessage('Should have a valid search'),
178 (req: express.Request, res: express.Response, next: express.NextFunction) => {
179 logger.debug('Checking videoPlaylists search query', { parameters: req.query })
181 if (areValidationErrors(req, res)) return
187 const videoPlaylistsAddVideoValidator = [
189 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
191 .custom(isIdOrUUIDValid).withMessage('Should have a valid video id/uuid'),
192 body('startTimestamp')
194 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid start timestamp'),
195 body('stopTimestamp')
197 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid stop timestamp'),
199 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
200 logger.debug('Checking videoPlaylistsAddVideoValidator parameters', { parameters: req.params })
202 if (areValidationErrors(req, res)) return
204 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
205 if (!await doesVideoExist(req.body.videoId, res, 'only-video')) return
207 const videoPlaylist = getPlaylist(res)
209 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) {
217 const videoPlaylistsUpdateOrRemoveVideoValidator = [
219 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
220 param('playlistElementId')
221 .custom(isIdValid).withMessage('Should have an element id/uuid'),
222 body('startTimestamp')
224 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid start timestamp'),
225 body('stopTimestamp')
227 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid stop timestamp'),
229 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
230 logger.debug('Checking videoPlaylistsRemoveVideoValidator parameters', { parameters: req.params })
232 if (areValidationErrors(req, res)) return
234 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
236 const videoPlaylist = getPlaylist(res)
238 const videoPlaylistElement = await VideoPlaylistElementModel.loadById(req.params.playlistElementId)
239 if (!videoPlaylistElement) {
241 status: HttpStatusCode.NOT_FOUND_404,
242 message: 'Video playlist element not found'
246 res.locals.videoPlaylistElement = videoPlaylistElement
248 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) return
254 const videoPlaylistElementAPGetValidator = [
256 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
257 param('playlistElementId')
258 .custom(isIdValid).withMessage('Should have an playlist element id'),
260 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
261 logger.debug('Checking videoPlaylistElementAPGetValidator parameters', { parameters: req.params })
263 if (areValidationErrors(req, res)) return
265 const playlistElementId = parseInt(req.params.playlistElementId + '', 10)
266 const playlistId = req.params.playlistId
268 const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndElementIdForAP(playlistId, playlistElementId)
269 if (!videoPlaylistElement) {
271 status: HttpStatusCode.NOT_FOUND_404,
272 message: 'Video playlist element not found'
277 if (videoPlaylistElement.VideoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
279 status: HttpStatusCode.FORBIDDEN_403,
280 message: 'Cannot get this private video playlist.'
284 res.locals.videoPlaylistElementAP = videoPlaylistElement
290 const videoPlaylistsReorderVideosValidator = [
292 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
293 body('startPosition')
294 .isInt({ min: 1 }).withMessage('Should have a valid start position'),
295 body('insertAfterPosition')
296 .isInt({ min: 0 }).withMessage('Should have a valid insert after position'),
297 body('reorderLength')
299 .isInt({ min: 1 }).withMessage('Should have a valid range length'),
301 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
302 logger.debug('Checking videoPlaylistsReorderVideosValidator parameters', { parameters: req.params })
304 if (areValidationErrors(req, res)) return
306 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
308 const videoPlaylist = getPlaylist(res)
309 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) return
311 const nextPosition = await VideoPlaylistElementModel.getNextPositionOf(videoPlaylist.id)
312 const startPosition: number = req.body.startPosition
313 const insertAfterPosition: number = req.body.insertAfterPosition
314 const reorderLength: number = req.body.reorderLength
316 if (startPosition >= nextPosition || insertAfterPosition >= nextPosition) {
317 res.fail({ message: `Start position or insert after position exceed the playlist limits (max: ${nextPosition - 1})` })
321 if (reorderLength && reorderLength + startPosition > nextPosition) {
322 res.fail({ message: `Reorder length with this start position exceeds the playlist limits (max: ${nextPosition - startPosition})` })
330 const commonVideoPlaylistFiltersValidator = [
331 query('playlistType')
333 .custom(isVideoPlaylistTypeValid).withMessage('Should have a valid playlist type'),
335 (req: express.Request, res: express.Response, next: express.NextFunction) => {
336 logger.debug('Checking commonVideoPlaylistFiltersValidator parameters', { parameters: req.params })
338 if (areValidationErrors(req, res)) return
344 const doVideosInPlaylistExistValidator = [
346 .customSanitizer(toIntArray)
347 .custom(v => isArrayOf(v, isIdValid)).withMessage('Should have a valid video ids array'),
349 (req: express.Request, res: express.Response, next: express.NextFunction) => {
350 logger.debug('Checking areVideosInPlaylistExistValidator parameters', { parameters: req.query })
352 if (areValidationErrors(req, res)) return
358 // ---------------------------------------------------------------------------
361 videoPlaylistsAddValidator,
362 videoPlaylistsUpdateValidator,
363 videoPlaylistsDeleteValidator,
364 videoPlaylistsGetValidator,
365 videoPlaylistsSearchValidator,
367 videoPlaylistsAddVideoValidator,
368 videoPlaylistsUpdateOrRemoveVideoValidator,
369 videoPlaylistsReorderVideosValidator,
371 videoPlaylistElementAPGetValidator,
373 commonVideoPlaylistFiltersValidator,
375 doVideosInPlaylistExistValidator
378 // ---------------------------------------------------------------------------
380 function getCommonPlaylistEditAttributes () {
382 body('thumbnailfile')
383 .custom((value, { req }) => isVideoImage(req.files, 'thumbnailfile'))
385 'This thumbnail file is not supported or too large. Please, make sure it is of the following type: ' +
386 CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.IMAGE.EXTNAME.join(', ')
391 .customSanitizer(toValueOrNull)
392 .custom(isVideoPlaylistDescriptionValid).withMessage('Should have a valid description'),
395 .customSanitizer(toIntOrNull)
396 .custom(isVideoPlaylistPrivacyValid).withMessage('Should have correct playlist privacy'),
397 body('videoChannelId')
399 .customSanitizer(toIntOrNull)
400 ] as (ValidationChain | ExpressPromiseHandler)[]
403 function checkUserCanManageVideoPlaylist (user: MUserAccountId, videoPlaylist: MVideoPlaylist, right: UserRight, res: express.Response) {
404 if (videoPlaylist.isOwned() === false) {
406 status: HttpStatusCode.FORBIDDEN_403,
407 message: 'Cannot manage video playlist of another server.'
412 // Check if the user can manage the video playlist
413 // The user can delete it if s/he is an admin
414 // Or if s/he is the video playlist's owner
415 if (user.hasRight(right) === false && videoPlaylist.ownerAccountId !== user.Account.id) {
417 status: HttpStatusCode.FORBIDDEN_403,
418 message: 'Cannot manage video playlist of another user'
426 function getPlaylist (res: express.Response) {
427 return res.locals.videoPlaylistFull || res.locals.videoPlaylistSummary