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 } from 'path'
8 import { VideoFileModel } from '../../../models/video/video-file'
9 import { VIDEO_IMPORT_TIMEOUT } from '../../../initializers/constants'
10 import { VideoImportPayload, VideoImportTorrentPayload, VideoImportYoutubeDLPayload, VideoState } from '../../../../shared'
11 import { federateVideoIfNeeded } from '../../activitypub/videos'
12 import { VideoModel } from '../../../models/video/video'
13 import { createTorrentAndSetInfoHash, downloadWebTorrentVideo } from '../../../helpers/webtorrent'
14 import { getSecureTorrentName } from '../../../helpers/utils'
15 import { move, remove, stat } from 'fs-extra'
16 import { Notifier } from '../../notifier'
17 import { CONFIG } from '../../../initializers/config'
18 import { sequelizeTypescript } from '../../../initializers/database'
19 import { generateVideoMiniature } from '../../thumbnail'
20 import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
21 import { MThumbnail } from '../../../typings/models/video/thumbnail'
22 import { MVideoImportDefault, MVideoImportDefaultFiles, MVideoImportVideo } from '@server/typings/models/video/video-import'
23 import { getVideoFilePath } from '@server/lib/video-paths'
24 import { addOptimizeOrMergeAudioJob } from '@server/helpers/video'
26 async function processVideoImport (job: Bull.Job) {
27 const payload = job.data as VideoImportPayload
29 if (payload.type === 'youtube-dl') return processYoutubeDLImport(job, payload)
30 if (payload.type === 'magnet-uri' || payload.type === 'torrent-file') return processTorrentImport(job, payload)
33 // ---------------------------------------------------------------------------
39 // ---------------------------------------------------------------------------
41 async function processTorrentImport (job: Bull.Job, payload: VideoImportTorrentPayload) {
42 logger.info('Processing torrent video import in job %d.', job.id)
44 const videoImport = await getVideoImportOrDie(payload.videoImportId)
47 videoImportId: payload.videoImportId,
49 generateThumbnail: true,
53 torrentName: videoImport.torrentName ? getSecureTorrentName(videoImport.torrentName) : undefined,
54 magnetUri: videoImport.magnetUri
56 return processFile(() => downloadWebTorrentVideo(target, VIDEO_IMPORT_TIMEOUT), videoImport, options)
59 async function processYoutubeDLImport (job: Bull.Job, payload: VideoImportYoutubeDLPayload) {
60 logger.info('Processing youtubeDL video import in job %d.', job.id)
62 const videoImport = await getVideoImportOrDie(payload.videoImportId)
64 videoImportId: videoImport.id,
66 generateThumbnail: payload.generateThumbnail,
67 generatePreview: payload.generatePreview
70 return processFile(() => downloadYoutubeDLVideo(videoImport.targetUrl, payload.fileExt, VIDEO_IMPORT_TIMEOUT), videoImport, options)
73 async function getVideoImportOrDie (videoImportId: number) {
74 const videoImport = await VideoImportModel.loadAndPopulateVideo(videoImportId)
75 if (!videoImport || !videoImport.Video) {
76 throw new Error('Cannot import video %s: the video import or video linked to this import does not exist anymore.')
82 type ProcessFileOptions = {
85 generateThumbnail: boolean
86 generatePreview: boolean
88 async function processFile (downloader: () => Promise<string>, videoImport: MVideoImportDefault, options: ProcessFileOptions) {
89 let tempVideoPath: string
90 let videoDestFile: string
91 let videoFile: VideoFileModel
94 // Download video from youtubeDL
95 tempVideoPath = await downloader()
97 // Get information about this video
98 const stats = await stat(tempVideoPath)
99 const isAble = await videoImport.User.isAbleToUploadVideo({ size: stats.size })
100 if (isAble === false) {
101 throw new Error('The user video quota is exceeded with this video to import.')
104 const { videoFileResolution } = await getVideoFileResolution(tempVideoPath)
105 const fps = await getVideoFileFPS(tempVideoPath)
106 const duration = await getDurationFromVideoFile(tempVideoPath)
108 // Create video file object in database
109 const videoFileData = {
110 extname: extname(tempVideoPath),
111 resolution: videoFileResolution,
114 videoId: videoImport.videoId
116 videoFile = new VideoFileModel(videoFileData)
118 const videoWithFiles = Object.assign(videoImport.Video, { VideoFiles: [ videoFile ], VideoStreamingPlaylists: [] })
119 // To clean files if the import fails
120 const videoImportWithFiles: MVideoImportDefaultFiles = Object.assign(videoImport, { Video: videoWithFiles })
123 videoDestFile = getVideoFilePath(videoImportWithFiles.Video, videoFile)
124 await move(tempVideoPath, videoDestFile)
125 tempVideoPath = null // This path is not used anymore
128 let thumbnailModel: MThumbnail
129 if (options.generateThumbnail) {
130 thumbnailModel = await generateVideoMiniature(videoImportWithFiles.Video, videoFile, ThumbnailType.MINIATURE)
134 let previewModel: MThumbnail
135 if (options.generatePreview) {
136 previewModel = await generateVideoMiniature(videoImportWithFiles.Video, videoFile, ThumbnailType.PREVIEW)
140 await createTorrentAndSetInfoHash(videoImportWithFiles.Video, videoFile)
142 const { videoImportUpdated, video } = await sequelizeTypescript.transaction(async t => {
143 const videoImportToUpdate = videoImportWithFiles as MVideoImportVideo
146 const video = await VideoModel.load(videoImportToUpdate.videoId, t)
147 if (!video) throw new Error('Video linked to import ' + videoImportToUpdate.videoId + ' does not exist anymore.')
149 const videoFileCreated = await videoFile.save({ transaction: t })
150 videoImportToUpdate.Video = Object.assign(video, { VideoFiles: [ videoFileCreated ] })
152 // Update video DB object
153 video.duration = duration
154 video.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED
155 await video.save({ transaction: t })
157 if (thumbnailModel) await video.addAndSaveThumbnail(thumbnailModel, t)
158 if (previewModel) await video.addAndSaveThumbnail(previewModel, t)
160 // Now we can federate the video (reload from database, we need more attributes)
161 const videoForFederation = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.uuid, t)
162 await federateVideoIfNeeded(videoForFederation, true, t)
164 // Update video import object
165 videoImportToUpdate.state = VideoImportState.SUCCESS
166 const videoImportUpdated = await videoImportToUpdate.save({ transaction: t }) as MVideoImportVideo
167 videoImportUpdated.Video = video
169 logger.info('Video %s imported.', video.uuid)
171 return { videoImportUpdated, video: videoForFederation }
174 Notifier.Instance.notifyOnFinishedVideoImport(videoImportUpdated, true)
176 if (video.isBlacklisted()) {
177 const videoBlacklist = Object.assign(video.VideoBlacklist, { Video: video })
179 Notifier.Instance.notifyOnVideoAutoBlacklist(videoBlacklist)
181 Notifier.Instance.notifyOnNewVideoIfNeeded(video)
184 // Create transcoding jobs?
185 if (video.state === VideoState.TO_TRANSCODE) {
186 await addOptimizeOrMergeAudioJob(videoImportUpdated.Video, videoFile)
191 if (tempVideoPath) await remove(tempVideoPath)
192 } catch (errUnlink) {
193 logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink })
196 videoImport.error = err.message
197 videoImport.state = VideoImportState.FAILED
198 await videoImport.save()
200 Notifier.Instance.notifyOnFinishedVideoImport(videoImport, false)