]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/middlewares/validators/videos/video-playlists.ts
Add to playlist dropdown
[github/Chocobozzz/PeerTube.git] / server / middlewares / validators / videos / video-playlists.ts
CommitLineData
418d092a 1import * as express from 'express'
df0b219d
C
2import { body, param, query, ValidationChain } from 'express-validator/check'
3import { UserRight } from '../../../../shared'
418d092a
C
4import { logger } from '../../../helpers/logger'
5import { UserModel } from '../../../models/account/user'
6import { areValidationErrors } from '../utils'
f0a39880 7import { isVideoExist, isVideoFileInfoHashValid, isVideoImage } from '../../../helpers/custom-validators/videos'
418d092a 8import { CONSTRAINTS_FIELDS } from '../../../initializers'
f0a39880 9import { isArrayOf, isIdOrUUIDValid, isIdValid, isUUIDValid, toArray, toValueOrNull, toIntArray } from '../../../helpers/custom-validators/misc'
418d092a
C
10import {
11 isVideoPlaylistDescriptionValid,
12 isVideoPlaylistExist,
13 isVideoPlaylistNameValid,
df0b219d
C
14 isVideoPlaylistPrivacyValid,
15 isVideoPlaylistTimestampValid,
16 isVideoPlaylistTypeValid
418d092a
C
17} from '../../../helpers/custom-validators/video-playlists'
18import { VideoPlaylistModel } from '../../../models/video/video-playlist'
19import { cleanUpReqFiles } from '../../../helpers/express-utils'
20import { isVideoChannelIdExist } from '../../../helpers/custom-validators/video-channels'
21import { VideoPlaylistElementModel } from '../../../models/video/video-playlist-element'
22import { VideoModel } from '../../../models/video/video'
23import { authenticatePromiseIfNeeded } from '../../oauth'
24import { VideoPlaylistPrivacy } from '../../../../shared/models/videos/playlist/video-playlist-privacy.model'
df0b219d 25import { VideoPlaylistType } from '../../../../shared/models/videos/playlist/video-playlist-type.model'
f0a39880 26import { areValidActorHandles } from '../../../helpers/custom-validators/activitypub/actor'
418d092a
C
27
28const videoPlaylistsAddValidator = getCommonPlaylistEditAttributes().concat([
29 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
30 logger.debug('Checking videoPlaylistsAddValidator parameters', { parameters: req.body })
31
32 if (areValidationErrors(req, res)) return cleanUpReqFiles(req)
33
34 if (req.body.videoChannelId && !await isVideoChannelIdExist(req.body.videoChannelId, res)) return cleanUpReqFiles(req)
35
36 return next()
37 }
38])
39
40const videoPlaylistsUpdateValidator = getCommonPlaylistEditAttributes().concat([
41 param('playlistId')
42 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
43
44 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
45 logger.debug('Checking videoPlaylistsUpdateValidator parameters', { parameters: req.body })
46
47 if (areValidationErrors(req, res)) return cleanUpReqFiles(req)
48
09979f89 49 if (!await isVideoPlaylistExist(req.params.playlistId, res, 'all')) return cleanUpReqFiles(req)
07b1a18a
C
50
51 const videoPlaylist = res.locals.videoPlaylist
52
418d092a
C
53 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, res.locals.videoPlaylist, UserRight.REMOVE_ANY_VIDEO_PLAYLIST, res)) {
54 return cleanUpReqFiles(req)
55 }
56
07b1a18a
C
57 if (videoPlaylist.privacy !== VideoPlaylistPrivacy.PRIVATE && req.body.privacy === VideoPlaylistPrivacy.PRIVATE) {
58 cleanUpReqFiles(req)
59 return res.status(409)
60 .json({ error: 'Cannot set "private" a video playlist that was not private.' })
61 }
62
df0b219d
C
63 if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) {
64 cleanUpReqFiles(req)
65 return res.status(409)
66 .json({ error: 'Cannot update a watch later playlist.' })
67 }
68
418d092a
C
69 if (req.body.videoChannelId && !await isVideoChannelIdExist(req.body.videoChannelId, res)) return cleanUpReqFiles(req)
70
71 return next()
72 }
73])
74
75const videoPlaylistsDeleteValidator = [
76 param('playlistId')
77 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
78
79 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
80 logger.debug('Checking videoPlaylistsDeleteValidator parameters', { parameters: req.params })
81
82 if (areValidationErrors(req, res)) return
83
84 if (!await isVideoPlaylistExist(req.params.playlistId, res)) return
df0b219d
C
85
86 const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
87 if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) {
88 return res.status(409)
89 .json({ error: 'Cannot delete a watch later playlist.' })
90 }
91
418d092a
C
92 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, res.locals.videoPlaylist, UserRight.REMOVE_ANY_VIDEO_PLAYLIST, res)) {
93 return
94 }
95
96 return next()
97 }
98]
99
100const videoPlaylistsGetValidator = [
101 param('playlistId')
102 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
103
104 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
105 logger.debug('Checking videoPlaylistsGetValidator parameters', { parameters: req.params })
106
107 if (areValidationErrors(req, res)) return
108
109 if (!await isVideoPlaylistExist(req.params.playlistId, res)) return
110
111 const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
07b1a18a
C
112
113 // Video is unlisted, check we used the uuid to fetch it
114 if (videoPlaylist.privacy === VideoPlaylistPrivacy.UNLISTED) {
115 if (isUUIDValid(req.params.playlistId)) return next()
116
117 return res.status(404).end()
118 }
119
418d092a
C
120 if (videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
121 await authenticatePromiseIfNeeded(req, res)
122
123 const user: UserModel = res.locals.oauth ? res.locals.oauth.token.User : null
124
125 if (
126 !user ||
127 (videoPlaylist.OwnerAccount.userId !== user.id && !user.hasRight(UserRight.UPDATE_ANY_VIDEO_PLAYLIST))
128 ) {
129 return res.status(403)
130 .json({ error: 'Cannot get this private video playlist.' })
131 }
132
133 return next()
134 }
135
136 return next()
137 }
138]
139
140const videoPlaylistsAddVideoValidator = [
141 param('playlistId')
142 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
143 body('videoId')
144 .custom(isIdOrUUIDValid).withMessage('Should have a valid video id/uuid'),
145 body('startTimestamp')
146 .optional()
df0b219d 147 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid start timestamp'),
418d092a
C
148 body('stopTimestamp')
149 .optional()
df0b219d 150 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid stop timestamp'),
418d092a
C
151
152 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
153 logger.debug('Checking videoPlaylistsAddVideoValidator parameters', { parameters: req.params })
154
155 if (areValidationErrors(req, res)) return
156
09979f89 157 if (!await isVideoPlaylistExist(req.params.playlistId, res, 'all')) return
07b1a18a 158 if (!await isVideoExist(req.body.videoId, res, 'only-video')) return
418d092a
C
159
160 const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
161 const video: VideoModel = res.locals.video
162
163 const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndVideo(videoPlaylist.id, video.id)
164 if (videoPlaylistElement) {
165 res.status(409)
166 .json({ error: 'This video in this playlist already exists' })
167 .end()
168
169 return
170 }
171
172 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, res.locals.videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) {
173 return
174 }
175
176 return next()
177 }
178]
179
180const videoPlaylistsUpdateOrRemoveVideoValidator = [
181 param('playlistId')
182 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
183 param('videoId')
184 .custom(isIdOrUUIDValid).withMessage('Should have an video id/uuid'),
185 body('startTimestamp')
186 .optional()
df0b219d 187 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid start timestamp'),
418d092a
C
188 body('stopTimestamp')
189 .optional()
df0b219d 190 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid stop timestamp'),
418d092a
C
191
192 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
193 logger.debug('Checking videoPlaylistsRemoveVideoValidator parameters', { parameters: req.params })
194
195 if (areValidationErrors(req, res)) return
196
09979f89 197 if (!await isVideoPlaylistExist(req.params.playlistId, res, 'all')) return
07b1a18a 198 if (!await isVideoExist(req.params.videoId, res, 'id')) return
418d092a
C
199
200 const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
201 const video: VideoModel = res.locals.video
202
203 const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndVideo(videoPlaylist.id, video.id)
204 if (!videoPlaylistElement) {
205 res.status(404)
206 .json({ error: 'Video playlist element not found' })
207 .end()
208
209 return
210 }
211 res.locals.videoPlaylistElement = videoPlaylistElement
212
213 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) return
214
215 return next()
216 }
217]
218
219const videoPlaylistElementAPGetValidator = [
220 param('playlistId')
221 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
222 param('videoId')
223 .custom(isIdOrUUIDValid).withMessage('Should have an video id/uuid'),
224
225 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
226 logger.debug('Checking videoPlaylistElementAPGetValidator parameters', { parameters: req.params })
227
228 if (areValidationErrors(req, res)) return
229
230 const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndVideoForAP(req.params.playlistId, req.params.videoId)
231 if (!videoPlaylistElement) {
232 res.status(404)
233 .json({ error: 'Video playlist element not found' })
234 .end()
235
236 return
237 }
238
239 if (videoPlaylistElement.VideoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
240 return res.status(403).end()
241 }
242
243 res.locals.videoPlaylistElement = videoPlaylistElement
244
245 return next()
246 }
247]
248
249const videoPlaylistsReorderVideosValidator = [
250 param('playlistId')
251 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
252 body('startPosition')
253 .isInt({ min: 1 }).withMessage('Should have a valid start position'),
254 body('insertAfterPosition')
255 .isInt({ min: 0 }).withMessage('Should have a valid insert after position'),
256 body('reorderLength')
257 .optional()
258 .isInt({ min: 1 }).withMessage('Should have a valid range length'),
259
260 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
261 logger.debug('Checking videoPlaylistsReorderVideosValidator parameters', { parameters: req.params })
262
263 if (areValidationErrors(req, res)) return
264
09979f89 265 if (!await isVideoPlaylistExist(req.params.playlistId, res, 'all')) return
418d092a
C
266
267 const videoPlaylist: VideoPlaylistModel = res.locals.videoPlaylist
268 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) return
269
07b1a18a
C
270 const nextPosition = await VideoPlaylistElementModel.getNextPositionOf(videoPlaylist.id)
271 const startPosition: number = req.body.startPosition
272 const insertAfterPosition: number = req.body.insertAfterPosition
273 const reorderLength: number = req.body.reorderLength
274
275 if (startPosition >= nextPosition || insertAfterPosition >= nextPosition) {
276 res.status(400)
277 .json({ error: `Start position or insert after position exceed the playlist limits (max: ${nextPosition - 1})` })
278 .end()
279
280 return
281 }
282
283 if (reorderLength && reorderLength + startPosition > nextPosition) {
284 res.status(400)
285 .json({ error: `Reorder length with this start position exceeds the playlist limits (max: ${nextPosition - startPosition})` })
286 .end()
287
288 return
289 }
290
418d092a
C
291 return next()
292 }
293]
294
df0b219d
C
295const commonVideoPlaylistFiltersValidator = [
296 query('playlistType')
297 .optional()
298 .custom(isVideoPlaylistTypeValid).withMessage('Should have a valid playlist type'),
299
300 (req: express.Request, res: express.Response, next: express.NextFunction) => {
301 logger.debug('Checking commonVideoPlaylistFiltersValidator parameters', { parameters: req.params })
302
303 if (areValidationErrors(req, res)) return
304
305 return next()
306 }
307]
308
f0a39880
C
309const doVideosInPlaylistExistValidator = [
310 query('videoIds')
311 .customSanitizer(toIntArray)
312 .custom(v => isArrayOf(v, isIdValid)).withMessage('Should have a valid video ids array'),
313
314 (req: express.Request, res: express.Response, next: express.NextFunction) => {
315 logger.debug('Checking areVideosInPlaylistExistValidator parameters', { parameters: req.query })
316
317 if (areValidationErrors(req, res)) return
318
319 return next()
320 }
321]
322
418d092a
C
323// ---------------------------------------------------------------------------
324
325export {
326 videoPlaylistsAddValidator,
327 videoPlaylistsUpdateValidator,
328 videoPlaylistsDeleteValidator,
329 videoPlaylistsGetValidator,
330
331 videoPlaylistsAddVideoValidator,
332 videoPlaylistsUpdateOrRemoveVideoValidator,
333 videoPlaylistsReorderVideosValidator,
334
df0b219d
C
335 videoPlaylistElementAPGetValidator,
336
f0a39880
C
337 commonVideoPlaylistFiltersValidator,
338
339 doVideosInPlaylistExistValidator
418d092a
C
340}
341
342// ---------------------------------------------------------------------------
343
344function getCommonPlaylistEditAttributes () {
345 return [
346 body('thumbnailfile')
347 .custom((value, { req }) => isVideoImage(req.files, 'thumbnailfile')).withMessage(
348 'This thumbnail file is not supported or too large. Please, make sure it is of the following type: '
349 + CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.IMAGE.EXTNAME.join(', ')
350 ),
351
352 body('displayName')
353 .custom(isVideoPlaylistNameValid).withMessage('Should have a valid display name'),
354 body('description')
355 .optional()
356 .customSanitizer(toValueOrNull)
357 .custom(isVideoPlaylistDescriptionValid).withMessage('Should have a valid description'),
358 body('privacy')
359 .optional()
360 .toInt()
361 .custom(isVideoPlaylistPrivacyValid).withMessage('Should have correct playlist privacy'),
362 body('videoChannelId')
363 .optional()
830b4faf 364 .customSanitizer(toValueOrNull)
418d092a
C
365 .toInt()
366 ] as (ValidationChain | express.Handler)[]
367}
368
369function checkUserCanManageVideoPlaylist (user: UserModel, videoPlaylist: VideoPlaylistModel, right: UserRight, res: express.Response) {
370 if (videoPlaylist.isOwned() === false) {
371 res.status(403)
372 .json({ error: 'Cannot manage video playlist of another server.' })
373 .end()
374
375 return false
376 }
377
378 // Check if the user can manage the video playlist
379 // The user can delete it if s/he is an admin
380 // Or if s/he is the video playlist's owner
381 if (user.hasRight(right) === false && videoPlaylist.ownerAccountId !== user.Account.id) {
382 res.status(403)
383 .json({ error: 'Cannot manage video playlist of another user' })
384 .end()
385
386 return false
387 }
388
389 return true
390}