]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/middlewares/validators/videos/video-live.ts
Improve views/viewers documentation
[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 if (body.permanentLive && body.saveReplay) {
122 cleanUpReqFiles(req)
123
124 return res.fail({ message: 'Cannot set this live as permanent while saving its replay' })
125 }
126
127 const user = res.locals.oauth.token.User
128 if (!await doesVideoChannelOfAccountExist(body.channelId, user, res)) return cleanUpReqFiles(req)
129
130 if (CONFIG.LIVE.MAX_INSTANCE_LIVES !== -1) {
131 const totalInstanceLives = await VideoModel.countLocalLives()
132
133 if (totalInstanceLives >= CONFIG.LIVE.MAX_INSTANCE_LIVES) {
134 cleanUpReqFiles(req)
135
136 return res.fail({
137 status: HttpStatusCode.FORBIDDEN_403,
138 message: 'Cannot create this live because the max instance lives limit is reached.',
139 type: ServerErrorCode.MAX_INSTANCE_LIVES_LIMIT_REACHED
140 })
141 }
142 }
143
144 if (CONFIG.LIVE.MAX_USER_LIVES !== -1) {
145 const totalUserLives = await VideoModel.countLivesOfAccount(user.Account.id)
146
147 if (totalUserLives >= CONFIG.LIVE.MAX_USER_LIVES) {
148 cleanUpReqFiles(req)
149
150 return res.fail({
151 status: HttpStatusCode.FORBIDDEN_403,
152 message: 'Cannot create this live because the max user lives limit is reached.',
153 type: ServerErrorCode.MAX_USER_LIVES_LIMIT_REACHED
154 })
155 }
156 }
157
158 if (!await isLiveVideoAccepted(req, res)) return cleanUpReqFiles(req)
159
160 return next()
161 }
162 ])
163
164 const videoLiveUpdateValidator = [
165 body('saveReplay')
166 .optional()
167 .customSanitizer(toBooleanOrNull)
168 .custom(isBooleanValid).withMessage('Should have a valid saveReplay attribute'),
169
170 body('latencyMode')
171 .optional()
172 .customSanitizer(toIntOrNull)
173 .custom(isLiveLatencyModeValid)
174 .withMessage('Should have a valid latency mode attribute'),
175
176 (req: express.Request, res: express.Response, next: express.NextFunction) => {
177 logger.debug('Checking videoLiveUpdateValidator parameters', { parameters: req.body })
178
179 if (areValidationErrors(req, res)) return
180
181 const body: LiveVideoUpdate = req.body
182
183 if (body.permanentLive && body.saveReplay) {
184 return res.fail({ message: 'Cannot set this live as permanent while saving its replay' })
185 }
186
187 if (hasValidSaveReplay(body) !== true) {
188 return res.fail({
189 status: HttpStatusCode.FORBIDDEN_403,
190 message: 'Saving live replay is not allowed by this instance'
191 })
192 }
193
194 if (hasValidLatencyMode(body) !== true) {
195 return res.fail({
196 status: HttpStatusCode.FORBIDDEN_403,
197 message: 'Custom latency mode is not allowed by this instance'
198 })
199 }
200
201 if (res.locals.videoAll.state !== VideoState.WAITING_FOR_LIVE) {
202 return res.fail({ message: 'Cannot update a live that has already started' })
203 }
204
205 // Check the user can manage the live
206 const user = res.locals.oauth.token.User
207 if (!checkUserCanManageVideo(user, res.locals.videoAll, UserRight.GET_ANY_LIVE, res)) return
208
209 return next()
210 }
211 ]
212
213 // ---------------------------------------------------------------------------
214
215 export {
216 videoLiveAddValidator,
217 videoLiveUpdateValidator,
218 videoLiveGetValidator
219 }
220
221 // ---------------------------------------------------------------------------
222
223 async function isLiveVideoAccepted (req: express.Request, res: express.Response) {
224 // Check we accept this video
225 const acceptParameters = {
226 liveVideoBody: req.body,
227 user: res.locals.oauth.token.User
228 }
229 const acceptedResult = await Hooks.wrapFun(
230 isLocalLiveVideoAccepted,
231 acceptParameters,
232 'filter:api.live-video.create.accept.result'
233 )
234
235 if (!acceptedResult || acceptedResult.accepted !== true) {
236 logger.info('Refused local live video.', { acceptedResult, acceptParameters })
237
238 res.fail({
239 status: HttpStatusCode.FORBIDDEN_403,
240 message: acceptedResult.errorMessage || 'Refused local live video'
241 })
242 return false
243 }
244
245 return true
246 }
247
248 function hasValidSaveReplay (body: LiveVideoUpdate | LiveVideoCreate) {
249 if (CONFIG.LIVE.ALLOW_REPLAY !== true && body.saveReplay === true) return false
250
251 return true
252 }
253
254 function hasValidLatencyMode (body: LiveVideoUpdate | LiveVideoCreate) {
255 if (
256 CONFIG.LIVE.LATENCY_SETTING.ENABLED !== true &&
257 exists(body.latencyMode) &&
258 body.latencyMode !== LiveVideoLatencyMode.DEFAULT
259 ) return false
260
261 return true
262 }