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'
17 import { getSecureTorrentName } from '../../../helpers/utils'
19 type VideoImportYoutubeDLPayload = {
24 downloadThumbnail: boolean
25 downloadPreview: boolean
28 type VideoImportTorrentPayload = {
29 type: 'magnet-uri' | 'torrent-file'
33 export type VideoImportPayload = VideoImportYoutubeDLPayload | VideoImportTorrentPayload
35 async function processVideoImport (job: Bull.Job) {
36 const payload = job.data as VideoImportPayload
38 if (payload.type === 'youtube-dl') return processYoutubeDLImport(job, payload)
39 if (payload.type === 'magnet-uri' || payload.type === 'torrent-file') return processTorrentImport(job, payload)
42 // ---------------------------------------------------------------------------
48 // ---------------------------------------------------------------------------
50 async function processTorrentImport (job: Bull.Job, payload: VideoImportTorrentPayload) {
51 logger.info('Processing torrent video import in job %d.', job.id)
53 const videoImport = await getVideoImportOrDie(payload.videoImportId)
56 videoImportId: payload.videoImportId,
58 downloadThumbnail: false,
59 downloadPreview: false,
61 generateThumbnail: true,
65 torrentName: videoImport.torrentName ? getSecureTorrentName(videoImport.torrentName) : undefined,
66 magnetUri: videoImport.magnetUri
68 return processFile(() => downloadWebTorrentVideo(target), videoImport, options)
71 async function processYoutubeDLImport (job: Bull.Job, payload: VideoImportYoutubeDLPayload) {
72 logger.info('Processing youtubeDL video import in job %d.', job.id)
74 const videoImport = await getVideoImportOrDie(payload.videoImportId)
76 videoImportId: videoImport.id,
78 downloadThumbnail: payload.downloadThumbnail,
79 downloadPreview: payload.downloadPreview,
80 thumbnailUrl: payload.thumbnailUrl,
82 generateThumbnail: false,
83 generatePreview: false
86 return processFile(() => downloadYoutubeDLVideo(videoImport.targetUrl), videoImport, options)
89 async function getVideoImportOrDie (videoImportId: number) {
90 const videoImport = await VideoImportModel.loadAndPopulateVideo(videoImportId)
91 if (!videoImport || !videoImport.Video) {
92 throw new Error('Cannot import video %s: the video import or video linked to this import does not exist anymore.')
98 type ProcessFileOptions = {
101 downloadThumbnail: boolean
102 downloadPreview: boolean
103 thumbnailUrl?: string
105 generateThumbnail: boolean
106 generatePreview: boolean
108 async function processFile (downloader: () => Promise<string>, videoImport: VideoImportModel, options: ProcessFileOptions) {
109 let tempVideoPath: string
110 let videoDestFile: string
111 let videoFile: VideoFileModel
113 // Download video from youtubeDL
114 tempVideoPath = await downloader()
116 // Get information about this video
117 const { videoFileResolution } = await getVideoFileResolution(tempVideoPath)
118 const fps = await getVideoFileFPS(tempVideoPath)
119 const stats = await statPromise(tempVideoPath)
120 const duration = await getDurationFromVideoFile(tempVideoPath)
122 // Create video file object in database
123 const videoFileData = {
124 extname: extname(tempVideoPath),
125 resolution: videoFileResolution,
128 videoId: videoImport.videoId
130 videoFile = new VideoFileModel(videoFileData)
131 // Import if the import fails, to clean files
132 videoImport.Video.VideoFiles = [ videoFile ]
135 videoDestFile = join(CONFIG.STORAGE.VIDEOS_DIR, videoImport.Video.getVideoFilename(videoFile))
136 await renamePromise(tempVideoPath, videoDestFile)
137 tempVideoPath = null // This path is not used anymore
140 if (options.downloadThumbnail) {
141 if (options.thumbnailUrl) {
142 const destThumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, videoImport.Video.getThumbnailName())
143 await doRequestAndSaveToFile({ method: 'GET', uri: options.thumbnailUrl }, destThumbnailPath)
145 await videoImport.Video.createThumbnail(videoFile)
147 } else if (options.generateThumbnail) {
148 await videoImport.Video.createThumbnail(videoFile)
152 if (options.downloadPreview) {
153 if (options.thumbnailUrl) {
154 const destPreviewPath = join(CONFIG.STORAGE.PREVIEWS_DIR, videoImport.Video.getPreviewName())
155 await doRequestAndSaveToFile({ method: 'GET', uri: options.thumbnailUrl }, destPreviewPath)
157 await videoImport.Video.createPreview(videoFile)
159 } else if (options.generatePreview) {
160 await videoImport.Video.createPreview(videoFile)
164 await videoImport.Video.createTorrentAndSetInfoHash(videoFile)
166 const videoImportUpdated: VideoImportModel = await sequelizeTypescript.transaction(async t => {
168 const video = await VideoModel.load(videoImport.videoId, t)
169 if (!video) throw new Error('Video linked to import ' + videoImport.videoId + ' does not exist anymore.')
170 videoImport.Video = video
172 const videoFileCreated = await videoFile.save({ transaction: t })
173 video.VideoFiles = [ videoFileCreated ]
175 // Update video DB object
176 video.duration = duration
177 video.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED
178 const videoUpdated = await video.save({ transaction: t })
180 // Now we can federate the video (reload from database, we need more attributes)
181 const videoForFederation = await VideoModel.loadByUUIDAndPopulateAccountAndServerAndTags(video.uuid, t)
182 await federateVideoIfNeeded(videoForFederation, true, t)
184 // Update video import object
185 videoImport.state = VideoImportState.SUCCESS
186 const videoImportUpdated = await videoImport.save({ transaction: t })
188 logger.info('Video %s imported.', videoImport.targetUrl)
190 videoImportUpdated.Video = videoUpdated
191 return videoImportUpdated
194 // Create transcoding jobs?
195 if (videoImportUpdated.Video.state === VideoState.TO_TRANSCODE) {
196 // Put uuid because we don't have id auto incremented for now
198 videoUUID: videoImportUpdated.Video.uuid,
202 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
207 if (tempVideoPath) await unlinkPromise(tempVideoPath)
208 } catch (errUnlink) {
209 logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink })
212 videoImport.error = err.message
213 videoImport.state = VideoImportState.FAILED
214 await videoImport.save()