1 import { Job } from 'bullmq'
2 import { move, remove, stat } from 'fs-extra'
3 import { retryTransactionWrapper } from '@server/helpers/database-utils'
4 import { YoutubeDLWrapper } from '@server/helpers/youtube-dl'
5 import { CONFIG } from '@server/initializers/config'
6 import { isPostImportVideoAccepted } from '@server/lib/moderation'
7 import { generateWebTorrentVideoFilename } from '@server/lib/paths'
8 import { Hooks } from '@server/lib/plugins/hooks'
9 import { ServerConfigManager } from '@server/lib/server-config-manager'
10 import { isAbleToUploadVideo } from '@server/lib/user'
11 import { buildMoveToObjectStorageJob, buildOptimizeOrMergeAudioJob } from '@server/lib/video'
12 import { VideoPathManager } from '@server/lib/video-path-manager'
13 import { buildNextVideoState } from '@server/lib/video-state'
14 import { ThumbnailModel } from '@server/models/video/thumbnail'
15 import { MUserId, MVideoFile, MVideoFullLight } from '@server/types/models'
16 import { MVideoImport, MVideoImportDefault, MVideoImportDefaultFiles, MVideoImportVideo } from '@server/types/models/video/video-import'
17 import { getLowercaseExtension } from '@shared/core-utils'
18 import { isAudioFile } from '@shared/extra-utils'
22 VideoImportPreventExceptionResult,
24 VideoImportTorrentPayload,
25 VideoImportTorrentPayloadType,
26 VideoImportYoutubeDLPayload,
27 VideoImportYoutubeDLPayloadType,
30 } from '@shared/models'
31 import { ffprobePromise, getVideoStreamDimensionsInfo, getVideoStreamDuration, getVideoStreamFPS } from '../../../helpers/ffmpeg'
32 import { logger } from '../../../helpers/logger'
33 import { getSecureTorrentName } from '../../../helpers/utils'
34 import { createTorrentAndSetInfoHash, downloadWebTorrentVideo } from '../../../helpers/webtorrent'
35 import { JOB_TTL } from '../../../initializers/constants'
36 import { sequelizeTypescript } from '../../../initializers/database'
37 import { VideoModel } from '../../../models/video/video'
38 import { VideoFileModel } from '../../../models/video/video-file'
39 import { VideoImportModel } from '../../../models/video/video-import'
40 import { federateVideoIfNeeded } from '../../activitypub/videos'
41 import { Notifier } from '../../notifier'
42 import { generateVideoMiniature } from '../../thumbnail'
43 import { JobQueue } from '../job-queue'
45 async function processVideoImport (job: Job): Promise<VideoImportPreventExceptionResult> {
46 const payload = job.data as VideoImportPayload
48 const videoImport = await getVideoImportOrDie(payload)
49 if (videoImport.state === VideoImportState.CANCELLED) {
50 logger.info('Do not process import since it has been cancelled', { payload })
51 return { resultType: 'success' }
54 videoImport.state = VideoImportState.PROCESSING
55 await videoImport.save()
58 if (payload.type === 'youtube-dl') await processYoutubeDLImport(job, videoImport, payload)
59 if (payload.type === 'magnet-uri' || payload.type === 'torrent-file') await processTorrentImport(job, videoImport, payload)
61 return { resultType: 'success' }
63 if (!payload.preventException) throw err
65 logger.warn('Catch error in video import to send value to parent job.', { payload, err })
66 return { resultType: 'error' }
70 // ---------------------------------------------------------------------------
76 // ---------------------------------------------------------------------------
78 async function processTorrentImport (job: Job, videoImport: MVideoImportDefault, payload: VideoImportTorrentPayload) {
79 logger.info('Processing torrent video import in job %s.', job.id)
81 const options = { type: payload.type, videoImportId: payload.videoImportId }
84 torrentName: videoImport.torrentName ? getSecureTorrentName(videoImport.torrentName) : undefined,
85 uri: videoImport.magnetUri
87 return processFile(() => downloadWebTorrentVideo(target, JOB_TTL['video-import']), videoImport, options)
90 async function processYoutubeDLImport (job: Job, videoImport: MVideoImportDefault, payload: VideoImportYoutubeDLPayload) {
91 logger.info('Processing youtubeDL video import in job %s.', job.id)
93 const options = { type: payload.type, videoImportId: videoImport.id }
95 const youtubeDL = new YoutubeDLWrapper(
96 videoImport.targetUrl,
97 ServerConfigManager.Instance.getEnabledResolutions('vod'),
98 CONFIG.TRANSCODING.ALWAYS_TRANSCODE_ORIGINAL_RESOLUTION
102 () => youtubeDL.downloadVideo(payload.fileExt, JOB_TTL['video-import']),
108 async function getVideoImportOrDie (payload: VideoImportPayload) {
109 const videoImport = await VideoImportModel.loadAndPopulateVideo(payload.videoImportId)
110 if (!videoImport?.Video) {
111 throw new Error(`Cannot import video ${payload.videoImportId}: the video import or video linked to this import does not exist anymore.`)
117 type ProcessFileOptions = {
118 type: VideoImportYoutubeDLPayloadType | VideoImportTorrentPayloadType
119 videoImportId: number
121 async function processFile (downloader: () => Promise<string>, videoImport: MVideoImportDefault, options: ProcessFileOptions) {
122 let tempVideoPath: string
123 let videoFile: VideoFileModel
126 // Download video from youtubeDL
127 tempVideoPath = await downloader()
129 // Get information about this video
130 const stats = await stat(tempVideoPath)
131 const isAble = await isAbleToUploadVideo(videoImport.User.id, stats.size)
132 if (isAble === false) {
133 throw new Error('The user video quota is exceeded with this video to import.')
136 const probe = await ffprobePromise(tempVideoPath)
138 const { resolution } = await isAudioFile(tempVideoPath, probe)
139 ? { resolution: VideoResolution.H_NOVIDEO }
140 : await getVideoStreamDimensionsInfo(tempVideoPath)
142 const fps = await getVideoStreamFPS(tempVideoPath, probe)
143 const duration = await getVideoStreamDuration(tempVideoPath, probe)
145 // Prepare video file object for creation in database
146 const fileExt = getLowercaseExtension(tempVideoPath)
147 const videoFileData = {
151 filename: generateWebTorrentVideoFilename(resolution, fileExt),
153 videoId: videoImport.videoId
155 videoFile = new VideoFileModel(videoFileData)
157 const hookName = options.type === 'youtube-dl'
158 ? 'filter:api.video.post-import-url.accept.result'
159 : 'filter:api.video.post-import-torrent.accept.result'
161 // Check we accept this video
162 const acceptParameters = {
164 video: videoImport.Video,
165 videoFilePath: tempVideoPath,
167 user: videoImport.User
169 const acceptedResult = await Hooks.wrapFun(isPostImportVideoAccepted, acceptParameters, hookName)
171 if (acceptedResult.accepted !== true) {
172 logger.info('Refused imported video.', { acceptedResult, acceptParameters })
174 videoImport.state = VideoImportState.REJECTED
175 await videoImport.save()
177 throw new Error(acceptedResult.errorMessage)
180 // Video is accepted, resuming preparation
181 const videoFileLockReleaser = await VideoPathManager.Instance.lockFiles(videoImport.Video.uuid)
184 const videoImportWithFiles = await refreshVideoImportFromDB(videoImport, videoFile)
187 const videoDestFile = VideoPathManager.Instance.getFSVideoFileOutputPath(videoImportWithFiles.Video, videoFile)
188 await move(tempVideoPath, videoDestFile)
190 tempVideoPath = null // This path is not used anymore
193 miniatureModel: thumbnailModel,
194 miniatureJSONSave: thumbnailSave
195 } = await generateMiniature(videoImportWithFiles, videoFile, ThumbnailType.MINIATURE)
198 miniatureModel: previewModel,
199 miniatureJSONSave: previewSave
200 } = await generateMiniature(videoImportWithFiles, videoFile, ThumbnailType.PREVIEW)
203 await createTorrentAndSetInfoHash(videoImportWithFiles.Video, videoFile)
205 const videoFileSave = videoFile.toJSON()
207 const { videoImportUpdated, video } = await retryTransactionWrapper(() => {
208 return sequelizeTypescript.transaction(async t => {
210 const video = await VideoModel.load(videoImportWithFiles.videoId, t)
211 if (!video) throw new Error('Video linked to import ' + videoImportWithFiles.videoId + ' does not exist anymore.')
213 await videoFile.save({ transaction: t })
215 // Update video DB object
216 video.duration = duration
217 video.state = buildNextVideoState(video.state)
218 await video.save({ transaction: t })
220 if (thumbnailModel) await video.addAndSaveThumbnail(thumbnailModel, t)
221 if (previewModel) await video.addAndSaveThumbnail(previewModel, t)
223 // Now we can federate the video (reload from database, we need more attributes)
224 const videoForFederation = await VideoModel.loadFull(video.uuid, t)
225 await federateVideoIfNeeded(videoForFederation, true, t)
227 // Update video import object
228 videoImportWithFiles.state = VideoImportState.SUCCESS
229 const videoImportUpdated = await videoImportWithFiles.save({ transaction: t }) as MVideoImport
231 logger.info('Video %s imported.', video.uuid)
233 return { videoImportUpdated, video: videoForFederation }
236 if (thumbnailModel) thumbnailModel = new ThumbnailModel(thumbnailSave)
237 if (previewModel) previewModel = new ThumbnailModel(previewSave)
239 videoFile = new VideoFileModel(videoFileSave)
245 await afterImportSuccess({ videoImport: videoImportUpdated, video, videoFile, user: videoImport.User })
247 videoFileLockReleaser()
250 await onImportError(err, tempVideoPath, videoImport)
256 async function refreshVideoImportFromDB (videoImport: MVideoImportDefault, videoFile: MVideoFile): Promise<MVideoImportDefaultFiles> {
257 // Refresh video, privacy may have changed
258 const video = await videoImport.Video.reload()
259 const videoWithFiles = Object.assign(video, { VideoFiles: [ videoFile ], VideoStreamingPlaylists: [] })
261 return Object.assign(videoImport, { Video: videoWithFiles })
264 async function generateMiniature (videoImportWithFiles: MVideoImportDefaultFiles, videoFile: MVideoFile, thumbnailType: ThumbnailType) {
265 // Generate miniature if the import did not created it
266 const needsMiniature = thumbnailType === ThumbnailType.MINIATURE
267 ? !videoImportWithFiles.Video.getMiniature()
268 : !videoImportWithFiles.Video.getPreview()
270 if (!needsMiniature) {
272 miniatureModel: null,
273 miniatureJSONSave: null
277 const miniatureModel = await generateVideoMiniature({
278 video: videoImportWithFiles.Video,
282 const miniatureJSONSave = miniatureModel.toJSON()
290 async function afterImportSuccess (options: {
291 videoImport: MVideoImport
292 video: MVideoFullLight
293 videoFile: MVideoFile
296 const { video, videoFile, videoImport, user } = options
298 Notifier.Instance.notifyOnFinishedVideoImport({ videoImport: Object.assign(videoImport, { Video: video }), success: true })
300 if (video.isBlacklisted()) {
301 const videoBlacklist = Object.assign(video.VideoBlacklist, { Video: video })
303 Notifier.Instance.notifyOnVideoAutoBlacklist(videoBlacklist)
305 Notifier.Instance.notifyOnNewVideoIfNeeded(video)
308 if (video.state === VideoState.TO_MOVE_TO_EXTERNAL_STORAGE) {
309 await JobQueue.Instance.createJob(
310 await buildMoveToObjectStorageJob({ video, previousVideoState: VideoState.TO_IMPORT })
315 if (video.state === VideoState.TO_TRANSCODE) { // Create transcoding jobs?
316 await JobQueue.Instance.createJob(
317 await buildOptimizeOrMergeAudioJob({ video, videoFile, user })
322 async function onImportError (err: Error, tempVideoPath: string, videoImport: MVideoImportVideo) {
324 if (tempVideoPath) await remove(tempVideoPath)
325 } catch (errUnlink) {
326 logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink })
329 videoImport.error = err.message
330 if (videoImport.state !== VideoImportState.REJECTED) {
331 videoImport.state = VideoImportState.FAILED
333 await videoImport.save()
335 Notifier.Instance.notifyOnFinishedVideoImport({ videoImport, success: false })