]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/middlewares/validators/videos/video-playlists.ts
Refactor auth flow
[github/Chocobozzz/PeerTube.git] / server / middlewares / validators / videos / video-playlists.ts
index 796c63748c9373921cc8f01baa974223d436404e..c872d045e0a150655d3a4b8e65e7bf287e066334 100644 (file)
@@ -1,36 +1,54 @@
 import * as express from 'express'
-import { body, param, query, ValidationChain } from 'express-validator/check'
-import { UserRight } from '../../../../shared'
-import { logger } from '../../../helpers/logger'
-import { UserModel } from '../../../models/account/user'
-import { areValidationErrors } from '../utils'
-import { isVideoExist, isVideoImage } from '../../../helpers/custom-validators/videos'
-import { CONSTRAINTS_FIELDS } from '../../../initializers'
-import { isIdOrUUIDValid, isUUIDValid, toValueOrNull } from '../../../helpers/custom-validators/misc'
+import { body, param, query, ValidationChain } from 'express-validator'
+import { ExpressPromiseHandler } from '@server/types/express'
+import { MUserAccountId } from '@server/types/models'
+import { UserRight, VideoPlaylistCreate, VideoPlaylistUpdate } from '../../../../shared'
+import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
+import { VideoPlaylistPrivacy } from '../../../../shared/models/videos/playlist/video-playlist-privacy.model'
+import { VideoPlaylistType } from '../../../../shared/models/videos/playlist/video-playlist-type.model'
+import {
+  isArrayOf,
+  isIdOrUUIDValid,
+  isIdValid,
+  isUUIDValid,
+  toIntArray,
+  toIntOrNull,
+  toValueOrNull
+} from '../../../helpers/custom-validators/misc'
 import {
   isVideoPlaylistDescriptionValid,
-  isVideoPlaylistExist,
   isVideoPlaylistNameValid,
   isVideoPlaylistPrivacyValid,
   isVideoPlaylistTimestampValid,
   isVideoPlaylistTypeValid
 } from '../../../helpers/custom-validators/video-playlists'
-import { VideoPlaylistModel } from '../../../models/video/video-playlist'
+import { isVideoImage } from '../../../helpers/custom-validators/videos'
 import { cleanUpReqFiles } from '../../../helpers/express-utils'
-import { isVideoChannelIdExist } from '../../../helpers/custom-validators/video-channels'
+import { logger } from '../../../helpers/logger'
+import { doesVideoChannelIdExist, doesVideoExist, doesVideoPlaylistExist, VideoPlaylistFetchType } from '../../../helpers/middlewares'
+import { CONSTRAINTS_FIELDS } from '../../../initializers/constants'
 import { VideoPlaylistElementModel } from '../../../models/video/video-playlist-element'
-import { VideoModel } from '../../../models/video/video'
-import { authenticatePromiseIfNeeded } from '../../oauth'
-import { VideoPlaylistPrivacy } from '../../../../shared/models/videos/playlist/video-playlist-privacy.model'
-import { VideoPlaylistType } from '../../../../shared/models/videos/playlist/video-playlist-type.model'
+import { MVideoPlaylist } from '../../../types/models/video/video-playlist'
+import { authenticatePromiseIfNeeded } from '../../auth'
+import { areValidationErrors } from '../utils'
 
 const videoPlaylistsAddValidator = getCommonPlaylistEditAttributes().concat([
+  body('displayName')
+    .custom(isVideoPlaylistNameValid).withMessage('Should have a valid display name'),
+
   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
     logger.debug('Checking videoPlaylistsAddValidator parameters', { parameters: req.body })
 
     if (areValidationErrors(req, res)) return cleanUpReqFiles(req)
 
-    if (req.body.videoChannelId && !await isVideoChannelIdExist(req.body.videoChannelId, res)) return cleanUpReqFiles(req)
+    const body: VideoPlaylistCreate = req.body
+    if (body.videoChannelId && !await doesVideoChannelIdExist(body.videoChannelId, res)) return cleanUpReqFiles(req)
+
+    if (body.privacy === VideoPlaylistPrivacy.PUBLIC && !body.videoChannelId) {
+      cleanUpReqFiles(req)
+      return res.status(HttpStatusCode.BAD_REQUEST_400)
+                .json({ error: 'Cannot set "public" a playlist that is not assigned to a channel.' })
+    }
 
     return next()
   }
@@ -40,32 +58,44 @@ const videoPlaylistsUpdateValidator = getCommonPlaylistEditAttributes().concat([
   param('playlistId')
     .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
 
+  body('displayName')
+    .optional()
+    .custom(isVideoPlaylistNameValid).withMessage('Should have a valid display name'),
+
   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
     logger.debug('Checking videoPlaylistsUpdateValidator parameters', { parameters: req.body })
 
     if (areValidationErrors(req, res)) return cleanUpReqFiles(req)
 
-    if (!await isVideoPlaylistExist(req.params.playlistId, res)) return cleanUpReqFiles(req)
+    if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return cleanUpReqFiles(req)
 
-    const videoPlaylist = res.locals.videoPlaylist
+    const videoPlaylist = getPlaylist(res)
 
-    if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, res.locals.videoPlaylist, UserRight.REMOVE_ANY_VIDEO_PLAYLIST, res)) {
+    if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.REMOVE_ANY_VIDEO_PLAYLIST, res)) {
       return cleanUpReqFiles(req)
     }
 
-    if (videoPlaylist.privacy !== VideoPlaylistPrivacy.PRIVATE && req.body.privacy === VideoPlaylistPrivacy.PRIVATE) {
+    const body: VideoPlaylistUpdate = req.body
+
+    const newPrivacy = body.privacy || videoPlaylist.privacy
+    if (newPrivacy === VideoPlaylistPrivacy.PUBLIC &&
+      (
+        (!videoPlaylist.videoChannelId && !body.videoChannelId) ||
+        body.videoChannelId === null
+      )
+    ) {
       cleanUpReqFiles(req)
-      return res.status(409)
-                .json({ error: 'Cannot set "private" a video playlist that was not private.' })
+      return res.status(HttpStatusCode.BAD_REQUEST_400)
+                .json({ error: 'Cannot set "public" a playlist that is not assigned to a channel.' })
     }
 
     if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) {
       cleanUpReqFiles(req)
-      return res.status(409)
+      return res.status(HttpStatusCode.BAD_REQUEST_400)
                 .json({ error: 'Cannot update a watch later playlist.' })
     }
 
-    if (req.body.videoChannelId && !await isVideoChannelIdExist(req.body.videoChannelId, res)) return cleanUpReqFiles(req)
+    if (body.videoChannelId && !await doesVideoChannelIdExist(body.videoChannelId, res)) return cleanUpReqFiles(req)
 
     return next()
   }
@@ -80,15 +110,15 @@ const videoPlaylistsDeleteValidator = [
 
     if (areValidationErrors(req, res)) return
 
-    if (!await isVideoPlaylistExist(req.params.playlistId, res)) return
+    if (!await doesVideoPlaylistExist(req.params.playlistId, res)) return
 
-    const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
+    const videoPlaylist = getPlaylist(res)
     if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) {
-      return res.status(409)
+      return res.status(HttpStatusCode.BAD_REQUEST_400)
                 .json({ error: 'Cannot delete a watch later playlist.' })
     }
 
-    if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, res.locals.videoPlaylist, UserRight.REMOVE_ANY_VIDEO_PLAYLIST, res)) {
+    if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.REMOVE_ANY_VIDEO_PLAYLIST, res)) {
       return
     }
 
@@ -96,41 +126,55 @@ const videoPlaylistsDeleteValidator = [
   }
 ]
 
-const videoPlaylistsGetValidator = [
-  param('playlistId')
-    .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
+const videoPlaylistsGetValidator = (fetchType: VideoPlaylistFetchType) => {
+  return [
+    param('playlistId')
+      .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
 
-  async (req: express.Request, res: express.Response, next: express.NextFunction) => {
-    logger.debug('Checking videoPlaylistsGetValidator parameters', { parameters: req.params })
+    async (req: express.Request, res: express.Response, next: express.NextFunction) => {
+      logger.debug('Checking videoPlaylistsGetValidator parameters', { parameters: req.params })
 
-    if (areValidationErrors(req, res)) return
+      if (areValidationErrors(req, res)) return
 
-    if (!await isVideoPlaylistExist(req.params.playlistId, res)) return
+      if (!await doesVideoPlaylistExist(req.params.playlistId, res, fetchType)) return
 
-    const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
+      const videoPlaylist = res.locals.videoPlaylistFull || res.locals.videoPlaylistSummary
 
-    // Video is unlisted, check we used the uuid to fetch it
-    if (videoPlaylist.privacy === VideoPlaylistPrivacy.UNLISTED) {
-      if (isUUIDValid(req.params.playlistId)) return next()
+      // Video is unlisted, check we used the uuid to fetch it
+      if (videoPlaylist.privacy === VideoPlaylistPrivacy.UNLISTED) {
+        if (isUUIDValid(req.params.playlistId)) return next()
 
-      return res.status(404).end()
-    }
+        return res.status(HttpStatusCode.NOT_FOUND_404).end()
+      }
+
+      if (videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
+        await authenticatePromiseIfNeeded(req, res)
 
-    if (videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
-      await authenticatePromiseIfNeeded(req, res)
+        const user = res.locals.oauth ? res.locals.oauth.token.User : null
 
-      const user: UserModel = res.locals.oauth ? res.locals.oauth.token.User : null
+        if (
+          !user ||
+          (videoPlaylist.OwnerAccount.id !== user.Account.id && !user.hasRight(UserRight.UPDATE_ANY_VIDEO_PLAYLIST))
+        ) {
+          return res.status(HttpStatusCode.FORBIDDEN_403)
+                    .json({ error: 'Cannot get this private video playlist.' })
+        }
 
-      if (
-        !user ||
-        (videoPlaylist.OwnerAccount.userId !== user.id && !user.hasRight(UserRight.UPDATE_ANY_VIDEO_PLAYLIST))
-      ) {
-        return res.status(403)
-                  .json({ error: 'Cannot get this private video playlist.' })
+        return next()
       }
 
       return next()
     }
+  ]
+}
+
+const videoPlaylistsSearchValidator = [
+  query('search').optional().not().isEmpty().withMessage('Should have a valid search'),
+
+  (req: express.Request, res: express.Response, next: express.NextFunction) => {
+    logger.debug('Checking videoPlaylists search query', { parameters: req.query })
+
+    if (areValidationErrors(req, res)) return
 
     return next()
   }
@@ -153,22 +197,12 @@ const videoPlaylistsAddVideoValidator = [
 
     if (areValidationErrors(req, res)) return
 
-    if (!await isVideoPlaylistExist(req.params.playlistId, res)) return
-    if (!await isVideoExist(req.body.videoId, res, 'only-video')) return
-
-    const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
-    const video: VideoModel = res.locals.video
+    if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
+    if (!await doesVideoExist(req.body.videoId, res, 'only-video')) return
 
-    const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndVideo(videoPlaylist.id, video.id)
-    if (videoPlaylistElement) {
-      res.status(409)
-         .json({ error: 'This video in this playlist already exists' })
-         .end()
-
-      return
-    }
+    const videoPlaylist = getPlaylist(res)
 
-    if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, res.locals.videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) {
+    if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) {
       return
     }
 
@@ -179,8 +213,8 @@ const videoPlaylistsAddVideoValidator = [
 const videoPlaylistsUpdateOrRemoveVideoValidator = [
   param('playlistId')
     .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
-  param('videoId')
-    .custom(isIdOrUUIDValid).withMessage('Should have an video id/uuid'),
+  param('playlistElementId')
+    .custom(isIdValid).withMessage('Should have an element id/uuid'),
   body('startTimestamp')
     .optional()
     .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid start timestamp'),
@@ -193,15 +227,13 @@ const videoPlaylistsUpdateOrRemoveVideoValidator = [
 
     if (areValidationErrors(req, res)) return
 
-    if (!await isVideoPlaylistExist(req.params.playlistId, res)) return
-    if (!await isVideoExist(req.params.videoId, res, 'id')) return
+    if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
 
-    const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
-    const video: VideoModel = res.locals.video
+    const videoPlaylist = getPlaylist(res)
 
-    const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndVideo(videoPlaylist.id, video.id)
+    const videoPlaylistElement = await VideoPlaylistElementModel.loadById(req.params.playlistElementId)
     if (!videoPlaylistElement) {
-      res.status(404)
+      res.status(HttpStatusCode.NOT_FOUND_404)
          .json({ error: 'Video playlist element not found' })
          .end()
 
@@ -218,17 +250,20 @@ const videoPlaylistsUpdateOrRemoveVideoValidator = [
 const videoPlaylistElementAPGetValidator = [
   param('playlistId')
     .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
-  param('videoId')
-    .custom(isIdOrUUIDValid).withMessage('Should have an video id/uuid'),
+  param('playlistElementId')
+    .custom(isIdValid).withMessage('Should have an playlist element id'),
 
   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
     logger.debug('Checking videoPlaylistElementAPGetValidator parameters', { parameters: req.params })
 
     if (areValidationErrors(req, res)) return
 
-    const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndVideoForAP(req.params.playlistId, req.params.videoId)
+    const playlistElementId = parseInt(req.params.playlistElementId + '', 10)
+    const playlistId = req.params.playlistId
+
+    const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndElementIdForAP(playlistId, playlistElementId)
     if (!videoPlaylistElement) {
-      res.status(404)
+      res.status(HttpStatusCode.NOT_FOUND_404)
          .json({ error: 'Video playlist element not found' })
          .end()
 
@@ -236,10 +271,10 @@ const videoPlaylistElementAPGetValidator = [
     }
 
     if (videoPlaylistElement.VideoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
-      return res.status(403).end()
+      return res.status(HttpStatusCode.FORBIDDEN_403).end()
     }
 
-    res.locals.videoPlaylistElement = videoPlaylistElement
+    res.locals.videoPlaylistElementAP = videoPlaylistElement
 
     return next()
   }
@@ -261,9 +296,9 @@ const videoPlaylistsReorderVideosValidator = [
 
     if (areValidationErrors(req, res)) return
 
-    if (!await isVideoPlaylistExist(req.params.playlistId, res)) return
+    if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
 
-    const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
+    const videoPlaylist = getPlaylist(res)
     if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) return
 
     const nextPosition = await VideoPlaylistElementModel.getNextPositionOf(videoPlaylist.id)
@@ -272,7 +307,7 @@ const videoPlaylistsReorderVideosValidator = [
     const reorderLength: number = req.body.reorderLength
 
     if (startPosition >= nextPosition || insertAfterPosition >= nextPosition) {
-      res.status(400)
+      res.status(HttpStatusCode.BAD_REQUEST_400)
          .json({ error: `Start position or insert after position exceed the playlist limits (max: ${nextPosition - 1})` })
          .end()
 
@@ -280,7 +315,7 @@ const videoPlaylistsReorderVideosValidator = [
     }
 
     if (reorderLength && reorderLength + startPosition > nextPosition) {
-      res.status(400)
+      res.status(HttpStatusCode.BAD_REQUEST_400)
          .json({ error: `Reorder length with this start position exceeds the playlist limits (max: ${nextPosition - startPosition})` })
          .end()
 
@@ -305,6 +340,20 @@ const commonVideoPlaylistFiltersValidator = [
   }
 ]
 
+const doVideosInPlaylistExistValidator = [
+  query('videoIds')
+    .customSanitizer(toIntArray)
+    .custom(v => isArrayOf(v, isIdValid)).withMessage('Should have a valid video ids array'),
+
+  (req: express.Request, res: express.Response, next: express.NextFunction) => {
+    logger.debug('Checking areVideosInPlaylistExistValidator parameters', { parameters: req.query })
+
+    if (areValidationErrors(req, res)) return
+
+    return next()
+  }
+]
+
 // ---------------------------------------------------------------------------
 
 export {
@@ -312,6 +361,7 @@ export {
   videoPlaylistsUpdateValidator,
   videoPlaylistsDeleteValidator,
   videoPlaylistsGetValidator,
+  videoPlaylistsSearchValidator,
 
   videoPlaylistsAddVideoValidator,
   videoPlaylistsUpdateOrRemoveVideoValidator,
@@ -319,7 +369,9 @@ export {
 
   videoPlaylistElementAPGetValidator,
 
-  commonVideoPlaylistFiltersValidator
+  commonVideoPlaylistFiltersValidator,
+
+  doVideosInPlaylistExistValidator
 }
 
 // ---------------------------------------------------------------------------
@@ -327,30 +379,29 @@ export {
 function getCommonPlaylistEditAttributes () {
   return [
     body('thumbnailfile')
-      .custom((value, { req }) => isVideoImage(req.files, 'thumbnailfile')).withMessage(
-      'This thumbnail file is not supported or too large. Please, make sure it is of the following type: '
-      + CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.IMAGE.EXTNAME.join(', ')
-    ),
+      .custom((value, { req }) => isVideoImage(req.files, 'thumbnailfile'))
+      .withMessage(
+        'This thumbnail file is not supported or too large. Please, make sure it is of the following type: ' +
+        CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.IMAGE.EXTNAME.join(', ')
+      ),
 
-    body('displayName')
-      .custom(isVideoPlaylistNameValid).withMessage('Should have a valid display name'),
     body('description')
       .optional()
       .customSanitizer(toValueOrNull)
       .custom(isVideoPlaylistDescriptionValid).withMessage('Should have a valid description'),
     body('privacy')
       .optional()
-      .toInt()
+      .customSanitizer(toIntOrNull)
       .custom(isVideoPlaylistPrivacyValid).withMessage('Should have correct playlist privacy'),
     body('videoChannelId')
       .optional()
-      .toInt()
-  ] as (ValidationChain | express.Handler)[]
+      .customSanitizer(toIntOrNull)
+  ] as (ValidationChain | ExpressPromiseHandler)[]
 }
 
-function checkUserCanManageVideoPlaylist (user: UserModel, videoPlaylist: VideoPlaylistModel, right: UserRight, res: express.Response) {
+function checkUserCanManageVideoPlaylist (user: MUserAccountId, videoPlaylist: MVideoPlaylist, right: UserRight, res: express.Response) {
   if (videoPlaylist.isOwned() === false) {
-    res.status(403)
+    res.status(HttpStatusCode.FORBIDDEN_403)
        .json({ error: 'Cannot manage video playlist of another server.' })
        .end()
 
@@ -361,7 +412,7 @@ function checkUserCanManageVideoPlaylist (user: UserModel, videoPlaylist: VideoP
   // The user can delete it if s/he is an admin
   // Or if s/he is the video playlist's owner
   if (user.hasRight(right) === false && videoPlaylist.ownerAccountId !== user.Account.id) {
-    res.status(403)
+    res.status(HttpStatusCode.FORBIDDEN_403)
        .json({ error: 'Cannot manage video playlist of another user' })
        .end()
 
@@ -370,3 +421,7 @@ function checkUserCanManageVideoPlaylist (user: UserModel, videoPlaylist: VideoP
 
   return true
 }
+
+function getPlaylist (res: express.Response) {
+  return res.locals.videoPlaylistFull || res.locals.videoPlaylistSummary
+}