]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/middlewares/validators/videos/video-view.ts
Clearer video creation from API regarding rates
[github/Chocobozzz/PeerTube.git] / server / middlewares / validators / videos / video-view.ts
1 import express from 'express'
2 import { body, param } from 'express-validator'
3 import { isVideoTimeValid } from '@server/helpers/custom-validators/video-view'
4 import { LocalVideoViewerModel } from '@server/models/view/local-video-viewer'
5 import { HttpStatusCode } from '../../../../shared/models/http/http-error-codes'
6 import { exists, isIdValid, isIntOrNull, toIntOrNull } from '../../../helpers/custom-validators/misc'
7 import { logger } from '../../../helpers/logger'
8 import { areValidationErrors, doesVideoExist, isValidVideoIdParam } from '../shared'
9
10 const getVideoLocalViewerValidator = [
11 param('localViewerId')
12 .custom(isIdValid).withMessage('Should have a valid local viewer id'),
13
14 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
15 logger.debug('Checking getVideoLocalViewerValidator parameters', { parameters: req.params })
16
17 if (areValidationErrors(req, res)) return
18
19 const localViewer = await LocalVideoViewerModel.loadFullById(+req.params.localViewerId)
20 if (!localViewer) {
21 return res.fail({
22 status: HttpStatusCode.NOT_FOUND_404,
23 message: 'Local viewer not found'
24 })
25 }
26
27 res.locals.localViewerFull = localViewer
28
29 return next()
30 }
31 ]
32
33 const videoViewValidator = [
34 isValidVideoIdParam('videoId'),
35
36 body('currentTime')
37 .optional() // TODO: remove optional in a few versions, introduced in 4.2
38 .customSanitizer(toIntOrNull)
39 .custom(isIntOrNull).withMessage('Should have correct current time'),
40
41 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
42 logger.debug('Checking videoView parameters', { parameters: req.body })
43
44 if (areValidationErrors(req, res)) return
45 if (!await doesVideoExist(req.params.videoId, res, 'only-video')) return
46
47 const video = res.locals.onlyVideo
48 const videoDuration = video.isLive
49 ? undefined
50 : video.duration
51
52 if (!exists(req.body.currentTime)) { // TODO: remove in a few versions, introduced in 4.2
53 req.body.currentTime = Math.min(videoDuration ?? 0, 30)
54 }
55
56 const currentTime: number = req.body.currentTime
57
58 if (!isVideoTimeValid(currentTime, videoDuration)) {
59 return res.fail({
60 status: HttpStatusCode.BAD_REQUEST_400,
61 message: 'Current time is invalid'
62 })
63 }
64
65 return next()
66 }
67 ]
68
69 // ---------------------------------------------------------------------------
70
71 export {
72 videoViewValidator,
73 getVideoLocalViewerValidator
74 }