]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/middlewares/validators/videos/video-playlists.ts
Add tags to AP rate logger
[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)
76148b27
RK
49
50 return res.fail({ message: 'Cannot set "public" a playlist that is not assigned to a channel.' })
c5e4e36d 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)
76148b27
RK
88
89 return res.fail({ message: 'Cannot set "public" a playlist that is not assigned to a channel.' })
c5e4e36d
C
90 }
91
df0b219d
C
92 if (videoPlaylist.type === VideoPlaylistType.WATCH_LATER) {
93 cleanUpReqFiles(req)
76148b27
RK
94
95 return res.fail({ message: 'Cannot update a watch later playlist.' })
df0b219d
C
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) {
76148b27 117 return res.fail({ message: 'Cannot delete a watch later playlist.' })
df0b219d
C
118 }
119
453e83ea 120 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.REMOVE_ANY_VIDEO_PLAYLIST, res)) {
418d092a
C
121 return
122 }
123
124 return next()
125 }
126]
127
453e83ea
C
128const videoPlaylistsGetValidator = (fetchType: VideoPlaylistFetchType) => {
129 return [
130 param('playlistId')
131 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
418d092a 132
453e83ea
C
133 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
134 logger.debug('Checking videoPlaylistsGetValidator parameters', { parameters: req.params })
418d092a 135
453e83ea 136 if (areValidationErrors(req, res)) return
418d092a 137
453e83ea 138 if (!await doesVideoPlaylistExist(req.params.playlistId, res, fetchType)) return
418d092a 139
453e83ea 140 const videoPlaylist = res.locals.videoPlaylistFull || res.locals.videoPlaylistSummary
07b1a18a 141
453e83ea
C
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()
07b1a18a 145
76148b27
RK
146 return res.fail({
147 status: HttpStatusCode.NOT_FOUND_404,
148 message: 'Playlist not found'
149 })
453e83ea 150 }
07b1a18a 151
453e83ea
C
152 if (videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
153 await authenticatePromiseIfNeeded(req, res)
418d092a 154
453e83ea 155 const user = res.locals.oauth ? res.locals.oauth.token.User : null
4d09cfba 156
453e83ea
C
157 if (
158 !user ||
159 (videoPlaylist.OwnerAccount.id !== user.Account.id && !user.hasRight(UserRight.UPDATE_ANY_VIDEO_PLAYLIST))
160 ) {
76148b27
RK
161 return res.fail({
162 status: HttpStatusCode.FORBIDDEN_403,
163 message: 'Cannot get this private video playlist.'
164 })
453e83ea
C
165 }
166
167 return next()
418d092a
C
168 }
169
170 return next()
171 }
453e83ea
C
172 ]
173}
418d092a 174
c06af501
RK
175const 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
418d092a
C
187const 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()
df0b219d 194 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid start timestamp'),
418d092a
C
195 body('stopTimestamp')
196 .optional()
df0b219d 197 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid stop timestamp'),
418d092a
C
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
0f6acda1
C
204 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
205 if (!await doesVideoExist(req.body.videoId, res, 'only-video')) return
418d092a 206
453e83ea 207 const videoPlaylist = getPlaylist(res)
418d092a 208
453e83ea 209 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) {
418d092a
C
210 return
211 }
212
213 return next()
214 }
215]
216
217const videoPlaylistsUpdateOrRemoveVideoValidator = [
218 param('playlistId')
219 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
bfbd9128
C
220 param('playlistElementId')
221 .custom(isIdValid).withMessage('Should have an element id/uuid'),
418d092a
C
222 body('startTimestamp')
223 .optional()
df0b219d 224 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid start timestamp'),
418d092a
C
225 body('stopTimestamp')
226 .optional()
df0b219d 227 .custom(isVideoPlaylistTimestampValid).withMessage('Should have a valid stop timestamp'),
418d092a
C
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
0f6acda1 234 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
418d092a 235
453e83ea 236 const videoPlaylist = getPlaylist(res)
418d092a 237
bfbd9128 238 const videoPlaylistElement = await VideoPlaylistElementModel.loadById(req.params.playlistElementId)
418d092a 239 if (!videoPlaylistElement) {
76148b27
RK
240 res.fail({
241 status: HttpStatusCode.NOT_FOUND_404,
242 message: 'Video playlist element not found'
243 })
418d092a
C
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
254const videoPlaylistElementAPGetValidator = [
255 param('playlistId')
256 .custom(isIdOrUUIDValid).withMessage('Should have a valid playlist id/uuid'),
37190663
C
257 param('playlistElementId')
258 .custom(isIdValid).withMessage('Should have an playlist element id'),
418d092a
C
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
37190663
C
265 const playlistElementId = parseInt(req.params.playlistElementId + '', 10)
266 const playlistId = req.params.playlistId
267
268 const videoPlaylistElement = await VideoPlaylistElementModel.loadByPlaylistAndElementIdForAP(playlistId, playlistElementId)
418d092a 269 if (!videoPlaylistElement) {
76148b27
RK
270 res.fail({
271 status: HttpStatusCode.NOT_FOUND_404,
272 message: 'Video playlist element not found'
273 })
418d092a
C
274 return
275 }
276
277 if (videoPlaylistElement.VideoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
76148b27
RK
278 return res.fail({
279 status: HttpStatusCode.FORBIDDEN_403,
280 message: 'Cannot get this private video playlist.'
281 })
418d092a
C
282 }
283
b5fecbf4 284 res.locals.videoPlaylistElementAP = videoPlaylistElement
418d092a
C
285
286 return next()
287 }
288]
289
290const 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
0f6acda1 306 if (!await doesVideoPlaylistExist(req.params.playlistId, res, 'all')) return
418d092a 307
453e83ea 308 const videoPlaylist = getPlaylist(res)
418d092a
C
309 if (!checkUserCanManageVideoPlaylist(res.locals.oauth.token.User, videoPlaylist, UserRight.UPDATE_ANY_VIDEO_PLAYLIST, res)) return
310
07b1a18a
C
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) {
76148b27 317 res.fail({ message: `Start position or insert after position exceed the playlist limits (max: ${nextPosition - 1})` })
07b1a18a
C
318 return
319 }
320
321 if (reorderLength && reorderLength + startPosition > nextPosition) {
76148b27 322 res.fail({ message: `Reorder length with this start position exceeds the playlist limits (max: ${nextPosition - startPosition})` })
07b1a18a
C
323 return
324 }
325
418d092a
C
326 return next()
327 }
328]
329
df0b219d
C
330const 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
f0a39880
C
344const 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
418d092a
C
358// ---------------------------------------------------------------------------
359
360export {
361 videoPlaylistsAddValidator,
362 videoPlaylistsUpdateValidator,
363 videoPlaylistsDeleteValidator,
364 videoPlaylistsGetValidator,
c06af501 365 videoPlaylistsSearchValidator,
418d092a
C
366
367 videoPlaylistsAddVideoValidator,
368 videoPlaylistsUpdateOrRemoveVideoValidator,
369 videoPlaylistsReorderVideosValidator,
370
df0b219d
C
371 videoPlaylistElementAPGetValidator,
372
f0a39880
C
373 commonVideoPlaylistFiltersValidator,
374
375 doVideosInPlaylistExistValidator
418d092a
C
376}
377
378// ---------------------------------------------------------------------------
379
380function getCommonPlaylistEditAttributes () {
381 return [
382 body('thumbnailfile')
a1587156
C
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 ),
418d092a 388
418d092a
C
389 body('description')
390 .optional()
391 .customSanitizer(toValueOrNull)
392 .custom(isVideoPlaylistDescriptionValid).withMessage('Should have a valid description'),
393 body('privacy')
394 .optional()
c8861d5d 395 .customSanitizer(toIntOrNull)
418d092a
C
396 .custom(isVideoPlaylistPrivacyValid).withMessage('Should have correct playlist privacy'),
397 body('videoChannelId')
398 .optional()
c8861d5d 399 .customSanitizer(toIntOrNull)
ba5a8d89 400 ] as (ValidationChain | ExpressPromiseHandler)[]
418d092a
C
401}
402
453e83ea 403function checkUserCanManageVideoPlaylist (user: MUserAccountId, videoPlaylist: MVideoPlaylist, right: UserRight, res: express.Response) {
418d092a 404 if (videoPlaylist.isOwned() === false) {
76148b27
RK
405 res.fail({
406 status: HttpStatusCode.FORBIDDEN_403,
407 message: 'Cannot manage video playlist of another server.'
408 })
418d092a
C
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) {
76148b27
RK
416 res.fail({
417 status: HttpStatusCode.FORBIDDEN_403,
418 message: 'Cannot manage video playlist of another user'
419 })
418d092a
C
420 return false
421 }
422
423 return true
424}
453e83ea
C
425
426function getPlaylist (res: express.Response) {
427 return res.locals.videoPlaylistFull || res.locals.videoPlaylistSummary
428}