]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/middlewares/validators/videos/video-playlists.ts
Fix redis connection timeout
[github/Chocobozzz/PeerTube.git] / server / middlewares / validators / videos / video-playlists.ts
index 27ee62b1fc569d03fafd65e203029833e59d10df..ec5a3a9c8fdd455f7616b0ac0cd53092d4b5f91a 100644 (file)
@@ -1,15 +1,21 @@
-import * as express from 'express'
+import express from 'express'
 import { body, param, query, ValidationChain } from 'express-validator'
-import { UserRight, VideoPlaylistCreate, VideoPlaylistUpdate } from '../../../../shared'
-import { logger } from '../../../helpers/logger'
-import { areValidationErrors } from '../utils'
-import { isVideoImage } from '../../../helpers/custom-validators/videos'
-import { CONSTRAINTS_FIELDS } from '../../../initializers/constants'
+import { ExpressPromiseHandler } from '@server/types/express'
+import { MUserAccountId } from '@server/types/models'
+import {
+  HttpStatusCode,
+  UserRight,
+  VideoPlaylistCreate,
+  VideoPlaylistPrivacy,
+  VideoPlaylistType,
+  VideoPlaylistUpdate
+} from '@shared/models'
 import {
   isArrayOf,
   isIdOrUUIDValid,
   isIdValid,
   isUUIDValid,
+  toCompleteUUID,
   toIntArray,
   toIntOrNull,
   toValueOrNull
@@ -21,14 +27,21 @@ import {
   isVideoPlaylistTimestampValid,
   isVideoPlaylistTypeValid
 } from '../../../helpers/custom-validators/video-playlists'
+import { isVideoImage } from '../../../helpers/custom-validators/videos'
 import { cleanUpReqFiles } from '../../../helpers/express-utils'
+import { logger } from '../../../helpers/logger'
+import { CONSTRAINTS_FIELDS } from '../../../initializers/constants'
 import { VideoPlaylistElementModel } from '../../../models/video/video-playlist-element'
-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 { doesVideoChannelIdExist, doesVideoExist, doesVideoPlaylistExist, VideoPlaylistFetchType } from '../../../helpers/middlewares'
-import { MVideoPlaylist } from '../../../typings/models/video/video-playlist'
-import { MUserAccountId } from '@server/typings/models'
+import { MVideoPlaylist } from '../../../types/models/video/video-playlist'
+import { authenticatePromiseIfNeeded } from '../../auth'
+import {
+  areValidationErrors,
+  doesVideoChannelIdExist,
+  doesVideoExist,
+  doesVideoPlaylistExist,
+  isValidPlaylistIdParam,
+  VideoPlaylistFetchType
+} from '../shared'
 
 const videoPlaylistsAddValidator = getCommonPlaylistEditAttributes().concat([
   body('displayName')
@@ -42,10 +55,13 @@ const videoPlaylistsAddValidator = getCommonPlaylistEditAttributes().concat([
     const body: VideoPlaylistCreate = req.body
     if (body.videoChannelId && !await doesVideoChannelIdExist(body.videoChannelId, res)) return cleanUpReqFiles(req)
 
-    if (body.privacy === VideoPlaylistPrivacy.PUBLIC && !body.videoChannelId) {
+    if (
+      !body.videoChannelId &&
+      (body.privacy === VideoPlaylistPrivacy.PUBLIC || body.privacy === VideoPlaylistPrivacy.UNLISTED)
+    ) {
       cleanUpReqFiles(req)
-      return res.status(400)
-                .json({ error: 'Cannot set "public" a playlist that is not assigned to a channel.' })
+
+      return res.fail({ message: 'Cannot set "public" or "unlisted" a playlist that is not assigned to a channel.' })
     }
 
     return next()
@@ -53,8 +69,7 @@ const videoPlaylistsAddValidator = getCommonPlaylistEditAttributes().concat([
 ])
 
 const videoPlaylistsUpdateValidator = getCommonPlaylistEditAttributes().concat([
-  param('playlistId')
-    .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
+  isValidPlaylistIdParam('playlistId'),
 
   body('displayName')
     .optional()
@@ -83,14 +98,14 @@ const videoPlaylistsUpdateValidator = getCommonPlaylistEditAttributes().concat([
       )
     ) {
       cleanUpReqFiles(req)
-      return res.status(400)
-                .json({ error: 'Cannot set "public" a playlist that is not assigned to a channel.' })
+
+      return res.fail({ message: 'Cannot set "public" a playlist that is not assigned to a channel.' })
     }
 
     if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) {
       cleanUpReqFiles(req)
-      return res.status(400)
-                .json({ error: 'Cannot update a watch later playlist.' })
+
+      return res.fail({ message: 'Cannot update a watch later playlist.' })
     }
 
     if (body.videoChannelId && !await doesVideoChannelIdExist(body.videoChannelId, res)) return cleanUpReqFiles(req)
@@ -100,8 +115,7 @@ const videoPlaylistsUpdateValidator = getCommonPlaylistEditAttributes().concat([
 ])
 
 const videoPlaylistsDeleteValidator = [
-  param('playlistId')
-    .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
+  isValidPlaylistIdParam('playlistId'),
 
   async (req: express.Request, res: express.Response, next: express.NextFunction) => {
     logger.debug('Checking videoPlaylistsDeleteValidator parameters', { parameters: req.params })
@@ -112,8 +126,7 @@ const videoPlaylistsDeleteValidator = [
 
     const videoPlaylist = getPlaylist(res)
     if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) {
-      return res.status(400)
-                .json({ error: 'Cannot delete a watch later playlist.' })
+      return res.fail({ message: 'Cannot delete a watch later playlist.' })
     }
 
     if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.REMOVE_ANY_VIDEO_PLAYLIST, res)) {
@@ -126,8 +139,7 @@ const videoPlaylistsDeleteValidator = [
 
 const videoPlaylistsGetValidator = (fetchType: VideoPlaylistFetchType) => {
   return [
-    param('playlistId')
-      .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
+    isValidPlaylistIdParam('playlistId'),
 
     async (req: express.Request, res: express.Response, next: express.NextFunction) => {
       logger.debug('Checking videoPlaylistsGetValidator parameters', { parameters: req.params })
@@ -142,7 +154,10 @@ const videoPlaylistsGetValidator = (fetchType: VideoPlaylistFetchType) => {
       if (videoPlaylist.privacy === VideoPlaylistPrivacy.UNLISTED) {
         if (isUUIDValid(req.params.playlistId)) return next()
 
-        return res.status(404).end()
+        return res.fail({
+          status: HttpStatusCode.NOT_FOUND_404,
+          message: 'Playlist not found'
+        })
       }
 
       if (videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
@@ -154,8 +169,10 @@ const videoPlaylistsGetValidator = (fetchType: VideoPlaylistFetchType) => {
           !user ||
           (videoPlaylist.OwnerAccount.id !== user.Account.id && !user.hasRight(UserRight.UPDATE_ANY_VIDEO_PLAYLIST))
         ) {
-          return res.status(403)
-                    .json({ error: 'Cannot get this private video playlist.' })
+          return res.fail({
+            status: HttpStatusCode.FORBIDDEN_403,
+            message: 'Cannot get this private video playlist.'
+          })
         }
 
         return next()
@@ -166,10 +183,23 @@ const videoPlaylistsGetValidator = (fetchType: VideoPlaylistFetchType) => {
   ]
 }
 
+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()
+  }
+]
+
 const videoPlaylistsAddVideoValidator = [
-  param('playlistId')
-    .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
+  isValidPlaylistIdParam('playlistId'),
+
   body('videoId')
+    .customSanitizer(toCompleteUUID)
     .custom(isIdOrUUIDValid).withMessage('Should have a valid video id/uuid'),
   body('startTimestamp')
     .optional()
@@ -187,16 +217,6 @@ const videoPlaylistsAddVideoValidator = [
     if (!await doesVideoExist(req.body.videoId, res, 'only-video')) return
 
     const videoPlaylist = getPlaylist(res)
-    const video = res.locals.onlyVideo
-
-    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
-    }
 
     if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) {
       return
@@ -207,9 +227,9 @@ const videoPlaylistsAddVideoValidator = [
 ]
 
 const videoPlaylistsUpdateOrRemoveVideoValidator = [
-  param('playlistId')
-    .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
+  isValidPlaylistIdParam('playlistId'),
   param('playlistElementId')
+    .customSanitizer(toCompleteUUID)
     .custom(isIdValid).withMessage('Should have an element id/uuid'),
   body('startTimestamp')
     .optional()
@@ -229,10 +249,10 @@ const videoPlaylistsUpdateOrRemoveVideoValidator = [
 
     const videoPlaylistElement = await VideoPlaylistElementModel.loadById(req.params.playlistElementId)
     if (!videoPlaylistElement) {
-      res.status(404)
-         .json({ error: 'Video playlist element not found' })
-         .end()
-
+      res.fail({
+        status: HttpStatusCode.NOT_FOUND_404,
+        message: 'Video playlist element not found'
+      })
       return
     }
     res.locals.videoPlaylistElement = videoPlaylistElement
@@ -244,27 +264,32 @@ 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'),
+  isValidPlaylistIdParam('playlistId'),
+  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)
-    if (!videoPlaylistElement) {
-      res.status(404)
-         .json({ error: 'Video playlist element not found' })
-         .end()
+    const playlistElementId = parseInt(req.params.playlistElementId + '', 10)
+    const playlistId = req.params.playlistId
 
+    const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndElementIdForAP(playlistId, playlistElementId)
+    if (!videoPlaylistElement) {
+      res.fail({
+        status: HttpStatusCode.NOT_FOUND_404,
+        message: 'Video playlist element not found'
+      })
       return
     }
 
     if (videoPlaylistElement.VideoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
-      return res.status(403).end()
+      return res.fail({
+        status: HttpStatusCode.FORBIDDEN_403,
+        message: 'Cannot get this private video playlist.'
+      })
     }
 
     res.locals.videoPlaylistElementAP = videoPlaylistElement
@@ -274,8 +299,7 @@ const videoPlaylistElementAPGetValidator = [
 ]
 
 const videoPlaylistsReorderVideosValidator = [
-  param('playlistId')
-    .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
+  isValidPlaylistIdParam('playlistId'),
   body('startPosition')
     .isInt({ min: 1 }).withMessage('Should have a valid start position'),
   body('insertAfterPosition')
@@ -300,18 +324,12 @@ const videoPlaylistsReorderVideosValidator = [
     const reorderLength: number = req.body.reorderLength
 
     if (startPosition >= nextPosition || insertAfterPosition >= nextPosition) {
-      res.status(400)
-         .json({ error: `Start position or insert after position exceed the playlist limits (max: ${nextPosition - 1})` })
-         .end()
-
+      res.fail({ message: `Start position or insert after position exceed the playlist limits (max: ${nextPosition - 1})` })
       return
     }
 
     if (reorderLength && reorderLength + startPosition > nextPosition) {
-      res.status(400)
-         .json({ error: `Reorder length with this start position exceeds the playlist limits (max: ${nextPosition - startPosition})` })
-         .end()
-
+      res.fail({ message: `Reorder length with this start position exceeds the playlist limits (max: ${nextPosition - startPosition})` })
       return
     }
 
@@ -354,6 +372,7 @@ export {
   videoPlaylistsUpdateValidator,
   videoPlaylistsDeleteValidator,
   videoPlaylistsGetValidator,
+  videoPlaylistsSearchValidator,
 
   videoPlaylistsAddVideoValidator,
   videoPlaylistsUpdateOrRemoveVideoValidator,
@@ -371,10 +390,11 @@ 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('description')
       .optional()
@@ -387,15 +407,15 @@ function getCommonPlaylistEditAttributes () {
     body('videoChannelId')
       .optional()
       .customSanitizer(toIntOrNull)
-  ] as (ValidationChain | express.Handler)[]
+  ] as (ValidationChain | ExpressPromiseHandler)[]
 }
 
 function checkUserCanManageVideoPlaylist (user: MUserAccountId, videoPlaylist: MVideoPlaylist, right: UserRight, res: express.Response) {
   if (videoPlaylist.isOwned() === false) {
-    res.status(403)
-       .json({ error: 'Cannot manage video playlist of another server.' })
-       .end()
-
+    res.fail({
+      status: HttpStatusCode.FORBIDDEN_403,
+      message: 'Cannot manage video playlist of another server.'
+    })
     return false
   }
 
@@ -403,10 +423,10 @@ function checkUserCanManageVideoPlaylist (user: MUserAccountId, videoPlaylist: M
   // 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)
-       .json({ error: 'Cannot manage video playlist of another user' })
-       .end()
-
+    res.fail({
+      status: HttpStatusCode.FORBIDDEN_403,
+      message: 'Cannot manage video playlist of another user'
+    })
     return false
   }