video-import.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. import * as Bull from 'bull'
  2. import { logger } from '../../../helpers/logger'
  3. import { downloadYoutubeDLVideo } from '../../../helpers/youtube-dl'
  4. import { VideoImportModel } from '../../../models/video/video-import'
  5. import { VideoImportState } from '../../../../shared/models/videos'
  6. import { getDurationFromVideoFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffmpeg-utils'
  7. import { extname } from 'path'
  8. import { VideoFileModel } from '../../../models/video/video-file'
  9. import { VIDEO_IMPORT_TIMEOUT } from '../../../initializers/constants'
  10. import { VideoState } from '../../../../shared'
  11. import { JobQueue } from '../index'
  12. import { federateVideoIfNeeded } from '../../activitypub'
  13. import { VideoModel } from '../../../models/video/video'
  14. import { createTorrentAndSetInfoHash, downloadWebTorrentVideo } from '../../../helpers/webtorrent'
  15. import { getSecureTorrentName } from '../../../helpers/utils'
  16. import { move, remove, stat } from 'fs-extra'
  17. import { Notifier } from '../../notifier'
  18. import { CONFIG } from '../../../initializers/config'
  19. import { sequelizeTypescript } from '../../../initializers/database'
  20. import { createVideoMiniatureFromUrl, generateVideoMiniature } from '../../thumbnail'
  21. import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
  22. import { MThumbnail } from '../../../typings/models/video/thumbnail'
  23. import { MVideoImportDefault, MVideoImportDefaultFiles, MVideoImportVideo } from '@server/typings/models/video/video-import'
  24. import { getVideoFilePath } from '@server/lib/video-paths'
  25. type VideoImportYoutubeDLPayload = {
  26. type: 'youtube-dl'
  27. videoImportId: number
  28. thumbnailUrl: string
  29. downloadThumbnail: boolean
  30. downloadPreview: boolean
  31. }
  32. type VideoImportTorrentPayload = {
  33. type: 'magnet-uri' | 'torrent-file'
  34. videoImportId: number
  35. }
  36. export type VideoImportPayload = VideoImportYoutubeDLPayload | VideoImportTorrentPayload
  37. async function processVideoImport (job: Bull.Job) {
  38. const payload = job.data as VideoImportPayload
  39. if (payload.type === 'youtube-dl') return processYoutubeDLImport(job, payload)
  40. if (payload.type === 'magnet-uri' || payload.type === 'torrent-file') return processTorrentImport(job, payload)
  41. }
  42. // ---------------------------------------------------------------------------
  43. export {
  44. processVideoImport
  45. }
  46. // ---------------------------------------------------------------------------
  47. async function processTorrentImport (job: Bull.Job, payload: VideoImportTorrentPayload) {
  48. logger.info('Processing torrent video import in job %d.', job.id)
  49. const videoImport = await getVideoImportOrDie(payload.videoImportId)
  50. const options = {
  51. videoImportId: payload.videoImportId,
  52. downloadThumbnail: false,
  53. downloadPreview: false,
  54. generateThumbnail: true,
  55. generatePreview: true
  56. }
  57. const target = {
  58. torrentName: videoImport.torrentName ? getSecureTorrentName(videoImport.torrentName) : undefined,
  59. magnetUri: videoImport.magnetUri
  60. }
  61. return processFile(() => downloadWebTorrentVideo(target, VIDEO_IMPORT_TIMEOUT), videoImport, options)
  62. }
  63. async function processYoutubeDLImport (job: Bull.Job, payload: VideoImportYoutubeDLPayload) {
  64. logger.info('Processing youtubeDL video import in job %d.', job.id)
  65. const videoImport = await getVideoImportOrDie(payload.videoImportId)
  66. const options = {
  67. videoImportId: videoImport.id,
  68. downloadThumbnail: payload.downloadThumbnail,
  69. downloadPreview: payload.downloadPreview,
  70. thumbnailUrl: payload.thumbnailUrl,
  71. generateThumbnail: false,
  72. generatePreview: false
  73. }
  74. return processFile(() => downloadYoutubeDLVideo(videoImport.targetUrl, VIDEO_IMPORT_TIMEOUT), videoImport, options)
  75. }
  76. async function getVideoImportOrDie (videoImportId: number) {
  77. const videoImport = await VideoImportModel.loadAndPopulateVideo(videoImportId)
  78. if (!videoImport || !videoImport.Video) {
  79. throw new Error('Cannot import video %s: the video import or video linked to this import does not exist anymore.')
  80. }
  81. return videoImport
  82. }
  83. type ProcessFileOptions = {
  84. videoImportId: number
  85. downloadThumbnail: boolean
  86. downloadPreview: boolean
  87. thumbnailUrl?: string
  88. generateThumbnail: boolean
  89. generatePreview: boolean
  90. }
  91. async function processFile (downloader: () => Promise<string>, videoImport: MVideoImportDefault, options: ProcessFileOptions) {
  92. let tempVideoPath: string
  93. let videoDestFile: string
  94. let videoFile: VideoFileModel
  95. try {
  96. // Download video from youtubeDL
  97. tempVideoPath = await downloader()
  98. // Get information about this video
  99. const stats = await stat(tempVideoPath)
  100. const isAble = await videoImport.User.isAbleToUploadVideo({ size: stats.size })
  101. if (isAble === false) {
  102. throw new Error('The user video quota is exceeded with this video to import.')
  103. }
  104. const { videoFileResolution } = await getVideoFileResolution(tempVideoPath)
  105. const fps = await getVideoFileFPS(tempVideoPath)
  106. const duration = await getDurationFromVideoFile(tempVideoPath)
  107. // Create video file object in database
  108. const videoFileData = {
  109. extname: extname(tempVideoPath),
  110. resolution: videoFileResolution,
  111. size: stats.size,
  112. fps,
  113. videoId: videoImport.videoId
  114. }
  115. videoFile = new VideoFileModel(videoFileData)
  116. const videoWithFiles = Object.assign(videoImport.Video, { VideoFiles: [ videoFile ], VideoStreamingPlaylists: [] })
  117. // To clean files if the import fails
  118. const videoImportWithFiles: MVideoImportDefaultFiles = Object.assign(videoImport, { Video: videoWithFiles })
  119. // Move file
  120. videoDestFile = getVideoFilePath(videoImportWithFiles.Video, videoFile)
  121. await move(tempVideoPath, videoDestFile)
  122. tempVideoPath = null // This path is not used anymore
  123. // Process thumbnail
  124. let thumbnailModel: MThumbnail
  125. if (options.downloadThumbnail && options.thumbnailUrl) {
  126. thumbnailModel = await createVideoMiniatureFromUrl(options.thumbnailUrl, videoImportWithFiles.Video, ThumbnailType.MINIATURE)
  127. } else if (options.generateThumbnail || options.downloadThumbnail) {
  128. thumbnailModel = await generateVideoMiniature(videoImportWithFiles.Video, videoFile, ThumbnailType.MINIATURE)
  129. }
  130. // Process preview
  131. let previewModel: MThumbnail
  132. if (options.downloadPreview && options.thumbnailUrl) {
  133. previewModel = await createVideoMiniatureFromUrl(options.thumbnailUrl, videoImportWithFiles.Video, ThumbnailType.PREVIEW)
  134. } else if (options.generatePreview || options.downloadPreview) {
  135. previewModel = await generateVideoMiniature(videoImportWithFiles.Video, videoFile, ThumbnailType.PREVIEW)
  136. }
  137. // Create torrent
  138. await createTorrentAndSetInfoHash(videoImportWithFiles.Video, videoFile)
  139. const { videoImportUpdated, video } = await sequelizeTypescript.transaction(async t => {
  140. const videoImportToUpdate = videoImportWithFiles as MVideoImportVideo
  141. // Refresh video
  142. const video = await VideoModel.load(videoImportToUpdate.videoId, t)
  143. if (!video) throw new Error('Video linked to import ' + videoImportToUpdate.videoId + ' does not exist anymore.')
  144. const videoFileCreated = await videoFile.save({ transaction: t })
  145. videoImportToUpdate.Video = Object.assign(video, { VideoFiles: [ videoFileCreated ] })
  146. // Update video DB object
  147. video.duration = duration
  148. video.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED
  149. await video.save({ transaction: t })
  150. if (thumbnailModel) await video.addAndSaveThumbnail(thumbnailModel, t)
  151. if (previewModel) await video.addAndSaveThumbnail(previewModel, t)
  152. // Now we can federate the video (reload from database, we need more attributes)
  153. const videoForFederation = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.uuid, t)
  154. await federateVideoIfNeeded(videoForFederation, true, t)
  155. // Update video import object
  156. videoImportToUpdate.state = VideoImportState.SUCCESS
  157. const videoImportUpdated = await videoImportToUpdate.save({ transaction: t }) as MVideoImportVideo
  158. videoImportUpdated.Video = video
  159. logger.info('Video %s imported.', video.uuid)
  160. return { videoImportUpdated, video: videoForFederation }
  161. })
  162. Notifier.Instance.notifyOnFinishedVideoImport(videoImportUpdated, true)
  163. if (video.isBlacklisted()) {
  164. const videoBlacklist = Object.assign(video.VideoBlacklist, { Video: video })
  165. Notifier.Instance.notifyOnVideoAutoBlacklist(videoBlacklist)
  166. } else {
  167. Notifier.Instance.notifyOnNewVideoIfNeeded(video)
  168. }
  169. // Create transcoding jobs?
  170. if (video.state === VideoState.TO_TRANSCODE) {
  171. // Put uuid because we don't have id auto incremented for now
  172. const dataInput = {
  173. type: 'optimize' as 'optimize',
  174. videoUUID: videoImportUpdated.Video.uuid,
  175. isNewVideo: true
  176. }
  177. await JobQueue.Instance.createJob({ type: 'video-transcoding', payload: dataInput })
  178. }
  179. } catch (err) {
  180. try {
  181. if (tempVideoPath) await remove(tempVideoPath)
  182. } catch (errUnlink) {
  183. logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink })
  184. }
  185. videoImport.error = err.message
  186. videoImport.state = VideoImportState.FAILED
  187. await videoImport.save()
  188. Notifier.Instance.notifyOnFinishedVideoImport(videoImport, false)
  189. throw err
  190. }
  191. }