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 { VideoState } from '../../../../shared'
11 import { JobQueue } from '../index'
12 import { federateVideoIfNeeded } from '../../activitypub'
13 import { VideoModel } from '../../../models/video/video'
14 import { createTorrentAndSetInfoHash, 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'
24 import { getVideoFilePath } from '@server/lib/video-paths'
26 type VideoImportYoutubeDLPayload = {
31 downloadThumbnail: boolean
32 downloadPreview: boolean
35 type VideoImportTorrentPayload = {
36 type: 'magnet-uri' | 'torrent-file'
40 export type VideoImportPayload = VideoImportYoutubeDLPayload | VideoImportTorrentPayload
42 async function processVideoImport (job: Bull.Job) {
43 const payload = job.data as VideoImportPayload
45 if (payload.type === 'youtube-dl') return processYoutubeDLImport(job, payload)
46 if (payload.type === 'magnet-uri' || payload.type === 'torrent-file') return processTorrentImport(job, payload)
49 // ---------------------------------------------------------------------------
55 // ---------------------------------------------------------------------------
57 async function processTorrentImport (job: Bull.Job, payload: VideoImportTorrentPayload) {
58 logger.info('Processing torrent video import in job %d.', job.id)
60 const videoImport = await getVideoImportOrDie(payload.videoImportId)
63 videoImportId: payload.videoImportId,
65 downloadThumbnail: false,
66 downloadPreview: false,
68 generateThumbnail: true,
72 torrentName: videoImport.torrentName ? getSecureTorrentName(videoImport.torrentName) : undefined,
73 magnetUri: videoImport.magnetUri
75 return processFile(() => downloadWebTorrentVideo(target, VIDEO_IMPORT_TIMEOUT), videoImport, options)
78 async function processYoutubeDLImport (job: Bull.Job, payload: VideoImportYoutubeDLPayload) {
79 logger.info('Processing youtubeDL video import in job %d.', job.id)
81 const videoImport = await getVideoImportOrDie(payload.videoImportId)
83 videoImportId: videoImport.id,
85 downloadThumbnail: payload.downloadThumbnail,
86 downloadPreview: payload.downloadPreview,
87 thumbnailUrl: payload.thumbnailUrl,
89 generateThumbnail: false,
90 generatePreview: false
93 return processFile(() => downloadYoutubeDLVideo(videoImport.targetUrl, VIDEO_IMPORT_TIMEOUT), videoImport, options)
96 async function getVideoImportOrDie (videoImportId: number) {
97 const videoImport = await VideoImportModel.loadAndPopulateVideo(videoImportId)
98 if (!videoImport || !videoImport.Video) {
99 throw new Error('Cannot import video %s: the video import or video linked to this import does not exist anymore.')
105 type ProcessFileOptions = {
106 videoImportId: number
108 downloadThumbnail: boolean
109 downloadPreview: boolean
110 thumbnailUrl?: string
112 generateThumbnail: boolean
113 generatePreview: boolean
115 async function processFile (downloader: () => Promise<string>, videoImport: MVideoImportDefault, options: ProcessFileOptions) {
116 let tempVideoPath: string
117 let videoDestFile: string
118 let videoFile: VideoFileModel
121 // Download video from youtubeDL
122 tempVideoPath = await downloader()
124 // Get information about this video
125 const stats = await stat(tempVideoPath)
126 const isAble = await videoImport.User.isAbleToUploadVideo({ size: stats.size })
127 if (isAble === false) {
128 throw new Error('The user video quota is exceeded with this video to import.')
131 const { videoFileResolution } = await getVideoFileResolution(tempVideoPath)
132 const fps = await getVideoFileFPS(tempVideoPath)
133 const duration = await getDurationFromVideoFile(tempVideoPath)
135 // Create video file object in database
136 const videoFileData = {
137 extname: extname(tempVideoPath),
138 resolution: videoFileResolution,
141 videoId: videoImport.videoId
143 videoFile = new VideoFileModel(videoFileData)
145 const videoWithFiles = Object.assign(videoImport.Video, { VideoFiles: [ videoFile ], VideoStreamingPlaylists: [] })
146 // To clean files if the import fails
147 const videoImportWithFiles: MVideoImportDefaultFiles = Object.assign(videoImport, { Video: videoWithFiles })
150 videoDestFile = getVideoFilePath(videoImportWithFiles.Video, videoFile)
151 await move(tempVideoPath, videoDestFile)
152 tempVideoPath = null // This path is not used anymore
155 let thumbnailModel: MThumbnail
156 if (options.downloadThumbnail && options.thumbnailUrl) {
157 thumbnailModel = await createVideoMiniatureFromUrl(options.thumbnailUrl, videoImportWithFiles.Video, ThumbnailType.MINIATURE)
158 } else if (options.generateThumbnail || options.downloadThumbnail) {
159 thumbnailModel = await generateVideoMiniature(videoImportWithFiles.Video, videoFile, ThumbnailType.MINIATURE)
163 let previewModel: MThumbnail
164 if (options.downloadPreview && options.thumbnailUrl) {
165 previewModel = await createVideoMiniatureFromUrl(options.thumbnailUrl, videoImportWithFiles.Video, ThumbnailType.PREVIEW)
166 } else if (options.generatePreview || options.downloadPreview) {
167 previewModel = await generateVideoMiniature(videoImportWithFiles.Video, videoFile, ThumbnailType.PREVIEW)
171 await createTorrentAndSetInfoHash(videoImportWithFiles.Video, videoFile)
173 const { videoImportUpdated, video } = await sequelizeTypescript.transaction(async t => {
174 const videoImportToUpdate = videoImportWithFiles as MVideoImportVideo
177 const video = await VideoModel.load(videoImportToUpdate.videoId, t)
178 if (!video) throw new Error('Video linked to import ' + videoImportToUpdate.videoId + ' does not exist anymore.')
180 const videoFileCreated = await videoFile.save({ transaction: t })
181 videoImportToUpdate.Video = Object.assign(video, { VideoFiles: [ videoFileCreated ] })
183 // Update video DB object
184 video.duration = duration
185 video.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED
186 await video.save({ transaction: t })
188 if (thumbnailModel) await video.addAndSaveThumbnail(thumbnailModel, t)
189 if (previewModel) await video.addAndSaveThumbnail(previewModel, t)
191 // Now we can federate the video (reload from database, we need more attributes)
192 const videoForFederation = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.uuid, t)
193 await federateVideoIfNeeded(videoForFederation, true, t)
195 // Update video import object
196 videoImportToUpdate.state = VideoImportState.SUCCESS
197 const videoImportUpdated = await videoImportToUpdate.save({ transaction: t }) as MVideoImportVideo
198 videoImportUpdated.Video = video
200 logger.info('Video %s imported.', video.uuid)
202 return { videoImportUpdated, video: videoForFederation }
205 Notifier.Instance.notifyOnFinishedVideoImport(videoImportUpdated, true)
207 if (video.isBlacklisted()) {
208 const videoBlacklist = Object.assign(video.VideoBlacklist, { Video: video })
210 Notifier.Instance.notifyOnVideoAutoBlacklist(videoBlacklist)
212 Notifier.Instance.notifyOnNewVideoIfNeeded(video)
215 // Create transcoding jobs?
216 if (video.state === VideoState.TO_TRANSCODE) {
217 // Put uuid because we don't have id auto incremented for now
219 type: 'optimize' as 'optimize',
220 videoUUID: videoImportUpdated.Video.uuid,
224 await JobQueue.Instance.createJob({ type: 'video-transcoding', payload: dataInput })
229 if (tempVideoPath) await remove(tempVideoPath)
230 } catch (errUnlink) {
231 logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink })
234 videoImport.error = err.message
235 videoImport.state = VideoImportState.FAILED
236 await videoImport.save()
238 Notifier.Instance.notifyOnFinishedVideoImport(videoImport, false)