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