live.ts 6.4 KB

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