video-import.ts 8.6 KB

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