1 import 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'
12 } from '@shared/models'
22 } from '../../../helpers/custom-validators/misc'
24 isVideoPlaylistDescriptionValid,
25 isVideoPlaylistNameValid,
26 isVideoPlaylistPrivacyValid,
27 isVideoPlaylistTimestampValid,
28 isVideoPlaylistTypeValid
29 } from '../../../helpers/custom-validators/video-playlists'
30 import { isVideoImage } from '../../../helpers/custom-validators/videos'
31 import { cleanUpReqFiles } from '../../../helpers/express-utils'
32 import { logger } from '../../../helpers/logger'
33 import { CONSTRAINTS_FIELDS } from '../../../initializers/constants'
34 import { VideoPlaylistElementModel } from '../../../models/video/video-playlist-element'
35 import { MVideoPlaylist } from '../../../types/models/video/video-playlist'
36 import { authenticatePromiseIfNeeded } from '../../auth'
39 doesVideoChannelIdExist,
41 doesVideoPlaylistExist,
42 isValidPlaylistIdParam,
43 VideoPlaylistFetchType
46 const videoPlaylistsAddValidator = getCommonPlaylistEditAttributes().concat([
48 .custom(isVideoPlaylistNameValid).withMessage('Should have a valid display name'),
50 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
51 logger.debug('Checking videoPlaylistsAddValidator parameters', { parameters: req.body })
53 if (areValidationErrors(req, res)) return cleanUpReqFiles(req)
55 const body: VideoPlaylistCreate = req.body
56 if (body.videoChannelId && !await doesVideoChannelIdExist(body.videoChannelId, res)) return cleanUpReqFiles(req)
59 !body.videoChannelId &&
60 (body.privacy === VideoPlaylistPrivacy.PUBLIC || body.privacy === VideoPlaylistPrivacy.UNLISTED)
64 return res.fail({ message: 'Cannot set "public" or "unlisted" a playlist that is not assigned to a channel.' })
71 const videoPlaylistsUpdateValidator = getCommonPlaylistEditAttributes().concat([
72 isValidPlaylistIdParam('playlistId'),
76 .custom(isVideoPlaylistNameValid).withMessage('Should have a valid display name'),
78 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
79 logger.debug('Checking videoPlaylistsUpdateValidator parameters', { parameters: req.body })
81 if (areValidationErrors(req, res)) return cleanUpReqFiles(req)
83 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return cleanUpReqFiles(req)
85 const videoPlaylist = getPlaylist(res)
87 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.REMOVE_ANY_VIDEO_PLAYLIST, res)) {
88 return cleanUpReqFiles(req)
91 const body: VideoPlaylistUpdate = req.body
93 const newPrivacy = body.privacy || videoPlaylist.privacy
94 if (newPrivacy === VideoPlaylistPrivacy.PUBLIC &&
96 (!videoPlaylist.videoChannelId && !body.videoChannelId) ||
97 body.videoChannelId === null
102 return res.fail({ message: 'Cannot set "public" a playlist that is not assigned to a channel.' })
105 if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) {
108 return res.fail({ message: 'Cannot update a watch later playlist.' })
111 if (body.videoChannelId && !await doesVideoChannelIdExist(body.videoChannelId, res)) return cleanUpReqFiles(req)
117 const videoPlaylistsDeleteValidator = [
118 isValidPlaylistIdParam('playlistId'),
120 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
121 logger.debug('Checking videoPlaylistsDeleteValidator parameters', { parameters: req.params })
123 if (areValidationErrors(req, res)) return
125 if (!await doesVideoPlaylistExist(req.params.playlistId, res)) return
127 const videoPlaylist = getPlaylist(res)
128 if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) {
129 return res.fail({ message: 'Cannot delete a watch later playlist.' })
132 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.REMOVE_ANY_VIDEO_PLAYLIST, res)) {
140 const videoPlaylistsGetValidator = (fetchType: VideoPlaylistFetchType) => {
142 isValidPlaylistIdParam('playlistId'),
144 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
145 logger.debug('Checking videoPlaylistsGetValidator parameters', { parameters: req.params })
147 if (areValidationErrors(req, res)) return
149 if (!await doesVideoPlaylistExist(req.params.playlistId, res, fetchType)) return
151 const videoPlaylist = res.locals.videoPlaylistFull || res.locals.videoPlaylistSummary
153 // Video is unlisted, check we used the uuid to fetch it
154 if (videoPlaylist.privacy === VideoPlaylistPrivacy.UNLISTED) {
155 if (isUUIDValid(req.params.playlistId)) return next()
158 status: HttpStatusCode.NOT_FOUND_404,
159 message: 'Playlist not found'
163 if (videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
164 await authenticatePromiseIfNeeded(req, res)
166 const user = res.locals.oauth ? res.locals.oauth.token.User : null
170 (videoPlaylist.OwnerAccount.id !== user.Account.id && !user.hasRight(UserRight.UPDATE_ANY_VIDEO_PLAYLIST))
173 status: HttpStatusCode.FORBIDDEN_403,
174 message: 'Cannot get this private video playlist.'
186 const videoPlaylistsSearchValidator = [
187 query('search').optional().not().isEmpty().withMessage('Should have a valid search'),
189 (req: express.Request, res: express.Response, next: express.NextFunction) => {
190 logger.debug('Checking videoPlaylists search query', { parameters: req.query })
192 if (areValidationErrors(req, res)) return
198 const videoPlaylistsAddVideoValidator = [
199 isValidPlaylistIdParam('playlistId'),
202 .customSanitizer(toCompleteUUID)
203 .custom(isIdOrUUIDValid).withMessage('Should have a valid video id/uuid'),
204 body('startTimestamp')
206 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid start timestamp'),
207 body('stopTimestamp')
209 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid stop timestamp'),
211 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
212 logger.debug('Checking videoPlaylistsAddVideoValidator parameters', { parameters: req.params })
214 if (areValidationErrors(req, res)) return
216 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
217 if (!await doesVideoExist(req.body.videoId, res, 'only-video')) return
219 const videoPlaylist = getPlaylist(res)
221 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) {
229 const videoPlaylistsUpdateOrRemoveVideoValidator = [
230 isValidPlaylistIdParam('playlistId'),
231 param('playlistElementId')
232 .customSanitizer(toCompleteUUID)
233 .custom(isIdValid).withMessage('Should have an element id/uuid'),
234 body('startTimestamp')
236 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid start timestamp'),
237 body('stopTimestamp')
239 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid stop timestamp'),
241 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
242 logger.debug('Checking videoPlaylistsRemoveVideoValidator parameters', { parameters: req.params })
244 if (areValidationErrors(req, res)) return
246 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
248 const videoPlaylist = getPlaylist(res)
250 const videoPlaylistElement = await VideoPlaylistElementModel.loadById(req.params.playlistElementId)
251 if (!videoPlaylistElement) {
253 status: HttpStatusCode.NOT_FOUND_404,
254 message: 'Video playlist element not found'
258 res.locals.videoPlaylistElement = videoPlaylistElement
260 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) return
266 const videoPlaylistElementAPGetValidator = [
267 isValidPlaylistIdParam('playlistId'),
268 param('playlistElementId')
269 .custom(isIdValid).withMessage('Should have an playlist element id'),
271 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
272 logger.debug('Checking videoPlaylistElementAPGetValidator parameters', { parameters: req.params })
274 if (areValidationErrors(req, res)) return
276 const playlistElementId = parseInt(req.params.playlistElementId + '', 10)
277 const playlistId = req.params.playlistId
279 const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndElementIdForAP(playlistId, playlistElementId)
280 if (!videoPlaylistElement) {
282 status: HttpStatusCode.NOT_FOUND_404,
283 message: 'Video playlist element not found'
288 if (videoPlaylistElement.VideoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
290 status: HttpStatusCode.FORBIDDEN_403,
291 message: 'Cannot get this private video playlist.'
295 res.locals.videoPlaylistElementAP = videoPlaylistElement
301 const videoPlaylistsReorderVideosValidator = [
302 isValidPlaylistIdParam('playlistId'),
303 body('startPosition')
304 .isInt({ min: 1 }).withMessage('Should have a valid start position'),
305 body('insertAfterPosition')
306 .isInt({ min: 0 }).withMessage('Should have a valid insert after position'),
307 body('reorderLength')
309 .isInt({ min: 1 }).withMessage('Should have a valid range length'),
311 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
312 logger.debug('Checking videoPlaylistsReorderVideosValidator parameters', { parameters: req.params })
314 if (areValidationErrors(req, res)) return
316 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
318 const videoPlaylist = getPlaylist(res)
319 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) return
321 const nextPosition = await VideoPlaylistElementModel.getNextPositionOf(videoPlaylist.id)
322 const startPosition: number = req.body.startPosition
323 const insertAfterPosition: number = req.body.insertAfterPosition
324 const reorderLength: number = req.body.reorderLength
326 if (startPosition >= nextPosition || insertAfterPosition >= nextPosition) {
327 res.fail({ message: `Start position or insert after position exceed the playlist limits (max: ${nextPosition - 1})` })
331 if (reorderLength && reorderLength + startPosition > nextPosition) {
332 res.fail({ message: `Reorder length with this start position exceeds the playlist limits (max: ${nextPosition - startPosition})` })
340 const commonVideoPlaylistFiltersValidator = [
341 query('playlistType')
343 .custom(isVideoPlaylistTypeValid).withMessage('Should have a valid playlist type'),
345 (req: express.Request, res: express.Response, next: express.NextFunction) => {
346 logger.debug('Checking commonVideoPlaylistFiltersValidator parameters', { parameters: req.params })
348 if (areValidationErrors(req, res)) return
354 const doVideosInPlaylistExistValidator = [
356 .customSanitizer(toIntArray)
357 .custom(v => isArrayOf(v, isIdValid)).withMessage('Should have a valid video ids array'),
359 (req: express.Request, res: express.Response, next: express.NextFunction) => {
360 logger.debug('Checking areVideosInPlaylistExistValidator parameters', { parameters: req.query })
362 if (areValidationErrors(req, res)) return
368 // ---------------------------------------------------------------------------
371 videoPlaylistsAddValidator,
372 videoPlaylistsUpdateValidator,
373 videoPlaylistsDeleteValidator,
374 videoPlaylistsGetValidator,
375 videoPlaylistsSearchValidator,
377 videoPlaylistsAddVideoValidator,
378 videoPlaylistsUpdateOrRemoveVideoValidator,
379 videoPlaylistsReorderVideosValidator,
381 videoPlaylistElementAPGetValidator,
383 commonVideoPlaylistFiltersValidator,
385 doVideosInPlaylistExistValidator
388 // ---------------------------------------------------------------------------
390 function getCommonPlaylistEditAttributes () {
392 body('thumbnailfile')
393 .custom((value, { req }) => isVideoImage(req.files, 'thumbnailfile'))
395 'This thumbnail file is not supported or too large. Please, make sure it is of the following type: ' +
396 CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.IMAGE.EXTNAME.join(', ')
401 .customSanitizer(toValueOrNull)
402 .custom(isVideoPlaylistDescriptionValid).withMessage('Should have a valid description'),
405 .customSanitizer(toIntOrNull)
406 .custom(isVideoPlaylistPrivacyValid).withMessage('Should have correct playlist privacy'),
407 body('videoChannelId')
409 .customSanitizer(toIntOrNull)
410 ] as (ValidationChain | ExpressPromiseHandler)[]
413 function checkUserCanManageVideoPlaylist (user: MUserAccountId, videoPlaylist: MVideoPlaylist, right: UserRight, res: express.Response) {
414 if (videoPlaylist.isOwned() === false) {
416 status: HttpStatusCode.FORBIDDEN_403,
417 message: 'Cannot manage video playlist of another server.'
422 // Check if the user can manage the video playlist
423 // The user can delete it if s/he is an admin
424 // Or if s/he is the video playlist's owner
425 if (user.hasRight(right) === false && videoPlaylist.ownerAccountId !== user.Account.id) {
427 status: HttpStatusCode.FORBIDDEN_403,
428 message: 'Cannot manage video playlist of another user'
436 function getPlaylist (res: express.Response) {
437 return res.locals.videoPlaylistFull || res.locals.videoPlaylistSummary