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'
24 type VideoImportYoutubeDLPayload = {
29 downloadThumbnail: boolean
30 downloadPreview: boolean
33 type VideoImportTorrentPayload = {
34 type: 'magnet-uri' | 'torrent-file'
38 export type VideoImportPayload = VideoImportYoutubeDLPayload | VideoImportTorrentPayload
40 async function processVideoImport (job: Bull.Job) {
41 const payload = job.data as VideoImportPayload
43 if (payload.type === 'youtube-dl') return processYoutubeDLImport(job, payload)
44 if (payload.type === 'magnet-uri' || payload.type === 'torrent-file') return processTorrentImport(job, payload)
47 // ---------------------------------------------------------------------------
53 // ---------------------------------------------------------------------------
55 async function processTorrentImport (job: Bull.Job, payload: VideoImportTorrentPayload) {
56 logger.info('Processing torrent video import in job %d.', job.id)
58 const videoImport = await getVideoImportOrDie(payload.videoImportId)
61 videoImportId: payload.videoImportId,
63 downloadThumbnail: false,
64 downloadPreview: false,
66 generateThumbnail: true,
70 torrentName: videoImport.torrentName ? getSecureTorrentName(videoImport.torrentName) : undefined,
71 magnetUri: videoImport.magnetUri
73 return processFile(() => downloadWebTorrentVideo(target, VIDEO_IMPORT_TIMEOUT), videoImport, options)
76 async function processYoutubeDLImport (job: Bull.Job, payload: VideoImportYoutubeDLPayload) {
77 logger.info('Processing youtubeDL video import in job %d.', job.id)
79 const videoImport = await getVideoImportOrDie(payload.videoImportId)
81 videoImportId: videoImport.id,
83 downloadThumbnail: payload.downloadThumbnail,
84 downloadPreview: payload.downloadPreview,
85 thumbnailUrl: payload.thumbnailUrl,
87 generateThumbnail: false,
88 generatePreview: false
91 return processFile(() => downloadYoutubeDLVideo(videoImport.targetUrl, VIDEO_IMPORT_TIMEOUT), videoImport, options)
94 async function getVideoImportOrDie (videoImportId: number) {
95 const videoImport = await VideoImportModel.loadAndPopulateVideo(videoImportId)
96 if (!videoImport || !videoImport.Video) {
97 throw new Error('Cannot import video %s: the video import or video linked to this import does not exist anymore.')
103 type ProcessFileOptions = {
104 videoImportId: number
106 downloadThumbnail: boolean
107 downloadPreview: boolean
108 thumbnailUrl?: string
110 generateThumbnail: boolean
111 generatePreview: boolean
113 async function processFile (downloader: () => Promise<string>, videoImport: VideoImportModel, options: ProcessFileOptions) {
114 let tempVideoPath: string
115 let videoDestFile: string
116 let videoFile: VideoFileModel
119 // Download video from youtubeDL
120 tempVideoPath = await downloader()
122 // Get information about this video
123 const stats = await stat(tempVideoPath)
124 const isAble = await videoImport.User.isAbleToUploadVideo({ size: stats.size })
125 if (isAble === false) {
126 throw new Error('The user video quota is exceeded with this video to import.')
129 const { videoFileResolution } = await getVideoFileResolution(tempVideoPath)
130 const fps = await getVideoFileFPS(tempVideoPath)
131 const duration = await getDurationFromVideoFile(tempVideoPath)
133 // Create video file object in database
134 const videoFileData = {
135 extname: extname(tempVideoPath),
136 resolution: videoFileResolution,
139 videoId: videoImport.videoId
141 videoFile = new VideoFileModel(videoFileData)
142 // To clean files if the import fails
143 videoImport.Video.VideoFiles = [ videoFile ]
146 videoDestFile = join(CONFIG.STORAGE.VIDEOS_DIR, videoImport.Video.getVideoFilename(videoFile))
147 await move(tempVideoPath, videoDestFile)
148 tempVideoPath = null // This path is not used anymore
151 let thumbnailModel: ThumbnailModel
152 if (options.downloadThumbnail && options.thumbnailUrl) {
153 thumbnailModel = await createVideoMiniatureFromUrl(options.thumbnailUrl, videoImport.Video, ThumbnailType.MINIATURE)
154 } else if (options.generateThumbnail || options.downloadThumbnail) {
155 thumbnailModel = await generateVideoMiniature(videoImport.Video, videoFile, ThumbnailType.MINIATURE)
159 let previewModel: ThumbnailModel
160 if (options.downloadPreview && options.thumbnailUrl) {
161 previewModel = await createVideoMiniatureFromUrl(options.thumbnailUrl, videoImport.Video, ThumbnailType.PREVIEW)
162 } else if (options.generatePreview || options.downloadPreview) {
163 previewModel = await generateVideoMiniature(videoImport.Video, videoFile, ThumbnailType.PREVIEW)
167 await videoImport.Video.createTorrentAndSetInfoHash(videoFile)
169 const videoImportUpdated: VideoImportModel = await sequelizeTypescript.transaction(async t => {
171 const video = await VideoModel.load(videoImport.videoId, t)
172 if (!video) throw new Error('Video linked to import ' + videoImport.videoId + ' does not exist anymore.')
173 videoImport.Video = video
175 const videoFileCreated = await videoFile.save({ transaction: t })
176 video.VideoFiles = [ videoFileCreated ]
178 // Update video DB object
179 video.duration = duration
180 video.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED
181 await video.save({ transaction: t })
183 if (thumbnailModel) await video.addAndSaveThumbnail(thumbnailModel, t)
184 if (previewModel) await video.addAndSaveThumbnail(previewModel, t)
186 // Now we can federate the video (reload from database, we need more attributes)
187 const videoForFederation = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.uuid, t)
188 await federateVideoIfNeeded(videoForFederation, true, t)
190 // Update video import object
191 videoImport.state = VideoImportState.SUCCESS
192 const videoImportUpdated = await videoImport.save({ transaction: t })
194 logger.info('Video %s imported.', video.uuid)
196 videoImportUpdated.Video = videoForFederation
197 return videoImportUpdated
200 Notifier.Instance.notifyOnFinishedVideoImport(videoImportUpdated, true)
202 if (videoImportUpdated.Video.isBlacklisted()) {
203 Notifier.Instance.notifyOnVideoAutoBlacklist(videoImportUpdated.Video)
205 Notifier.Instance.notifyOnNewVideoIfNeeded(videoImportUpdated.Video)
208 // Create transcoding jobs?
209 if (videoImportUpdated.Video.state === VideoState.TO_TRANSCODE) {
210 // Put uuid because we don't have id auto incremented for now
212 type: 'optimize' as 'optimize',
213 videoUUID: videoImportUpdated.Video.uuid,
217 await JobQueue.Instance.createJob({ type: 'video-transcoding', payload: dataInput })
222 if (tempVideoPath) await remove(tempVideoPath)
223 } catch (errUnlink) {
224 logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink })
227 videoImport.error = err.message
228 videoImport.state = VideoImportState.FAILED
229 await videoImport.save()
231 Notifier.Instance.notifyOnFinishedVideoImport(videoImport, false)