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