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 { renamePromise, statPromise, unlinkPromise } from '../../../helpers/core-utils'
10 import { CONFIG, sequelizeTypescript } from '../../../initializers'
11 import { doRequestAndSaveToFile } from '../../../helpers/requests'
12 import { VideoState } from '../../../../shared'
13 import { JobQueue } from '../index'
14 import { federateVideoIfNeeded } from '../../activitypub'
15 import { VideoModel } from '../../../models/video/video'
16 import { downloadWebTorrentVideo } from '../../../helpers/webtorrent'
18 type VideoImportYoutubeDLPayload = {
23 downloadThumbnail: boolean
24 downloadPreview: boolean
27 type VideoImportTorrentPayload = {
32 export type VideoImportPayload = VideoImportYoutubeDLPayload | VideoImportTorrentPayload
34 async function processVideoImport (job: Bull.Job) {
35 const payload = job.data as VideoImportPayload
37 if (payload.type === 'youtube-dl') return processYoutubeDLImport(job, payload)
38 if (payload.type === 'magnet-uri') return processTorrentImport(job, payload)
41 // ---------------------------------------------------------------------------
47 // ---------------------------------------------------------------------------
49 async function processTorrentImport (job: Bull.Job, payload: VideoImportTorrentPayload) {
50 logger.info('Processing torrent video import in job %d.', job.id)
52 const videoImport = await getVideoImportOrDie(payload.videoImportId)
54 videoImportId: payload.videoImportId,
56 downloadThumbnail: false,
57 downloadPreview: false,
59 generateThumbnail: true,
62 return processFile(() => downloadWebTorrentVideo(videoImport.magnetUri), videoImport, options)
65 async function processYoutubeDLImport (job: Bull.Job, payload: VideoImportYoutubeDLPayload) {
66 logger.info('Processing youtubeDL video import in job %d.', job.id)
68 const videoImport = await getVideoImportOrDie(payload.videoImportId)
70 videoImportId: videoImport.id,
72 downloadThumbnail: payload.downloadThumbnail,
73 downloadPreview: payload.downloadPreview,
74 thumbnailUrl: payload.thumbnailUrl,
76 generateThumbnail: false,
77 generatePreview: false
80 return processFile(() => downloadYoutubeDLVideo(videoImport.targetUrl), videoImport, options)
83 async function getVideoImportOrDie (videoImportId: number) {
84 const videoImport = await VideoImportModel.loadAndPopulateVideo(videoImportId)
85 if (!videoImport || !videoImport.Video) {
86 throw new Error('Cannot import video %s: the video import or video linked to this import does not exist anymore.')
92 type ProcessFileOptions = {
95 downloadThumbnail: boolean
96 downloadPreview: boolean
99 generateThumbnail: boolean
100 generatePreview: boolean
102 async function processFile (downloader: () => Promise<string>, videoImport: VideoImportModel, options: ProcessFileOptions) {
103 let tempVideoPath: string
104 let videoDestFile: string
105 let videoFile: VideoFileModel
107 // Download video from youtubeDL
108 tempVideoPath = await downloader()
110 // Get information about this video
111 const { videoFileResolution } = await getVideoFileResolution(tempVideoPath)
112 const fps = await getVideoFileFPS(tempVideoPath)
113 const stats = await statPromise(tempVideoPath)
114 const duration = await getDurationFromVideoFile(tempVideoPath)
116 // Create video file object in database
117 const videoFileData = {
118 extname: extname(tempVideoPath),
119 resolution: videoFileResolution,
122 videoId: videoImport.videoId
124 videoFile = new VideoFileModel(videoFileData)
125 // Import if the import fails, to clean files
126 videoImport.Video.VideoFiles = [ videoFile ]
129 videoDestFile = join(CONFIG.STORAGE.VIDEOS_DIR, videoImport.Video.getVideoFilename(videoFile))
130 await renamePromise(tempVideoPath, videoDestFile)
131 tempVideoPath = null // This path is not used anymore
134 if (options.downloadThumbnail) {
135 if (options.thumbnailUrl) {
136 const destThumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, videoImport.Video.getThumbnailName())
137 await doRequestAndSaveToFile({ method: 'GET', uri: options.thumbnailUrl }, destThumbnailPath)
139 await videoImport.Video.createThumbnail(videoFile)
141 } else if (options.generateThumbnail) {
142 await videoImport.Video.createThumbnail(videoFile)
146 if (options.downloadPreview) {
147 if (options.thumbnailUrl) {
148 const destPreviewPath = join(CONFIG.STORAGE.PREVIEWS_DIR, videoImport.Video.getPreviewName())
149 await doRequestAndSaveToFile({ method: 'GET', uri: options.thumbnailUrl }, destPreviewPath)
151 await videoImport.Video.createPreview(videoFile)
153 } else if (options.generatePreview) {
154 await videoImport.Video.createPreview(videoFile)
158 await videoImport.Video.createTorrentAndSetInfoHash(videoFile)
160 const videoImportUpdated: VideoImportModel = await sequelizeTypescript.transaction(async t => {
162 const video = await VideoModel.load(videoImport.videoId, t)
163 if (!video) throw new Error('Video linked to import ' + videoImport.videoId + ' does not exist anymore.')
164 videoImport.Video = video
166 const videoFileCreated = await videoFile.save({ transaction: t })
167 video.VideoFiles = [ videoFileCreated ]
169 // Update video DB object
170 video.duration = duration
171 video.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED
172 const videoUpdated = await video.save({ transaction: t })
174 // Now we can federate the video (reload from database, we need more attributes)
175 const videoForFederation = await VideoModel.loadByUUIDAndPopulateAccountAndServerAndTags(video.uuid, t)
176 await federateVideoIfNeeded(videoForFederation, true, t)
178 // Update video import object
179 videoImport.state = VideoImportState.SUCCESS
180 const videoImportUpdated = await videoImport.save({ transaction: t })
182 logger.info('Video %s imported.', videoImport.targetUrl)
184 videoImportUpdated.Video = videoUpdated
185 return videoImportUpdated
188 // Create transcoding jobs?
189 if (videoImportUpdated.Video.state === VideoState.TO_TRANSCODE) {
190 // Put uuid because we don't have id auto incremented for now
192 videoUUID: videoImportUpdated.Video.uuid,
196 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
201 if (tempVideoPath) await unlinkPromise(tempVideoPath)
202 } catch (errUnlink) {
203 logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink })
206 videoImport.error = err.message
207 videoImport.state = VideoImportState.FAILED
208 await videoImport.save()