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