]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/middlewares/validators/videos/video-playlists.ts
Refactor auth flow
[github/Chocobozzz/PeerTube.git] / server / middlewares / validators / videos / video-playlists.ts
CommitLineData
418d092a 1import * as express from 'express'
c8861d5d 2import { body, param, query, ValidationChain } from 'express-validator'
ba5a8d89
C
3import { ExpressPromiseHandler } from '@server/types/express'
4import { MUserAccountId } from '@server/types/models'
c5e4e36d 5import { UserRight, VideoPlaylistCreate, VideoPlaylistUpdate } from '../../../../shared'
ba5a8d89
C
6import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes'
7import { VideoPlaylistPrivacy } from '../../../../shared/models/videos/playlist/video-playlist-privacy.model'
8import { VideoPlaylistType } from '../../../../shared/models/videos/playlist/video-playlist-type.model'
c8861d5d
C
9import {
10 isArrayOf,
11 isIdOrUUIDValid,
12 isIdValid,
13 isUUIDValid,
14 toIntArray,
15 toIntOrNull,
16 toValueOrNull
17} from '../../../helpers/custom-validators/misc'
418d092a 18import {
9f79ade6 19 isVideoPlaylistDescriptionValid,
418d092a 20 isVideoPlaylistNameValid,
df0b219d
C
21 isVideoPlaylistPrivacyValid,
22 isVideoPlaylistTimestampValid,
23 isVideoPlaylistTypeValid
418d092a 24} from '../../../helpers/custom-validators/video-playlists'
ba5a8d89 25import { isVideoImage } from '../../../helpers/custom-validators/videos'
418d092a 26import { cleanUpReqFiles } from '../../../helpers/express-utils'
ba5a8d89 27import { logger } from '../../../helpers/logger'
453e83ea 28import { doesVideoChannelIdExist, doesVideoExist, doesVideoPlaylistExist, VideoPlaylistFetchType } from '../../../helpers/middlewares'
ba5a8d89
C
29import { CONSTRAINTS_FIELDS } from '../../../initializers/constants'
30import { VideoPlaylistElementModel } from '../../../models/video/video-playlist-element'
26d6bf65 31import { MVideoPlaylist } from '../../../types/models/video/video-playlist'
f43db2f4 32import { authenticatePromiseIfNeeded } from '../../auth'
ba5a8d89 33import { areValidationErrors } from '../utils'
418d092a
C
34
35const videoPlaylistsAddValidator = getCommonPlaylistEditAttributes().concat([
1b319b7a
C
36 body('displayName')
37 .custom(isVideoPlaylistNameValid).withMessage('Should have a valid display name'),
38
418d092a
C
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
c5e4e36d 44 const body: VideoPlaylistCreate = req.body
0f6acda1 45 if (body.videoChannelId && !await doesVideoChannelIdExist(body.videoChannelId, res)) return cleanUpReqFiles(req)
c5e4e36d
C
46
47 if (body.privacy === VideoPlaylistPrivacy.PUBLIC && !body.videoChannelId) {
48 cleanUpReqFiles(req)
2d53be02 49 return res.status(HttpStatusCode.BAD_REQUEST_400)
c5e4e36d
C
50 .json({ error: 'Cannot set "public" a playlist that is not assigned to a channel.' })
51 }
418d092a
C
52
53 return next()
54 }
55])
56
57const videoPlaylistsUpdateValidator = getCommonPlaylistEditAttributes().concat([
58 param('playlistId')
59 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
60
1b319b7a
C
61 body('displayName')
62 .optional()
63 .custom(isVideoPlaylistNameValid).withMessage('Should have a valid display name'),
64
418d092a
C
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
0f6acda1 70 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return cleanUpReqFiles(req)
07b1a18a 71
453e83ea 72 const videoPlaylist = getPlaylist(res)
07b1a18a 73
453e83ea 74 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.REMOVE_ANY_VIDEO_PLAYLIST, res)) {
418d092a
C
75 return cleanUpReqFiles(req)
76 }
77
c5e4e36d
C
78 const body: VideoPlaylistUpdate = req.body
79
c5e4e36d
C
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)
2d53be02 88 return res.status(HttpStatusCode.BAD_REQUEST_400)
c5e4e36d
C
89 .json({ error: 'Cannot set "public" a playlist that is not assigned to a channel.' })
90 }
91
df0b219d
C
92 if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) {
93 cleanUpReqFiles(req)
2d53be02 94 return res.status(HttpStatusCode.BAD_REQUEST_400)
df0b219d
C
95 .json({ error: 'Cannot update a watch later playlist.' })
96 }
97
0f6acda1 98 if (body.videoChannelId && !await doesVideoChannelIdExist(body.videoChannelId, res)) return cleanUpReqFiles(req)
418d092a
C
99
100 return next()
101 }
102])
103
104const 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
0f6acda1 113 if (!await doesVideoPlaylistExist(req.params.playlistId, res)) return
df0b219d 114
453e83ea 115 const videoPlaylist = getPlaylist(res)
df0b219d 116 if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) {
2d53be02 117 return res.status(HttpStatusCode.BAD_REQUEST_400)
df0b219d
C
118 .json({ error: 'Cannot delete a watch later playlist.' })
119 }
120
453e83ea 121 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.REMOVE_ANY_VIDEO_PLAYLIST, res)) {
418d092a
C
122 return
123 }
124
125 return next()
126 }
127]
128
453e83ea
C
129const videoPlaylistsGetValidator = (fetchType: VideoPlaylistFetchType) => {
130 return [
131 param('playlistId')
132 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
418d092a 133
453e83ea
C
134 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
135 logger.debug('Checking videoPlaylistsGetValidator parameters', { parameters: req.params })
418d092a 136
453e83ea 137 if (areValidationErrors(req, res)) return
418d092a 138
453e83ea 139 if (!await doesVideoPlaylistExist(req.params.playlistId, res, fetchType)) return
418d092a 140
453e83ea 141 const videoPlaylist = res.locals.videoPlaylistFull || res.locals.videoPlaylistSummary
07b1a18a 142
453e83ea
C
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()
07b1a18a 146
2d53be02 147 return res.status(HttpStatusCode.NOT_FOUND_404).end()
453e83ea 148 }
07b1a18a 149
453e83ea
C
150 if (videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
151 await authenticatePromiseIfNeeded(req, res)
418d092a 152
453e83ea 153 const user = res.locals.oauth ? res.locals.oauth.token.User : null
4d09cfba 154
453e83ea
C
155 if (
156 !user ||
157 (videoPlaylist.OwnerAccount.id !== user.Account.id && !user.hasRight(UserRight.UPDATE_ANY_VIDEO_PLAYLIST))
158 ) {
2d53be02 159 return res.status(HttpStatusCode.FORBIDDEN_403)
453e83ea
C
160 .json({ error: 'Cannot get this private video playlist.' })
161 }
162
163 return next()
418d092a
C
164 }
165
166 return next()
167 }
453e83ea
C
168 ]
169}
418d092a 170
c06af501
RK
171const 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
418d092a
C
183const 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()
df0b219d 190 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid start timestamp'),
418d092a
C
191 body('stopTimestamp')
192 .optional()
df0b219d 193 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid stop timestamp'),
418d092a
C
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
0f6acda1
C
200 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
201 if (!await doesVideoExist(req.body.videoId, res, 'only-video')) return
418d092a 202
453e83ea 203 const videoPlaylist = getPlaylist(res)
418d092a 204
453e83ea 205 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) {
418d092a
C
206 return
207 }
208
209 return next()
210 }
211]
212
213const videoPlaylistsUpdateOrRemoveVideoValidator = [
214 param('playlistId')
215 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
bfbd9128
C
216 param('playlistElementId')
217 .custom(isIdValid).withMessage('Should have an element id/uuid'),
418d092a
C
218 body('startTimestamp')
219 .optional()
df0b219d 220 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid start timestamp'),
418d092a
C
221 body('stopTimestamp')
222 .optional()
df0b219d 223 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid stop timestamp'),
418d092a
C
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
0f6acda1 230 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
418d092a 231
453e83ea 232 const videoPlaylist = getPlaylist(res)
418d092a 233
bfbd9128 234 const videoPlaylistElement = await VideoPlaylistElementModel.loadById(req.params.playlistElementId)
418d092a 235 if (!videoPlaylistElement) {
2d53be02 236 res.status(HttpStatusCode.NOT_FOUND_404)
418d092a
C
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
250const videoPlaylistElementAPGetValidator = [
251 param('playlistId')
252 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
37190663
C
253 param('playlistElementId')
254 .custom(isIdValid).withMessage('Should have an playlist element id'),
418d092a
C
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
37190663
C
261 const playlistElementId = parseInt(req.params.playlistElementId + '', 10)
262 const playlistId = req.params.playlistId
263
264 const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndElementIdForAP(playlistId, playlistElementId)
418d092a 265 if (!videoPlaylistElement) {
2d53be02 266 res.status(HttpStatusCode.NOT_FOUND_404)
418d092a
C
267 .json({ error: 'Video playlist element not found' })
268 .end()
269
270 return
271 }
272
273 if (videoPlaylistElement.VideoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
2d53be02 274 return res.status(HttpStatusCode.FORBIDDEN_403).end()
418d092a
C
275 }
276
b5fecbf4 277 res.locals.videoPlaylistElementAP = videoPlaylistElement
418d092a
C
278
279 return next()
280 }
281]
282
283const 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
0f6acda1 299 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
418d092a 300
453e83ea 301 const videoPlaylist = getPlaylist(res)
418d092a
C
302 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) return
303
07b1a18a
C
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) {
2d53be02 310 res.status(HttpStatusCode.BAD_REQUEST_400)
07b1a18a
C
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) {
2d53be02 318 res.status(HttpStatusCode.BAD_REQUEST_400)
07b1a18a
C
319 .json({ error: `Reorder length with this start position exceeds the playlist limits (max: ${nextPosition - startPosition})` })
320 .end()
321
322 return
323 }
324
418d092a
C
325 return next()
326 }
327]
328
df0b219d
C
329const 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
f0a39880
C
343const 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
418d092a
C
357// ---------------------------------------------------------------------------
358
359export {
360 videoPlaylistsAddValidator,
361 videoPlaylistsUpdateValidator,
362 videoPlaylistsDeleteValidator,
363 videoPlaylistsGetValidator,
c06af501 364 videoPlaylistsSearchValidator,
418d092a
C
365
366 videoPlaylistsAddVideoValidator,
367 videoPlaylistsUpdateOrRemoveVideoValidator,
368 videoPlaylistsReorderVideosValidator,
369
df0b219d
C
370 videoPlaylistElementAPGetValidator,
371
f0a39880
C
372 commonVideoPlaylistFiltersValidator,
373
374 doVideosInPlaylistExistValidator
418d092a
C
375}
376
377// ---------------------------------------------------------------------------
378
379function getCommonPlaylistEditAttributes () {
380 return [
381 body('thumbnailfile')
a1587156
C
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 ),
418d092a 387
418d092a
C
388 body('description')
389 .optional()
390 .customSanitizer(toValueOrNull)
391 .custom(isVideoPlaylistDescriptionValid).withMessage('Should have a valid description'),
392 body('privacy')
393 .optional()
c8861d5d 394 .customSanitizer(toIntOrNull)
418d092a
C
395 .custom(isVideoPlaylistPrivacyValid).withMessage('Should have correct playlist privacy'),
396 body('videoChannelId')
397 .optional()
c8861d5d 398 .customSanitizer(toIntOrNull)
ba5a8d89 399 ] as (ValidationChain | ExpressPromiseHandler)[]
418d092a
C
400}
401
453e83ea 402function checkUserCanManageVideoPlaylist (user: MUserAccountId, videoPlaylist: MVideoPlaylist, right: UserRight, res: express.Response) {
418d092a 403 if (videoPlaylist.isOwned() === false) {
2d53be02 404 res.status(HttpStatusCode.FORBIDDEN_403)
418d092a
C
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) {
2d53be02 415 res.status(HttpStatusCode.FORBIDDEN_403)
418d092a
C
416 .json({ error: 'Cannot manage video playlist of another user' })
417 .end()
418
419 return false
420 }
421
422 return true
423}
453e83ea
C
424
425function getPlaylist (res: express.Response) {
426 return res.locals.videoPlaylistFull || res.locals.videoPlaylistSummary
427}