]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/middlewares/validators/videos/video-playlists.ts
Add tags to AP rate logger
[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
50 return res.fail({ message: '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
89 return res.fail({ message: '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
95 return res.fail({ message: '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.fail({ message: 'Cannot delete a watch later playlist.' })
118 }
119
120 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.REMOVE_ANY_VIDEO_PLAYLIST, res)) {
121 return
122 }
123
124 return next()
125 }
126 ]
127
128 const videoPlaylistsGetValidator = (fetchType: VideoPlaylistFetchType) => {
129 return [
130 param('playlistId')
131 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
132
133 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
134 logger.debug('Checking videoPlaylistsGetValidator parameters', { parameters: req.params })
135
136 if (areValidationErrors(req, res)) return
137
138 if (!await doesVideoPlaylistExist(req.params.playlistId, res, fetchType)) return
139
140 const videoPlaylist = res.locals.videoPlaylistFull || res.locals.videoPlaylistSummary
141
142 // Video is unlisted, check we used the uuid to fetch it
143 if (videoPlaylist.privacy === VideoPlaylistPrivacy.UNLISTED) {
144 if (isUUIDValid(req.params.playlistId)) return next()
145
146 return res.fail({
147 status: HttpStatusCode.NOT_FOUND_404,
148 message: 'Playlist not found'
149 })
150 }
151
152 if (videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
153 await authenticatePromiseIfNeeded(req, res)
154
155 const user = res.locals.oauth ? res.locals.oauth.token.User : null
156
157 if (
158 !user ||
159 (videoPlaylist.OwnerAccount.id !== user.Account.id && !user.hasRight(UserRight.UPDATE_ANY_VIDEO_PLAYLIST))
160 ) {
161 return res.fail({
162 status: HttpStatusCode.FORBIDDEN_403,
163 message: 'Cannot get this private video playlist.'
164 })
165 }
166
167 return next()
168 }
169
170 return next()
171 }
172 ]
173 }
174
175 const videoPlaylistsSearchValidator = [
176 query('search').optional().not().isEmpty().withMessage('Should have a valid search'),
177
178 (req: express.Request, res: express.Response, next: express.NextFunction) => {
179 logger.debug('Checking videoPlaylists search query', { parameters: req.query })
180
181 if (areValidationErrors(req, res)) return
182
183 return next()
184 }
185 ]
186
187 const videoPlaylistsAddVideoValidator = [
188 param('playlistId')
189 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
190 body('videoId')
191 .custom(isIdOrUUIDValid).withMessage('Should have a valid video id/uuid'),
192 body('startTimestamp')
193 .optional()
194 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid start timestamp'),
195 body('stopTimestamp')
196 .optional()
197 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid stop timestamp'),
198
199 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
200 logger.debug('Checking videoPlaylistsAddVideoValidator parameters', { parameters: req.params })
201
202 if (areValidationErrors(req, res)) return
203
204 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
205 if (!await doesVideoExist(req.body.videoId, res, 'only-video')) return
206
207 const videoPlaylist = getPlaylist(res)
208
209 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) {
210 return
211 }
212
213 return next()
214 }
215 ]
216
217 const videoPlaylistsUpdateOrRemoveVideoValidator = [
218 param('playlistId')
219 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
220 param('playlistElementId')
221 .custom(isIdValid).withMessage('Should have an element id/uuid'),
222 body('startTimestamp')
223 .optional()
224 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid start timestamp'),
225 body('stopTimestamp')
226 .optional()
227 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid stop timestamp'),
228
229 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
230 logger.debug('Checking videoPlaylistsRemoveVideoValidator parameters', { parameters: req.params })
231
232 if (areValidationErrors(req, res)) return
233
234 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
235
236 const videoPlaylist = getPlaylist(res)
237
238 const videoPlaylistElement = await VideoPlaylistElementModel.loadById(req.params.playlistElementId)
239 if (!videoPlaylistElement) {
240 res.fail({
241 status: HttpStatusCode.NOT_FOUND_404,
242 message: 'Video playlist element not found'
243 })
244 return
245 }
246 res.locals.videoPlaylistElement = videoPlaylistElement
247
248 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) return
249
250 return next()
251 }
252 ]
253
254 const videoPlaylistElementAPGetValidator = [
255 param('playlistId')
256 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
257 param('playlistElementId')
258 .custom(isIdValid).withMessage('Should have an playlist element id'),
259
260 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
261 logger.debug('Checking videoPlaylistElementAPGetValidator parameters', { parameters: req.params })
262
263 if (areValidationErrors(req, res)) return
264
265 const playlistElementId = parseInt(req.params.playlistElementId + '', 10)
266 const playlistId = req.params.playlistId
267
268 const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndElementIdForAP(playlistId, playlistElementId)
269 if (!videoPlaylistElement) {
270 res.fail({
271 status: HttpStatusCode.NOT_FOUND_404,
272 message: 'Video playlist element not found'
273 })
274 return
275 }
276
277 if (videoPlaylistElement.VideoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
278 return res.fail({
279 status: HttpStatusCode.FORBIDDEN_403,
280 message: 'Cannot get this private video playlist.'
281 })
282 }
283
284 res.locals.videoPlaylistElementAP = videoPlaylistElement
285
286 return next()
287 }
288 ]
289
290 const videoPlaylistsReorderVideosValidator = [
291 param('playlistId')
292 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
293 body('startPosition')
294 .isInt({ min: 1 }).withMessage('Should have a valid start position'),
295 body('insertAfterPosition')
296 .isInt({ min: 0 }).withMessage('Should have a valid insert after position'),
297 body('reorderLength')
298 .optional()
299 .isInt({ min: 1 }).withMessage('Should have a valid range length'),
300
301 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
302 logger.debug('Checking videoPlaylistsReorderVideosValidator parameters', { parameters: req.params })
303
304 if (areValidationErrors(req, res)) return
305
306 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
307
308 const videoPlaylist = getPlaylist(res)
309 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) return
310
311 const nextPosition = await VideoPlaylistElementModel.getNextPositionOf(videoPlaylist.id)
312 const startPosition: number = req.body.startPosition
313 const insertAfterPosition: number = req.body.insertAfterPosition
314 const reorderLength: number = req.body.reorderLength
315
316 if (startPosition >= nextPosition || insertAfterPosition >= nextPosition) {
317 res.fail({ message: `Start position or insert after position exceed the playlist limits (max: ${nextPosition - 1})` })
318 return
319 }
320
321 if (reorderLength && reorderLength + startPosition > nextPosition) {
322 res.fail({ message: `Reorder length with this start position exceeds the playlist limits (max: ${nextPosition - startPosition})` })
323 return
324 }
325
326 return next()
327 }
328 ]
329
330 const commonVideoPlaylistFiltersValidator = [
331 query('playlistType')
332 .optional()
333 .custom(isVideoPlaylistTypeValid).withMessage('Should have a valid playlist type'),
334
335 (req: express.Request, res: express.Response, next: express.NextFunction) => {
336 logger.debug('Checking commonVideoPlaylistFiltersValidator parameters', { parameters: req.params })
337
338 if (areValidationErrors(req, res)) return
339
340 return next()
341 }
342 ]
343
344 const doVideosInPlaylistExistValidator = [
345 query('videoIds')
346 .customSanitizer(toIntArray)
347 .custom(v => isArrayOf(v, isIdValid)).withMessage('Should have a valid video ids array'),
348
349 (req: express.Request, res: express.Response, next: express.NextFunction) => {
350 logger.debug('Checking areVideosInPlaylistExistValidator parameters', { parameters: req.query })
351
352 if (areValidationErrors(req, res)) return
353
354 return next()
355 }
356 ]
357
358 // ---------------------------------------------------------------------------
359
360 export {
361 videoPlaylistsAddValidator,
362 videoPlaylistsUpdateValidator,
363 videoPlaylistsDeleteValidator,
364 videoPlaylistsGetValidator,
365 videoPlaylistsSearchValidator,
366
367 videoPlaylistsAddVideoValidator,
368 videoPlaylistsUpdateOrRemoveVideoValidator,
369 videoPlaylistsReorderVideosValidator,
370
371 videoPlaylistElementAPGetValidator,
372
373 commonVideoPlaylistFiltersValidator,
374
375 doVideosInPlaylistExistValidator
376 }
377
378 // ---------------------------------------------------------------------------
379
380 function getCommonPlaylistEditAttributes () {
381 return [
382 body('thumbnailfile')
383 .custom((value, { req }) => isVideoImage(req.files, 'thumbnailfile'))
384 .withMessage(
385 'This thumbnail file is not supported or too large. Please, make sure it is of the following type: ' +
386 CONSTRAINTS_FIELDS.VIDEO_PLAYLISTS.IMAGE.EXTNAME.join(', ')
387 ),
388
389 body('description')
390 .optional()
391 .customSanitizer(toValueOrNull)
392 .custom(isVideoPlaylistDescriptionValid).withMessage('Should have a valid description'),
393 body('privacy')
394 .optional()
395 .customSanitizer(toIntOrNull)
396 .custom(isVideoPlaylistPrivacyValid).withMessage('Should have correct playlist privacy'),
397 body('videoChannelId')
398 .optional()
399 .customSanitizer(toIntOrNull)
400 ] as (ValidationChain | ExpressPromiseHandler)[]
401 }
402
403 function checkUserCanManageVideoPlaylist (user: MUserAccountId, videoPlaylist: MVideoPlaylist, right: UserRight, res: express.Response) {
404 if (videoPlaylist.isOwned() === false) {
405 res.fail({
406 status: HttpStatusCode.FORBIDDEN_403,
407 message: 'Cannot manage video playlist of another server.'
408 })
409 return false
410 }
411
412 // Check if the user can manage the video playlist
413 // The user can delete it if s/he is an admin
414 // Or if s/he is the video playlist's owner
415 if (user.hasRight(right) === false && videoPlaylist.ownerAccountId !== user.Account.id) {
416 res.fail({
417 status: HttpStatusCode.FORBIDDEN_403,
418 message: 'Cannot manage video playlist of another user'
419 })
420 return false
421 }
422
423 return true
424 }
425
426 function getPlaylist (res: express.Response) {
427 return res.locals.videoPlaylistFull || res.locals.videoPlaylistSummary
428 }