1 import { Job } from 'bull'
2 import { move, remove, stat } from 'fs-extra'
3 import { getLowercaseExtension } from '@shared/core-utils'
4 import { retryTransactionWrapper } from '@server/helpers/database-utils'
5 import { YoutubeDLWrapper } from '@server/helpers/youtube-dl'
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 { addMoveToObjectStorageJob, addOptimizeOrMergeAudioJob } 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 { MVideoImportDefault, MVideoImportDefaultFiles, MVideoImportVideo } from '@server/types/models/video/video-import'
18 VideoImportTorrentPayload,
19 VideoImportTorrentPayloadType,
20 VideoImportYoutubeDLPayload,
21 VideoImportYoutubeDLPayloadType,
23 } from '../../../../shared'
24 import { VideoImportState, VideoResolution } from '../../../../shared/models/videos'
25 import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
26 import { ffprobePromise, getDurationFromVideoFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils'
27 import { logger } from '../../../helpers/logger'
28 import { getSecureTorrentName } from '../../../helpers/utils'
29 import { createTorrentAndSetInfoHash, downloadWebTorrentVideo } from '../../../helpers/webtorrent'
30 import { VIDEO_IMPORT_TIMEOUT } from '../../../initializers/constants'
31 import { sequelizeTypescript } from '../../../initializers/database'
32 import { VideoModel } from '../../../models/video/video'
33 import { VideoFileModel } from '../../../models/video/video-file'
34 import { VideoImportModel } from '../../../models/video/video-import'
35 import { MThumbnail } from '../../../types/models/video/thumbnail'
36 import { federateVideoIfNeeded } from '../../activitypub/videos'
37 import { Notifier } from '../../notifier'
38 import { generateVideoMiniature } from '../../thumbnail'
39 import { isAudioFile } from '@shared/extra-utils'
41 async function processVideoImport (job: 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: Job, payload: VideoImportTorrentPayload) {
57 logger.info('Processing torrent video import in job %d.', job.id)
59 const videoImport = await getVideoImportOrDie(payload.videoImportId)
63 videoImportId: payload.videoImportId
66 torrentName: videoImport.torrentName ? getSecureTorrentName(videoImport.torrentName) : undefined,
67 uri: videoImport.magnetUri
69 return processFile(() => downloadWebTorrentVideo(target, VIDEO_IMPORT_TIMEOUT), videoImport, options)
72 async function processYoutubeDLImport (job: Job, payload: VideoImportYoutubeDLPayload) {
73 logger.info('Processing youtubeDL video import in job %d.', job.id)
75 const videoImport = await getVideoImportOrDie(payload.videoImportId)
78 videoImportId: videoImport.id
81 const youtubeDL = new YoutubeDLWrapper(videoImport.targetUrl, ServerConfigManager.Instance.getEnabledResolutions('vod'))
84 () => youtubeDL.downloadVideo(payload.fileExt, VIDEO_IMPORT_TIMEOUT),
90 async function getVideoImportOrDie (videoImportId: number) {
91 const videoImport = await VideoImportModel.loadAndPopulateVideo(videoImportId)
92 if (!videoImport || !videoImport.Video) {
93 throw new Error('Cannot import video %s: the video import or video linked to this import does not exist anymore.')
99 type ProcessFileOptions = {
100 type: VideoImportYoutubeDLPayloadType | VideoImportTorrentPayloadType
101 videoImportId: number
103 async function processFile (downloader: () => Promise<string>, videoImport: MVideoImportDefault, options: ProcessFileOptions) {
104 let tempVideoPath: string
105 let videoFile: VideoFileModel
108 // Download video from youtubeDL
109 tempVideoPath = await downloader()
111 // Get information about this video
112 const stats = await stat(tempVideoPath)
113 const isAble = await isAbleToUploadVideo(videoImport.User.id, stats.size)
114 if (isAble === false) {
115 throw new Error('The user video quota is exceeded with this video to import.')
118 const probe = await ffprobePromise(tempVideoPath)
120 const { resolution } = await isAudioFile(tempVideoPath, probe)
121 ? { resolution: VideoResolution.H_NOVIDEO }
122 : await getVideoFileResolution(tempVideoPath)
124 const fps = await getVideoFileFPS(tempVideoPath, probe)
125 const duration = await getDurationFromVideoFile(tempVideoPath, probe)
127 // Prepare video file object for creation in database
128 const fileExt = getLowercaseExtension(tempVideoPath)
129 const videoFileData = {
133 filename: generateWebTorrentVideoFilename(resolution, fileExt),
135 videoId: videoImport.videoId
137 videoFile = new VideoFileModel(videoFileData)
139 const hookName = options.type === 'youtube-dl'
140 ? 'filter:api.video.post-import-url.accept.result'
141 : 'filter:api.video.post-import-torrent.accept.result'
143 // Check we accept this video
144 const acceptParameters = {
146 video: videoImport.Video,
147 videoFilePath: tempVideoPath,
149 user: videoImport.User
151 const acceptedResult = await Hooks.wrapFun(isPostImportVideoAccepted, acceptParameters, hookName)
153 if (acceptedResult.accepted !== true) {
154 logger.info('Refused imported video.', { acceptedResult, acceptParameters })
156 videoImport.state = VideoImportState.REJECTED
157 await videoImport.save()
159 throw new Error(acceptedResult.errorMessage)
162 // Video is accepted, resuming preparation
163 const videoWithFiles = Object.assign(videoImport.Video, { VideoFiles: [ videoFile ], VideoStreamingPlaylists: [] })
164 // To clean files if the import fails
165 const videoImportWithFiles: MVideoImportDefaultFiles = Object.assign(videoImport, { Video: videoWithFiles })
168 const videoDestFile = VideoPathManager.Instance.getFSVideoFileOutputPath(videoImportWithFiles.Video, videoFile)
169 await move(tempVideoPath, videoDestFile)
170 tempVideoPath = null // This path is not used anymore
172 // Generate miniature if the import did not created it
173 let thumbnailModel: MThumbnail
174 let thumbnailSave: object
175 if (!videoImportWithFiles.Video.getMiniature()) {
176 thumbnailModel = await generateVideoMiniature({
177 video: videoImportWithFiles.Video,
179 type: ThumbnailType.MINIATURE
181 thumbnailSave = thumbnailModel.toJSON()
184 // Generate preview if the import did not created it
185 let previewModel: MThumbnail
186 let previewSave: object
187 if (!videoImportWithFiles.Video.getPreview()) {
188 previewModel = await generateVideoMiniature({
189 video: videoImportWithFiles.Video,
191 type: ThumbnailType.PREVIEW
193 previewSave = previewModel.toJSON()
197 await createTorrentAndSetInfoHash(videoImportWithFiles.Video, videoFile)
199 const videoFileSave = videoFile.toJSON()
201 const { videoImportUpdated, video } = await retryTransactionWrapper(() => {
202 return sequelizeTypescript.transaction(async t => {
203 const videoImportToUpdate = videoImportWithFiles as MVideoImportVideo
206 const video = await VideoModel.load(videoImportToUpdate.videoId, t)
207 if (!video) throw new Error('Video linked to import ' + videoImportToUpdate.videoId + ' does not exist anymore.')
209 const videoFileCreated = await videoFile.save({ transaction: t })
211 // Update video DB object
212 video.duration = duration
213 video.state = buildNextVideoState(video.state)
214 await video.save({ transaction: t })
216 if (thumbnailModel) await video.addAndSaveThumbnail(thumbnailModel, t)
217 if (previewModel) await video.addAndSaveThumbnail(previewModel, t)
219 // Now we can federate the video (reload from database, we need more attributes)
220 const videoForFederation = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.uuid, t)
221 await federateVideoIfNeeded(videoForFederation, true, t)
223 // Update video import object
224 videoImportToUpdate.state = VideoImportState.SUCCESS
225 const videoImportUpdated = await videoImportToUpdate.save({ transaction: t }) as MVideoImportVideo
226 videoImportUpdated.Video = video
228 videoImportToUpdate.Video = Object.assign(video, { VideoFiles: [ videoFileCreated ] })
230 logger.info('Video %s imported.', video.uuid)
232 return { videoImportUpdated, video: videoForFederation }
235 if (thumbnailModel) thumbnailModel = new ThumbnailModel(thumbnailSave)
236 if (previewModel) previewModel = new ThumbnailModel(previewSave)
238 videoFile = new VideoFileModel(videoFileSave)
244 Notifier.Instance.notifyOnFinishedVideoImport({ videoImport: videoImportUpdated, success: true })
246 if (video.isBlacklisted()) {
247 const videoBlacklist = Object.assign(video.VideoBlacklist, { Video: video })
249 Notifier.Instance.notifyOnVideoAutoBlacklist(videoBlacklist)
251 Notifier.Instance.notifyOnNewVideoIfNeeded(video)
254 if (video.state === VideoState.TO_MOVE_TO_EXTERNAL_STORAGE) {
255 return addMoveToObjectStorageJob(videoImportUpdated.Video)
258 // Create transcoding jobs?
259 if (video.state === VideoState.TO_TRANSCODE) {
260 await addOptimizeOrMergeAudioJob(videoImportUpdated.Video, videoFile, videoImport.User)
265 if (tempVideoPath) await remove(tempVideoPath)
266 } catch (errUnlink) {
267 logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink })
270 videoImport.error = err.message
271 if (videoImport.state !== VideoImportState.REJECTED) {
272 videoImport.state = VideoImportState.FAILED
274 await videoImport.save()
276 Notifier.Instance.notifyOnFinishedVideoImport({ videoImport, success: false })