]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/middlewares/validators/videos/video-live.ts
Move middleware utils in middlewares
[github/Chocobozzz/PeerTube.git] / server / middlewares / validators / videos / video-live.ts
1 import * as express from 'express'
2 import { body, param } from 'express-validator'
3 import { CONSTRAINTS_FIELDS } from '@server/initializers/constants'
4 import { isLocalLiveVideoAccepted } from '@server/lib/moderation'
5 import { Hooks } from '@server/lib/plugins/hooks'
6 import { VideoModel } from '@server/models/video/video'
7 import { VideoLiveModel } from '@server/models/video/video-live'
8 import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
9 import { ServerErrorCode, UserRight, VideoState } from '@shared/models'
10 import { isBooleanValid, isIdOrUUIDValid, isIdValid, toBooleanOrNull, toIntOrNull } from '../../../helpers/custom-validators/misc'
11 import { isVideoNameValid } from '../../../helpers/custom-validators/videos'
12 import { cleanUpReqFiles } from '../../../helpers/express-utils'
13 import { logger } from '../../../helpers/logger'
14 import { CONFIG } from '../../../initializers/config'
15 import { areValidationErrors, checkUserCanManageVideo, doesVideoChannelOfAccountExist, doesVideoExist } from '../shared'
16 import { getCommonVideoEditAttributes } from './videos'
17
18 const videoLiveGetValidator = [
19 param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid videoId'),
20
21 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
22 logger.debug('Checking videoLiveGetValidator parameters', { parameters: req.params, user: res.locals.oauth.token.User.username })
23
24 if (areValidationErrors(req, res)) return
25 if (!await doesVideoExist(req.params.videoId, res, 'all')) return
26
27 // Check if the user who did the request is able to get the live info
28 const user = res.locals.oauth.token.User
29 if (!checkUserCanManageVideo(user, res.locals.videoAll, UserRight.GET_ANY_LIVE, res, false)) return
30
31 const videoLive = await VideoLiveModel.loadByVideoId(res.locals.videoAll.id)
32 if (!videoLive) {
33 return res.fail({
34 status: HttpStatusCode.NOT_FOUND_404,
35 message: 'Live video not found'
36 })
37 }
38
39 res.locals.videoLive = videoLive
40
41 return next()
42 }
43 ]
44
45 const videoLiveAddValidator = getCommonVideoEditAttributes().concat([
46 body('channelId')
47 .customSanitizer(toIntOrNull)
48 .custom(isIdValid).withMessage('Should have correct video channel id'),
49
50 body('name')
51 .custom(isVideoNameValid).withMessage(
52 `Should have a video name between ${CONSTRAINTS_FIELDS.VIDEOS.NAME.min} and ${CONSTRAINTS_FIELDS.VIDEOS.NAME.max} characters long`
53 ),
54
55 body('saveReplay')
56 .optional()
57 .customSanitizer(toBooleanOrNull)
58 .custom(isBooleanValid).withMessage('Should have a valid saveReplay attribute'),
59
60 body('permanentLive')
61 .optional()
62 .customSanitizer(toBooleanOrNull)
63 .custom(isBooleanValid).withMessage('Should have a valid permanentLive attribute'),
64
65 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
66 logger.debug('Checking videoLiveAddValidator parameters', { parameters: req.body })
67
68 if (areValidationErrors(req, res)) return cleanUpReqFiles(req)
69
70 if (CONFIG.LIVE.ENABLED !== true) {
71 cleanUpReqFiles(req)
72
73 return res.fail({
74 status: HttpStatusCode.FORBIDDEN_403,
75 message: 'Live is not enabled on this instance'
76 })
77 }
78
79 if (CONFIG.LIVE.ALLOW_REPLAY !== true && req.body.saveReplay === true) {
80 cleanUpReqFiles(req)
81
82 return res.fail({
83 status: HttpStatusCode.FORBIDDEN_403,
84 message: 'Saving live replay is not allowed instance'
85 })
86 }
87
88 if (req.body.permanentLive && req.body.saveReplay) {
89 cleanUpReqFiles(req)
90
91 return res.fail({ message: 'Cannot set this live as permanent while saving its replay' })
92 }
93
94 const user = res.locals.oauth.token.User
95 if (!await doesVideoChannelOfAccountExist(req.body.channelId, user, res)) return cleanUpReqFiles(req)
96
97 if (CONFIG.LIVE.MAX_INSTANCE_LIVES !== -1) {
98 const totalInstanceLives = await VideoModel.countLocalLives()
99
100 if (totalInstanceLives >= CONFIG.LIVE.MAX_INSTANCE_LIVES) {
101 cleanUpReqFiles(req)
102
103 return res.fail({
104 status: HttpStatusCode.FORBIDDEN_403,
105 message: 'Cannot create this live because the max instance lives limit is reached.',
106 type: ServerErrorCode.MAX_INSTANCE_LIVES_LIMIT_REACHED
107 })
108 }
109 }
110
111 if (CONFIG.LIVE.MAX_USER_LIVES !== -1) {
112 const totalUserLives = await VideoModel.countLivesOfAccount(user.Account.id)
113
114 if (totalUserLives >= CONFIG.LIVE.MAX_USER_LIVES) {
115 cleanUpReqFiles(req)
116
117 return res.fail({
118 status: HttpStatusCode.FORBIDDEN_403,
119 type: ServerErrorCode.MAX_USER_LIVES_LIMIT_REACHED,
120 message: 'Cannot create this live because the max user lives limit is reached.'
121 })
122 }
123 }
124
125 if (!await isLiveVideoAccepted(req, res)) return cleanUpReqFiles(req)
126
127 return next()
128 }
129 ])
130
131 const videoLiveUpdateValidator = [
132 body('saveReplay')
133 .optional()
134 .customSanitizer(toBooleanOrNull)
135 .custom(isBooleanValid).withMessage('Should have a valid saveReplay attribute'),
136
137 (req: express.Request, res: express.Response, next: express.NextFunction) => {
138 logger.debug('Checking videoLiveUpdateValidator parameters', { parameters: req.body })
139
140 if (areValidationErrors(req, res)) return
141
142 if (req.body.permanentLive && req.body.saveReplay) {
143 return res.fail({ message: 'Cannot set this live as permanent while saving its replay' })
144 }
145
146 if (CONFIG.LIVE.ALLOW_REPLAY !== true && req.body.saveReplay === true) {
147 return res.fail({
148 status: HttpStatusCode.FORBIDDEN_403,
149 message: 'Saving live replay is not allowed instance'
150 })
151 }
152
153 if (res.locals.videoAll.state !== VideoState.WAITING_FOR_LIVE) {
154 return res.fail({ message: 'Cannot update a live that has already started' })
155 }
156
157 // Check the user can manage the live
158 const user = res.locals.oauth.token.User
159 if (!checkUserCanManageVideo(user, res.locals.videoAll, UserRight.GET_ANY_LIVE, res)) return
160
161 return next()
162 }
163 ]
164
165 // ---------------------------------------------------------------------------
166
167 export {
168 videoLiveAddValidator,
169 videoLiveUpdateValidator,
170 videoLiveGetValidator
171 }
172
173 // ---------------------------------------------------------------------------
174
175 async function isLiveVideoAccepted (req: express.Request, res: express.Response) {
176 // Check we accept this video
177 const acceptParameters = {
178 liveVideoBody: req.body,
179 user: res.locals.oauth.token.User
180 }
181 const acceptedResult = await Hooks.wrapFun(
182 isLocalLiveVideoAccepted,
183 acceptParameters,
184 'filter:api.live-video.create.accept.result'
185 )
186
187 if (!acceptedResult || acceptedResult.accepted !== true) {
188 logger.info('Refused local live video.', { acceptedResult, acceptParameters })
189
190 res.fail({
191 status: HttpStatusCode.FORBIDDEN_403,
192 message: acceptedResult.errorMessage || 'Refused local live video'
193 })
194 return false
195 }
196
197 return true
198 }