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