]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/middlewares/validators/videos/video-playlists.ts
Fix big play button
[github/Chocobozzz/PeerTube.git] / server / middlewares / validators / videos / video-playlists.ts
index 6b15c5464a8ad70a7090743106f5c94c7ff06fa6..0d2e6e90c5fceacedddccc4c57d2c005aa0fc106 100644 (file)
@@ -1,10 +1,11 @@
 import * as express from 'express'
 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 { logger } from '../../../helpers/logger'
-import { areValidationErrors } from '../utils'
-import { isVideoImage } from '../../../helpers/custom-validators/videos'
-import { CONSTRAINTS_FIELDS } from '../../../initializers/constants'
+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,
@@ -21,14 +22,14 @@ 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, VideoPlaylistFetchType } from '../shared'
 
 const videoPlaylistsAddValidator = getCommonPlaylistEditAttributes().concat([
   body('displayName')
@@ -44,8 +45,8 @@ const videoPlaylistsAddValidator = getCommonPlaylistEditAttributes().concat([
 
     if (body.privacy === VideoPlaylistPrivacy.PUBLIC && !body.videoChannelId) {
       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.' })
     }
 
     return next()
@@ -83,14 +84,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)
@@ -112,8 +113,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)) {
@@ -142,7 +142,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 +157,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()
@@ -199,16 +204,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
@@ -241,10 +236,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
@@ -258,25 +253,31 @@ 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)
-    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
@@ -312,18 +313,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
     }
 
@@ -401,15 +396,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
   }
 
@@ -417,10 +412,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
   }