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 { createVideoMiniatureFromUrl, generateVideoMiniature } from '../../thumbnail'
21 import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
22 import { MThumbnail } from '../../../typings/models/video/thumbnail'
23 import { MVideoImportDefault, MVideoImportDefaultFiles, MVideoImportVideo } from '@server/typings/models/video/video-import'
25 type VideoImportYoutubeDLPayload = {
30 downloadThumbnail: boolean
31 downloadPreview: boolean
34 type VideoImportTorrentPayload = {
35 type: 'magnet-uri' | 'torrent-file'
39 export type VideoImportPayload = VideoImportYoutubeDLPayload | VideoImportTorrentPayload
41 async function processVideoImport (job: Bull.Job) {
42 const payload = job.data as VideoImportPayload
44 if (payload.type === 'youtube-dl') return processYoutubeDLImport(job, payload)
45 if (payload.type === 'magnet-uri' || payload.type === 'torrent-file') return processTorrentImport(job, payload)
48 // ---------------------------------------------------------------------------
54 // ---------------------------------------------------------------------------
56 async function processTorrentImport (job: Bull.Job, payload: VideoImportTorrentPayload) {
57 logger.info('Processing torrent video import in job %d.', job.id)
59 const videoImport = await getVideoImportOrDie(payload.videoImportId)
62 videoImportId: payload.videoImportId,
64 downloadThumbnail: false,
65 downloadPreview: false,
67 generateThumbnail: true,
71 torrentName: videoImport.torrentName ? getSecureTorrentName(videoImport.torrentName) : undefined,
72 magnetUri: videoImport.magnetUri
74 return processFile(() => downloadWebTorrentVideo(target, VIDEO_IMPORT_TIMEOUT), videoImport, options)
77 async function processYoutubeDLImport (job: Bull.Job, payload: VideoImportYoutubeDLPayload) {
78 logger.info('Processing youtubeDL video import in job %d.', job.id)
80 const videoImport = await getVideoImportOrDie(payload.videoImportId)
82 videoImportId: videoImport.id,
84 downloadThumbnail: payload.downloadThumbnail,
85 downloadPreview: payload.downloadPreview,
86 thumbnailUrl: payload.thumbnailUrl,
88 generateThumbnail: false,
89 generatePreview: false
92 return processFile(() => downloadYoutubeDLVideo(videoImport.targetUrl, VIDEO_IMPORT_TIMEOUT), videoImport, options)
95 async function getVideoImportOrDie (videoImportId: number) {
96 const videoImport = await VideoImportModel.loadAndPopulateVideo(videoImportId)
97 if (!videoImport || !videoImport.Video) {
98 throw new Error('Cannot import video %s: the video import or video linked to this import does not exist anymore.')
104 type ProcessFileOptions = {
105 videoImportId: number
107 downloadThumbnail: boolean
108 downloadPreview: boolean
109 thumbnailUrl?: string
111 generateThumbnail: boolean
112 generatePreview: boolean
114 async function processFile (downloader: () => Promise<string>, videoImport: MVideoImportDefault, options: ProcessFileOptions) {
115 let tempVideoPath: string
116 let videoDestFile: string
117 let videoFile: VideoFileModel
120 // Download video from youtubeDL
121 tempVideoPath = await downloader()
123 // Get information about this video
124 const stats = await stat(tempVideoPath)
125 const isAble = await videoImport.User.isAbleToUploadVideo({ size: stats.size })
126 if (isAble === false) {
127 throw new Error('The user video quota is exceeded with this video to import.')
130 const { videoFileResolution } = await getVideoFileResolution(tempVideoPath)
131 const fps = await getVideoFileFPS(tempVideoPath)
132 const duration = await getDurationFromVideoFile(tempVideoPath)
134 // Create video file object in database
135 const videoFileData = {
136 extname: extname(tempVideoPath),
137 resolution: videoFileResolution,
140 videoId: videoImport.videoId
142 videoFile = new VideoFileModel(videoFileData)
144 const videoWithFiles = Object.assign(videoImport.Video, { VideoFiles: [ videoFile ] })
145 // To clean files if the import fails
146 const videoImportWithFiles: MVideoImportDefaultFiles = Object.assign(videoImport, { Video: videoWithFiles })
149 videoDestFile = join(CONFIG.STORAGE.VIDEOS_DIR, videoImportWithFiles.Video.getVideoFilename(videoFile))
150 await move(tempVideoPath, videoDestFile)
151 tempVideoPath = null // This path is not used anymore
154 let thumbnailModel: MThumbnail
155 if (options.downloadThumbnail && options.thumbnailUrl) {
156 thumbnailModel = await createVideoMiniatureFromUrl(options.thumbnailUrl, videoImportWithFiles.Video, ThumbnailType.MINIATURE)
157 } else if (options.generateThumbnail || options.downloadThumbnail) {
158 thumbnailModel = await generateVideoMiniature(videoImportWithFiles.Video, videoFile, ThumbnailType.MINIATURE)
162 let previewModel: MThumbnail
163 if (options.downloadPreview && options.thumbnailUrl) {
164 previewModel = await createVideoMiniatureFromUrl(options.thumbnailUrl, videoImportWithFiles.Video, ThumbnailType.PREVIEW)
165 } else if (options.generatePreview || options.downloadPreview) {
166 previewModel = await generateVideoMiniature(videoImportWithFiles.Video, videoFile, ThumbnailType.PREVIEW)
170 await videoImportWithFiles.Video.createTorrentAndSetInfoHash(videoFile)
172 const { videoImportUpdated, video } = await sequelizeTypescript.transaction(async t => {
173 const videoImportToUpdate = videoImportWithFiles as MVideoImportVideo
176 const video = await VideoModel.load(videoImportToUpdate.videoId, t)
177 if (!video) throw new Error('Video linked to import ' + videoImportToUpdate.videoId + ' does not exist anymore.')
179 const videoFileCreated = await videoFile.save({ transaction: t })
180 videoImportToUpdate.Video = Object.assign(video, { VideoFiles: [ videoFileCreated ] })
182 // Update video DB object
183 video.duration = duration
184 video.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED
185 await video.save({ transaction: t })
187 if (thumbnailModel) await video.addAndSaveThumbnail(thumbnailModel, t)
188 if (previewModel) await video.addAndSaveThumbnail(previewModel, t)
190 // Now we can federate the video (reload from database, we need more attributes)
191 const videoForFederation = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.uuid, t)
192 await federateVideoIfNeeded(videoForFederation, true, t)
194 // Update video import object
195 videoImportToUpdate.state = VideoImportState.SUCCESS
196 const videoImportUpdated = await videoImportToUpdate.save({ transaction: t }) as MVideoImportVideo
197 videoImportUpdated.Video = video
199 logger.info('Video %s imported.', video.uuid)
201 return { videoImportUpdated, video: videoForFederation }
204 Notifier.Instance.notifyOnFinishedVideoImport(videoImportUpdated, true)
206 if (video.isBlacklisted()) {
207 Notifier.Instance.notifyOnVideoAutoBlacklist(video)
209 Notifier.Instance.notifyOnNewVideoIfNeeded(video)
212 // Create transcoding jobs?
213 if (video.state === VideoState.TO_TRANSCODE) {
214 // Put uuid because we don't have id auto incremented for now
216 type: 'optimize' as 'optimize',
217 videoUUID: videoImportUpdated.Video.uuid,
221 await JobQueue.Instance.createJob({ type: 'video-transcoding', payload: dataInput })
226 if (tempVideoPath) await remove(tempVideoPath)
227 } catch (errUnlink) {
228 logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink })
231 videoImport.error = err.message
232 videoImport.state = VideoImportState.FAILED
233 await videoImport.save()
235 Notifier.Instance.notifyOnFinishedVideoImport(videoImport, false)