]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/live.ts
Fix getting live by anonymous user
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / live.ts
1 import express from 'express'
2 import { exists } from '@server/helpers/custom-validators/misc'
3 import { createReqFiles } from '@server/helpers/express-utils'
4 import { ASSETS_PATH, MIMETYPES } from '@server/initializers/constants'
5 import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url'
6 import { federateVideoIfNeeded } from '@server/lib/activitypub/videos'
7 import { Hooks } from '@server/lib/plugins/hooks'
8 import { buildLocalVideoFromReq, buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video'
9 import { videoLiveAddValidator, videoLiveGetValidator, videoLiveUpdateValidator } from '@server/middlewares/validators/videos/video-live'
10 import { VideoLiveModel } from '@server/models/video/video-live'
11 import { MVideoDetails, MVideoFullLight } from '@server/types/models'
12 import { buildUUID, uuidToShort } from '@shared/extra-utils'
13 import { HttpStatusCode, LiveVideoCreate, LiveVideoLatencyMode, LiveVideoUpdate, UserRight, VideoState } from '@shared/models'
14 import { logger } from '../../../helpers/logger'
15 import { sequelizeTypescript } from '../../../initializers/database'
16 import { updateVideoMiniatureFromExisting } from '../../../lib/thumbnail'
17 import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, optionalAuthenticate } from '../../../middlewares'
18 import { VideoModel } from '../../../models/video/video'
19
20 const liveRouter = express.Router()
21
22 const reqVideoFileLive = createReqFiles([ 'thumbnailfile', 'previewfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT)
23
24 liveRouter.post('/live',
25 authenticate,
26 reqVideoFileLive,
27 asyncMiddleware(videoLiveAddValidator),
28 asyncRetryTransactionMiddleware(addLiveVideo)
29 )
30
31 liveRouter.get('/live/:videoId',
32 optionalAuthenticate,
33 asyncMiddleware(videoLiveGetValidator),
34 getLiveVideo
35 )
36
37 liveRouter.put('/live/:videoId',
38 authenticate,
39 asyncMiddleware(videoLiveGetValidator),
40 videoLiveUpdateValidator,
41 asyncRetryTransactionMiddleware(updateLiveVideo)
42 )
43
44 // ---------------------------------------------------------------------------
45
46 export {
47 liveRouter
48 }
49
50 // ---------------------------------------------------------------------------
51
52 function getLiveVideo (req: express.Request, res: express.Response) {
53 const videoLive = res.locals.videoLive
54
55 return res.json(videoLive.toFormattedJSON(canSeePrivateLiveInformation(res)))
56 }
57
58 function canSeePrivateLiveInformation (res: express.Response) {
59 const user = res.locals.oauth?.token.User
60 if (!user) return false
61
62 if (user.hasRight(UserRight.GET_ANY_LIVE)) return true
63
64 const video = res.locals.videoAll
65 return video.VideoChannel.Account.userId === user.id
66 }
67
68 async function updateLiveVideo (req: express.Request, res: express.Response) {
69 const body: LiveVideoUpdate = req.body
70
71 const video = res.locals.videoAll
72 const videoLive = res.locals.videoLive
73
74 if (exists(body.saveReplay)) videoLive.saveReplay = body.saveReplay
75 if (exists(body.permanentLive)) videoLive.permanentLive = body.permanentLive
76 if (exists(body.latencyMode)) videoLive.latencyMode = body.latencyMode
77
78 video.VideoLive = await videoLive.save()
79
80 await federateVideoIfNeeded(video, false)
81
82 return res.status(HttpStatusCode.NO_CONTENT_204).end()
83 }
84
85 async function addLiveVideo (req: express.Request, res: express.Response) {
86 const videoInfo: LiveVideoCreate = req.body
87
88 // Prepare data so we don't block the transaction
89 let videoData = buildLocalVideoFromReq(videoInfo, res.locals.videoChannel.id)
90 videoData = await Hooks.wrapObject(videoData, 'filter:api.video.live.video-attribute.result')
91
92 videoData.isLive = true
93 videoData.state = VideoState.WAITING_FOR_LIVE
94 videoData.duration = 0
95
96 const video = new VideoModel(videoData) as MVideoDetails
97 video.url = getLocalVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
98
99 const videoLive = new VideoLiveModel()
100 videoLive.saveReplay = videoInfo.saveReplay || false
101 videoLive.permanentLive = videoInfo.permanentLive || false
102 videoLive.latencyMode = videoInfo.latencyMode || LiveVideoLatencyMode.DEFAULT
103 videoLive.streamKey = buildUUID()
104
105 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
106 video,
107 files: req.files,
108 fallback: type => {
109 return updateVideoMiniatureFromExisting({
110 inputPath: ASSETS_PATH.DEFAULT_LIVE_BACKGROUND,
111 video,
112 type,
113 automaticallyGenerated: true,
114 keepOriginal: true
115 })
116 }
117 })
118
119 const { videoCreated } = await sequelizeTypescript.transaction(async t => {
120 const sequelizeOptions = { transaction: t }
121
122 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
123
124 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
125 if (previewModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
126
127 // Do not forget to add video channel information to the created video
128 videoCreated.VideoChannel = res.locals.videoChannel
129
130 videoLive.videoId = videoCreated.id
131 videoCreated.VideoLive = await videoLive.save(sequelizeOptions)
132
133 await setVideoTags({ video, tags: videoInfo.tags, transaction: t })
134
135 await federateVideoIfNeeded(videoCreated, true, t)
136
137 logger.info('Video live %s with uuid %s created.', videoInfo.name, videoCreated.uuid)
138
139 return { videoCreated }
140 })
141
142 Hooks.runAction('action:api.live-video.created', { video: videoCreated, req, res })
143
144 return res.json({
145 video: {
146 id: videoCreated.id,
147 shortUUID: uuidToShort(videoCreated.uuid),
148 uuid: videoCreated.uuid
149 }
150 })
151 }