]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/middlewares/validators/videos/video-live.ts
Allow to update a live with untouched privacy
[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 { VideoLiveSessionModel } from '@server/models/video/video-live-session'
10 import {
11 HttpStatusCode,
12 LiveVideoCreate,
13 LiveVideoLatencyMode,
14 LiveVideoUpdate,
15 ServerErrorCode,
16 UserRight,
17 VideoState
18 } from '@shared/models'
19 import { exists, isBooleanValid, isIdValid, toBooleanOrNull, toIntOrNull } from '../../../helpers/custom-validators/misc'
20 import { isVideoNameValid, isVideoPrivacyValid } from '../../../helpers/custom-validators/videos'
21 import { cleanUpReqFiles } from '../../../helpers/express-utils'
22 import { logger } from '../../../helpers/logger'
23 import { CONFIG } from '../../../initializers/config'
24 import {
25 areValidationErrors,
26 checkUserCanManageVideo,
27 doesVideoChannelOfAccountExist,
28 doesVideoExist,
29 isValidVideoIdParam
30 } from '../shared'
31 import { getCommonVideoEditAttributes } from './videos'
32
33 const videoLiveGetValidator = [
34 isValidVideoIdParam('videoId'),
35
36 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
37 if (areValidationErrors(req, res)) return
38 if (!await doesVideoExist(req.params.videoId, res, 'all')) return
39
40 const videoLive = await VideoLiveModel.loadByVideoId(res.locals.videoAll.id)
41 if (!videoLive) {
42 return res.fail({
43 status: HttpStatusCode.NOT_FOUND_404,
44 message: 'Live video not found'
45 })
46 }
47
48 res.locals.videoLive = videoLive
49
50 return next()
51 }
52 ]
53
54 const videoLiveAddValidator = getCommonVideoEditAttributes().concat([
55 body('channelId')
56 .customSanitizer(toIntOrNull)
57 .custom(isIdValid),
58
59 body('name')
60 .custom(isVideoNameValid).withMessage(
61 `Should have a video name between ${CONSTRAINTS_FIELDS.VIDEOS.NAME.min} and ${CONSTRAINTS_FIELDS.VIDEOS.NAME.max} characters long`
62 ),
63
64 body('saveReplay')
65 .optional()
66 .customSanitizer(toBooleanOrNull)
67 .custom(isBooleanValid).withMessage('Should have a valid saveReplay boolean'),
68
69 body('replaySettings.privacy')
70 .optional()
71 .customSanitizer(toIntOrNull)
72 .custom(isVideoPrivacyValid),
73
74 body('permanentLive')
75 .optional()
76 .customSanitizer(toBooleanOrNull)
77 .custom(isBooleanValid).withMessage('Should have a valid permanentLive boolean'),
78
79 body('latencyMode')
80 .optional()
81 .customSanitizer(toIntOrNull)
82 .custom(isLiveLatencyModeValid),
83
84 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
85 if (areValidationErrors(req, res)) return cleanUpReqFiles(req)
86
87 if (CONFIG.LIVE.ENABLED !== true) {
88 cleanUpReqFiles(req)
89
90 return res.fail({
91 status: HttpStatusCode.FORBIDDEN_403,
92 message: 'Live is not enabled on this instance',
93 type: ServerErrorCode.LIVE_NOT_ENABLED
94 })
95 }
96
97 const body: LiveVideoCreate = req.body
98
99 if (hasValidSaveReplay(body) !== true) {
100 cleanUpReqFiles(req)
101
102 return res.fail({
103 status: HttpStatusCode.FORBIDDEN_403,
104 message: 'Saving live replay is not enabled on this instance',
105 type: ServerErrorCode.LIVE_NOT_ALLOWING_REPLAY
106 })
107 }
108
109 if (hasValidLatencyMode(body) !== true) {
110 cleanUpReqFiles(req)
111
112 return res.fail({
113 status: HttpStatusCode.FORBIDDEN_403,
114 message: 'Custom latency mode is not allowed by this instance'
115 })
116 }
117
118 const user = res.locals.oauth.token.User
119 if (!await doesVideoChannelOfAccountExist(body.channelId, user, res)) return cleanUpReqFiles(req)
120
121 if (CONFIG.LIVE.MAX_INSTANCE_LIVES !== -1) {
122 const totalInstanceLives = await VideoModel.countLives({ remote: false, mode: 'not-ended' })
123
124 if (totalInstanceLives >= CONFIG.LIVE.MAX_INSTANCE_LIVES) {
125 cleanUpReqFiles(req)
126
127 return res.fail({
128 status: HttpStatusCode.FORBIDDEN_403,
129 message: 'Cannot create this live because the max instance lives limit is reached.',
130 type: ServerErrorCode.MAX_INSTANCE_LIVES_LIMIT_REACHED
131 })
132 }
133 }
134
135 if (CONFIG.LIVE.MAX_USER_LIVES !== -1) {
136 const totalUserLives = await VideoModel.countLivesOfAccount(user.Account.id)
137
138 if (totalUserLives >= CONFIG.LIVE.MAX_USER_LIVES) {
139 cleanUpReqFiles(req)
140
141 return res.fail({
142 status: HttpStatusCode.FORBIDDEN_403,
143 message: 'Cannot create this live because the max user lives limit is reached.',
144 type: ServerErrorCode.MAX_USER_LIVES_LIMIT_REACHED
145 })
146 }
147 }
148
149 if (!await isLiveVideoAccepted(req, res)) return cleanUpReqFiles(req)
150
151 return next()
152 }
153 ])
154
155 const videoLiveUpdateValidator = [
156 body('saveReplay')
157 .optional()
158 .customSanitizer(toBooleanOrNull)
159 .custom(isBooleanValid).withMessage('Should have a valid saveReplay boolean'),
160
161 body('replaySettings.privacy')
162 .optional()
163 .customSanitizer(toIntOrNull)
164 .custom(isVideoPrivacyValid),
165
166 body('latencyMode')
167 .optional()
168 .customSanitizer(toIntOrNull)
169 .custom(isLiveLatencyModeValid),
170
171 (req: express.Request, res: express.Response, next: express.NextFunction) => {
172 if (areValidationErrors(req, res)) return
173
174 const body: LiveVideoUpdate = req.body
175
176 if (hasValidSaveReplay(body) !== true) {
177 return res.fail({
178 status: HttpStatusCode.FORBIDDEN_403,
179 message: 'Saving live replay is not allowed by this instance'
180 })
181 }
182
183 if (hasValidLatencyMode(body) !== true) {
184 return res.fail({
185 status: HttpStatusCode.FORBIDDEN_403,
186 message: 'Custom latency mode is not allowed by this instance'
187 })
188 }
189
190 if (!checkLiveSettingsReplayConsistency({ res, body })) return
191
192 if (res.locals.videoAll.state !== VideoState.WAITING_FOR_LIVE) {
193 return res.fail({ message: 'Cannot update a live that has already started' })
194 }
195
196 // Check the user can manage the live
197 const user = res.locals.oauth.token.User
198 if (!checkUserCanManageVideo(user, res.locals.videoAll, UserRight.GET_ANY_LIVE, res)) return
199
200 return next()
201 }
202 ]
203
204 const videoLiveListSessionsValidator = [
205 (req: express.Request, res: express.Response, next: express.NextFunction) => {
206 // Check the user can manage the live
207 const user = res.locals.oauth.token.User
208 if (!checkUserCanManageVideo(user, res.locals.videoAll, UserRight.GET_ANY_LIVE, res)) return
209
210 return next()
211 }
212 ]
213
214 const videoLiveFindReplaySessionValidator = [
215 isValidVideoIdParam('videoId'),
216
217 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
218 if (areValidationErrors(req, res)) return
219 if (!await doesVideoExist(req.params.videoId, res, 'id')) return
220
221 const session = await VideoLiveSessionModel.findSessionOfReplay(res.locals.videoId.id)
222 if (!session) {
223 return res.fail({
224 status: HttpStatusCode.NOT_FOUND_404,
225 message: 'No live replay found'
226 })
227 }
228
229 res.locals.videoLiveSession = session
230
231 return next()
232 }
233 ]
234
235 // ---------------------------------------------------------------------------
236
237 export {
238 videoLiveAddValidator,
239 videoLiveUpdateValidator,
240 videoLiveListSessionsValidator,
241 videoLiveFindReplaySessionValidator,
242 videoLiveGetValidator
243 }
244
245 // ---------------------------------------------------------------------------
246
247 async function isLiveVideoAccepted (req: express.Request, res: express.Response) {
248 // Check we accept this video
249 const acceptParameters = {
250 liveVideoBody: req.body,
251 user: res.locals.oauth.token.User
252 }
253 const acceptedResult = await Hooks.wrapFun(
254 isLocalLiveVideoAccepted,
255 acceptParameters,
256 'filter:api.live-video.create.accept.result'
257 )
258
259 if (!acceptedResult || acceptedResult.accepted !== true) {
260 logger.info('Refused local live video.', { acceptedResult, acceptParameters })
261
262 res.fail({
263 status: HttpStatusCode.FORBIDDEN_403,
264 message: acceptedResult.errorMessage || 'Refused local live video'
265 })
266 return false
267 }
268
269 return true
270 }
271
272 function hasValidSaveReplay (body: LiveVideoUpdate | LiveVideoCreate) {
273 if (CONFIG.LIVE.ALLOW_REPLAY !== true && body.saveReplay === true) return false
274
275 return true
276 }
277
278 function hasValidLatencyMode (body: LiveVideoUpdate | LiveVideoCreate) {
279 if (
280 CONFIG.LIVE.LATENCY_SETTING.ENABLED !== true &&
281 exists(body.latencyMode) &&
282 body.latencyMode !== LiveVideoLatencyMode.DEFAULT
283 ) return false
284
285 return true
286 }
287
288 function checkLiveSettingsReplayConsistency (options: {
289 res: express.Response
290 body: LiveVideoUpdate
291 }) {
292 const { res, body } = options
293
294 // We now save replays of this live, so replay settings are mandatory
295 if (res.locals.videoLive.saveReplay !== true && body.saveReplay === true) {
296
297 if (!exists(body.replaySettings)) {
298 res.fail({
299 status: HttpStatusCode.BAD_REQUEST_400,
300 message: 'Replay settings are missing now the live replay is saved'
301 })
302 return false
303 }
304
305 if (!exists(body.replaySettings.privacy)) {
306 res.fail({
307 status: HttpStatusCode.BAD_REQUEST_400,
308 message: 'Privacy replay setting is missing now the live replay is saved'
309 })
310 return false
311 }
312 }
313
314 // Save replay was and is not enabled, so send an error the user if it specified replay settings
315 if ((!exists(body.saveReplay) && res.locals.videoLive.saveReplay === false) || body.saveReplay === false) {
316 if (exists(body.replaySettings)) {
317 res.fail({
318 status: HttpStatusCode.BAD_REQUEST_400,
319 message: 'Cannot save replay settings since live replay is not enabled'
320 })
321 return false
322 }
323 }
324
325 return true
326 }