1 import { Job } from 'bull'
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 { isPostImportVideoAccepted } from '@server/lib/moderation'
6 import { generateWebTorrentVideoFilename } from '@server/lib/paths'
7 import { Hooks } from '@server/lib/plugins/hooks'
8 import { ServerConfigManager } from '@server/lib/server-config-manager'
9 import { isAbleToUploadVideo } from '@server/lib/user'
10 import { addMoveToObjectStorageJob, addOptimizeOrMergeAudioJob } from '@server/lib/video'
11 import { VideoPathManager } from '@server/lib/video-path-manager'
12 import { buildNextVideoState } from '@server/lib/video-state'
13 import { ThumbnailModel } from '@server/models/video/thumbnail'
14 import { MVideoImportDefault, MVideoImportDefaultFiles, MVideoImportVideo } from '@server/types/models/video/video-import'
15 import { getLowercaseExtension } from '@shared/core-utils'
16 import { isAudioFile } from '@shared/extra-utils'
21 VideoImportTorrentPayload,
22 VideoImportTorrentPayloadType,
23 VideoImportYoutubeDLPayload,
24 VideoImportYoutubeDLPayloadType,
27 } from '@shared/models'
28 import { ffprobePromise, getDurationFromVideoFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils'
29 import { logger } from '../../../helpers/logger'
30 import { getSecureTorrentName } from '../../../helpers/utils'
31 import { createTorrentAndSetInfoHash, downloadWebTorrentVideo } from '../../../helpers/webtorrent'
32 import { VIDEO_IMPORT_TIMEOUT } from '../../../initializers/constants'
33 import { sequelizeTypescript } from '../../../initializers/database'
34 import { VideoModel } from '../../../models/video/video'
35 import { VideoFileModel } from '../../../models/video/video-file'
36 import { VideoImportModel } from '../../../models/video/video-import'
37 import { MThumbnail } from '../../../types/models/video/thumbnail'
38 import { federateVideoIfNeeded } from '../../activitypub/videos'
39 import { Notifier } from '../../notifier'
40 import { generateVideoMiniature } from '../../thumbnail'
42 async function processVideoImport (job: 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: Job, payload: VideoImportTorrentPayload) {
58 logger.info('Processing torrent video import in job %d.', job.id)
60 const videoImport = await getVideoImportOrDie(payload.videoImportId)
64 videoImportId: payload.videoImportId
67 torrentName: videoImport.torrentName ? getSecureTorrentName(videoImport.torrentName) : undefined,
68 uri: videoImport.magnetUri
70 return processFile(() => downloadWebTorrentVideo(target, VIDEO_IMPORT_TIMEOUT), videoImport, options)
73 async function processYoutubeDLImport (job: Job, payload: VideoImportYoutubeDLPayload) {
74 logger.info('Processing youtubeDL video import in job %d.', job.id)
76 const videoImport = await getVideoImportOrDie(payload.videoImportId)
79 videoImportId: videoImport.id
82 const youtubeDL = new YoutubeDLWrapper(videoImport.targetUrl, ServerConfigManager.Instance.getEnabledResolutions('vod'))
85 () => youtubeDL.downloadVideo(payload.fileExt, VIDEO_IMPORT_TIMEOUT),
91 async function getVideoImportOrDie (videoImportId: number) {
92 const videoImport = await VideoImportModel.loadAndPopulateVideo(videoImportId)
93 if (!videoImport || !videoImport.Video) {
94 throw new Error('Cannot import video %s: the video import or video linked to this import does not exist anymore.')
100 type ProcessFileOptions = {
101 type: VideoImportYoutubeDLPayloadType | VideoImportTorrentPayloadType
102 videoImportId: number
104 async function processFile (downloader: () => Promise<string>, videoImport: MVideoImportDefault, options: ProcessFileOptions) {
105 let tempVideoPath: string
106 let videoFile: VideoFileModel
109 // Download video from youtubeDL
110 tempVideoPath = await downloader()
112 // Get information about this video
113 const stats = await stat(tempVideoPath)
114 const isAble = await isAbleToUploadVideo(videoImport.User.id, stats.size)
115 if (isAble === false) {
116 throw new Error('The user video quota is exceeded with this video to import.')
119 const probe = await ffprobePromise(tempVideoPath)
121 const { resolution } = await isAudioFile(tempVideoPath, probe)
122 ? { resolution: VideoResolution.H_NOVIDEO }
123 : await getVideoFileResolution(tempVideoPath)
125 const fps = await getVideoFileFPS(tempVideoPath, probe)
126 const duration = await getDurationFromVideoFile(tempVideoPath, probe)
128 // Prepare video file object for creation in database
129 const fileExt = getLowercaseExtension(tempVideoPath)
130 const videoFileData = {
134 filename: generateWebTorrentVideoFilename(resolution, fileExt),
136 videoId: videoImport.videoId
138 videoFile = new VideoFileModel(videoFileData)
140 const hookName = options.type === 'youtube-dl'
141 ? 'filter:api.video.post-import-url.accept.result'
142 : 'filter:api.video.post-import-torrent.accept.result'
144 // Check we accept this video
145 const acceptParameters = {
147 video: videoImport.Video,
148 videoFilePath: tempVideoPath,
150 user: videoImport.User
152 const acceptedResult = await Hooks.wrapFun(isPostImportVideoAccepted, acceptParameters, hookName)
154 if (acceptedResult.accepted !== true) {
155 logger.info('Refused imported video.', { acceptedResult, acceptParameters })
157 videoImport.state = VideoImportState.REJECTED
158 await videoImport.save()
160 throw new Error(acceptedResult.errorMessage)
163 // Video is accepted, resuming preparation
164 const videoWithFiles = Object.assign(videoImport.Video, { VideoFiles: [ videoFile ], VideoStreamingPlaylists: [] })
165 // To clean files if the import fails
166 const videoImportWithFiles: MVideoImportDefaultFiles = Object.assign(videoImport, { Video: videoWithFiles })
169 const videoDestFile = VideoPathManager.Instance.getFSVideoFileOutputPath(videoImportWithFiles.Video, videoFile)
170 await move(tempVideoPath, videoDestFile)
171 tempVideoPath = null // This path is not used anymore
173 // Generate miniature if the import did not created it
174 let thumbnailModel: MThumbnail
175 let thumbnailSave: object
176 if (!videoImportWithFiles.Video.getMiniature()) {
177 thumbnailModel = await generateVideoMiniature({
178 video: videoImportWithFiles.Video,
180 type: ThumbnailType.MINIATURE
182 thumbnailSave = thumbnailModel.toJSON()
185 // Generate preview if the import did not created it
186 let previewModel: MThumbnail
187 let previewSave: object
188 if (!videoImportWithFiles.Video.getPreview()) {
189 previewModel = await generateVideoMiniature({
190 video: videoImportWithFiles.Video,
192 type: ThumbnailType.PREVIEW
194 previewSave = previewModel.toJSON()
198 await createTorrentAndSetInfoHash(videoImportWithFiles.Video, videoFile)
200 const videoFileSave = videoFile.toJSON()
202 const { videoImportUpdated, video } = await retryTransactionWrapper(() => {
203 return sequelizeTypescript.transaction(async t => {
204 const videoImportToUpdate = videoImportWithFiles as MVideoImportVideo
207 const video = await VideoModel.load(videoImportToUpdate.videoId, t)
208 if (!video) throw new Error('Video linked to import ' + videoImportToUpdate.videoId + ' does not exist anymore.')
210 const videoFileCreated = await videoFile.save({ transaction: t })
212 // Update video DB object
213 video.duration = duration
214 video.state = buildNextVideoState(video.state)
215 await video.save({ transaction: t })
217 if (thumbnailModel) await video.addAndSaveThumbnail(thumbnailModel, t)
218 if (previewModel) await video.addAndSaveThumbnail(previewModel, t)
220 // Now we can federate the video (reload from database, we need more attributes)
221 const videoForFederation = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.uuid, t)
222 await federateVideoIfNeeded(videoForFederation, true, t)
224 // Update video import object
225 videoImportToUpdate.state = VideoImportState.SUCCESS
226 const videoImportUpdated = await videoImportToUpdate.save({ transaction: t }) as MVideoImportVideo
227 videoImportUpdated.Video = video
229 videoImportToUpdate.Video = Object.assign(video, { VideoFiles: [ videoFileCreated ] })
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 Notifier.Instance.notifyOnFinishedVideoImport({ videoImport: videoImportUpdated, success: true })
247 if (video.isBlacklisted()) {
248 const videoBlacklist = Object.assign(video.VideoBlacklist, { Video: video })
250 Notifier.Instance.notifyOnVideoAutoBlacklist(videoBlacklist)
252 Notifier.Instance.notifyOnNewVideoIfNeeded(video)
255 if (video.state === VideoState.TO_MOVE_TO_EXTERNAL_STORAGE) {
256 return addMoveToObjectStorageJob(videoImportUpdated.Video)
259 // Create transcoding jobs?
260 if (video.state === VideoState.TO_TRANSCODE) {
261 await addOptimizeOrMergeAudioJob(videoImportUpdated.Video, videoFile, videoImport.User)
266 if (tempVideoPath) await remove(tempVideoPath)
267 } catch (errUnlink) {
268 logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink })
271 videoImport.error = err.message
272 if (videoImport.state !== VideoImportState.REJECTED) {
273 videoImport.state = VideoImportState.FAILED
275 await videoImport.save()
277 Notifier.Instance.notifyOnFinishedVideoImport({ videoImport, success: false })