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 { CONFIG, sequelizeTypescript, VIDEO_IMPORT_TIMEOUT } from '../../../initializers'
10 import { doRequestAndSaveToFile } from '../../../helpers/requests'
11 import { VideoState } from '../../../../shared'
12 import { JobQueue } from '../index'
13 import { federateVideoIfNeeded } from '../../activitypub'
14 import { VideoModel } from '../../../models/video/video'
15 import { downloadWebTorrentVideo } from '../../../helpers/webtorrent'
16 import { getSecureTorrentName } from '../../../helpers/utils'
17 import { remove, rename, stat } from 'fs-extra'
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, VIDEO_IMPORT_TIMEOUT), 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, VIDEO_IMPORT_TIMEOUT), 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 stats = await stat(tempVideoPath)
118 const isAble = await videoImport.User.isAbleToUploadVideo({ size: stats.size })
119 if (isAble === false) {
120 throw new Error('The user video quota is exceeded with this video to import.')
123 const { videoFileResolution } = await getVideoFileResolution(tempVideoPath)
124 const fps = await getVideoFileFPS(tempVideoPath)
125 const duration = await getDurationFromVideoFile(tempVideoPath)
127 // Create video file object in database
128 const videoFileData = {
129 extname: extname(tempVideoPath),
130 resolution: videoFileResolution,
133 videoId: videoImport.videoId
135 videoFile = new VideoFileModel(videoFileData)
136 // Import if the import fails, to clean files
137 videoImport.Video.VideoFiles = [ videoFile ]
140 videoDestFile = join(CONFIG.STORAGE.VIDEOS_DIR, videoImport.Video.getVideoFilename(videoFile))
141 await rename(tempVideoPath, videoDestFile)
142 tempVideoPath = null // This path is not used anymore
145 if (options.downloadThumbnail) {
146 if (options.thumbnailUrl) {
147 const destThumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, videoImport.Video.getThumbnailName())
148 await doRequestAndSaveToFile({ method: 'GET', uri: options.thumbnailUrl }, destThumbnailPath)
150 await videoImport.Video.createThumbnail(videoFile)
152 } else if (options.generateThumbnail) {
153 await videoImport.Video.createThumbnail(videoFile)
157 if (options.downloadPreview) {
158 if (options.thumbnailUrl) {
159 const destPreviewPath = join(CONFIG.STORAGE.PREVIEWS_DIR, videoImport.Video.getPreviewName())
160 await doRequestAndSaveToFile({ method: 'GET', uri: options.thumbnailUrl }, destPreviewPath)
162 await videoImport.Video.createPreview(videoFile)
164 } else if (options.generatePreview) {
165 await videoImport.Video.createPreview(videoFile)
169 await videoImport.Video.createTorrentAndSetInfoHash(videoFile)
171 const videoImportUpdated: VideoImportModel = await sequelizeTypescript.transaction(async t => {
173 const video = await VideoModel.load(videoImport.videoId, t)
174 if (!video) throw new Error('Video linked to import ' + videoImport.videoId + ' does not exist anymore.')
175 videoImport.Video = video
177 const videoFileCreated = await videoFile.save({ transaction: t })
178 video.VideoFiles = [ videoFileCreated ]
180 // Update video DB object
181 video.duration = duration
182 video.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED
183 const videoUpdated = await video.save({ transaction: t })
185 // Now we can federate the video (reload from database, we need more attributes)
186 const videoForFederation = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.uuid, t)
187 await federateVideoIfNeeded(videoForFederation, true, t)
189 // Update video import object
190 videoImport.state = VideoImportState.SUCCESS
191 const videoImportUpdated = await videoImport.save({ transaction: t })
193 logger.info('Video %s imported.', video.uuid)
195 videoImportUpdated.Video = videoUpdated
196 return videoImportUpdated
199 // Create transcoding jobs?
200 if (videoImportUpdated.Video.state === VideoState.TO_TRANSCODE) {
201 // Put uuid because we don't have id auto incremented for now
203 videoUUID: videoImportUpdated.Video.uuid,
207 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
212 if (tempVideoPath) await remove(tempVideoPath)
213 } catch (errUnlink) {
214 logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink })
217 videoImport.error = err.message
218 videoImport.state = VideoImportState.FAILED
219 await videoImport.save()