1 import * as Bull from 'bull'
2 import { move, remove, stat } from 'fs-extra'
3 import { extname } from 'path'
4 import { retryTransactionWrapper } from '@server/helpers/database-utils'
5 import { isPostImportVideoAccepted } from '@server/lib/moderation'
6 import { Hooks } from '@server/lib/plugins/hooks'
7 import { isAbleToUploadVideo } from '@server/lib/user'
8 import { addOptimizeOrMergeAudioJob } from '@server/lib/video'
9 import { generateVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
10 import { ThumbnailModel } from '@server/models/video/thumbnail'
11 import { MVideoImportDefault, MVideoImportDefaultFiles, MVideoImportVideo } from '@server/types/models/video/video-import'
14 VideoImportTorrentPayload,
15 VideoImportTorrentPayloadType,
16 VideoImportYoutubeDLPayload,
17 VideoImportYoutubeDLPayloadType,
19 } from '../../../../shared'
20 import { VideoImportState } from '../../../../shared/models/videos'
21 import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
22 import { getDurationFromVideoFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils'
23 import { logger } from '../../../helpers/logger'
24 import { getSecureTorrentName } from '../../../helpers/utils'
25 import { createTorrentAndSetInfoHash, downloadWebTorrentVideo } from '../../../helpers/webtorrent'
26 import { downloadYoutubeDLVideo } from '../../../helpers/youtube-dl'
27 import { CONFIG } from '../../../initializers/config'
28 import { VIDEO_IMPORT_TIMEOUT } from '../../../initializers/constants'
29 import { sequelizeTypescript } from '../../../initializers/database'
30 import { VideoModel } from '../../../models/video/video'
31 import { VideoFileModel } from '../../../models/video/video-file'
32 import { VideoImportModel } from '../../../models/video/video-import'
33 import { MThumbnail } from '../../../types/models/video/thumbnail'
34 import { federateVideoIfNeeded } from '../../activitypub/videos'
35 import { Notifier } from '../../notifier'
36 import { generateVideoMiniature } from '../../thumbnail'
38 async function processVideoImport (job: Bull.Job) {
39 const payload = job.data as VideoImportPayload
41 if (payload.type === 'youtube-dl') return processYoutubeDLImport(job, payload)
42 if (payload.type === 'magnet-uri' || payload.type === 'torrent-file') return processTorrentImport(job, payload)
45 // ---------------------------------------------------------------------------
51 // ---------------------------------------------------------------------------
53 async function processTorrentImport (job: Bull.Job, payload: VideoImportTorrentPayload) {
54 logger.info('Processing torrent video import in job %d.', job.id)
56 const videoImport = await getVideoImportOrDie(payload.videoImportId)
60 videoImportId: payload.videoImportId
63 torrentName: videoImport.torrentName ? getSecureTorrentName(videoImport.torrentName) : undefined,
64 magnetUri: videoImport.magnetUri
66 return processFile(() => downloadWebTorrentVideo(target, VIDEO_IMPORT_TIMEOUT), videoImport, options)
69 async function processYoutubeDLImport (job: Bull.Job, payload: VideoImportYoutubeDLPayload) {
70 logger.info('Processing youtubeDL video import in job %d.', job.id)
72 const videoImport = await getVideoImportOrDie(payload.videoImportId)
75 videoImportId: videoImport.id
79 () => downloadYoutubeDLVideo(videoImport.targetUrl, payload.fileExt, VIDEO_IMPORT_TIMEOUT),
85 async function getVideoImportOrDie (videoImportId: number) {
86 const videoImport = await VideoImportModel.loadAndPopulateVideo(videoImportId)
87 if (!videoImport || !videoImport.Video) {
88 throw new Error('Cannot import video %s: the video import or video linked to this import does not exist anymore.')
94 type ProcessFileOptions = {
95 type: VideoImportYoutubeDLPayloadType | VideoImportTorrentPayloadType
98 async function processFile (downloader: () => Promise<string>, videoImport: MVideoImportDefault, options: ProcessFileOptions) {
99 let tempVideoPath: string
100 let videoDestFile: string
101 let videoFile: VideoFileModel
104 // Download video from youtubeDL
105 tempVideoPath = await downloader()
107 // Get information about this video
108 const stats = await stat(tempVideoPath)
109 const isAble = await isAbleToUploadVideo(videoImport.User.id, stats.size)
110 if (isAble === false) {
111 throw new Error('The user video quota is exceeded with this video to import.')
114 const { videoFileResolution } = await getVideoFileResolution(tempVideoPath)
115 const fps = await getVideoFileFPS(tempVideoPath)
116 const duration = await getDurationFromVideoFile(tempVideoPath)
118 // Prepare video file object for creation in database
119 const fileExt = extname(tempVideoPath)
120 const videoFileData = {
122 resolution: videoFileResolution,
124 filename: generateVideoFilename(videoImport.Video, false, videoFileResolution, fileExt),
126 videoId: videoImport.videoId
128 videoFile = new VideoFileModel(videoFileData)
130 const hookName = options.type === 'youtube-dl'
131 ? 'filter:api.video.post-import-url.accept.result'
132 : 'filter:api.video.post-import-torrent.accept.result'
134 // Check we accept this video
135 const acceptParameters = {
137 video: videoImport.Video,
138 videoFilePath: tempVideoPath,
140 user: videoImport.User
142 const acceptedResult = await Hooks.wrapFun(isPostImportVideoAccepted, acceptParameters, hookName)
144 if (acceptedResult.accepted !== true) {
145 logger.info('Refused imported video.', { acceptedResult, acceptParameters })
147 videoImport.state = VideoImportState.REJECTED
148 await videoImport.save()
150 throw new Error(acceptedResult.errorMessage)
153 // Video is accepted, resuming preparation
154 const videoWithFiles = Object.assign(videoImport.Video, { VideoFiles: [ videoFile ], VideoStreamingPlaylists: [] })
155 // To clean files if the import fails
156 const videoImportWithFiles: MVideoImportDefaultFiles = Object.assign(videoImport, { Video: videoWithFiles })
159 videoDestFile = getVideoFilePath(videoImportWithFiles.Video, videoFile)
160 await move(tempVideoPath, videoDestFile)
161 tempVideoPath = null // This path is not used anymore
163 // Generate miniature if the import did not created it
164 let thumbnailModel: MThumbnail
165 let thumbnailSave: object
166 if (!videoImportWithFiles.Video.getMiniature()) {
167 thumbnailModel = await generateVideoMiniature({
168 video: videoImportWithFiles.Video,
170 type: ThumbnailType.MINIATURE
172 thumbnailSave = thumbnailModel.toJSON()
175 // Generate preview if the import did not created it
176 let previewModel: MThumbnail
177 let previewSave: object
178 if (!videoImportWithFiles.Video.getPreview()) {
179 previewModel = await generateVideoMiniature({
180 video: videoImportWithFiles.Video,
182 type: ThumbnailType.PREVIEW
184 previewSave = previewModel.toJSON()
188 await createTorrentAndSetInfoHash(videoImportWithFiles.Video, videoFile)
190 const videoFileSave = videoFile.toJSON()
192 const { videoImportUpdated, video } = await retryTransactionWrapper(() => {
193 return sequelizeTypescript.transaction(async t => {
194 const videoImportToUpdate = videoImportWithFiles as MVideoImportVideo
197 const video = await VideoModel.load(videoImportToUpdate.videoId, t)
198 if (!video) throw new Error('Video linked to import ' + videoImportToUpdate.videoId + ' does not exist anymore.')
200 const videoFileCreated = await videoFile.save({ transaction: t })
202 // Update video DB object
203 video.duration = duration
204 video.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED
205 await video.save({ transaction: t })
207 if (thumbnailModel) await video.addAndSaveThumbnail(thumbnailModel, t)
208 if (previewModel) await video.addAndSaveThumbnail(previewModel, t)
210 // Now we can federate the video (reload from database, we need more attributes)
211 const videoForFederation = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.uuid, t)
212 await federateVideoIfNeeded(videoForFederation, true, t)
214 // Update video import object
215 videoImportToUpdate.state = VideoImportState.SUCCESS
216 const videoImportUpdated = await videoImportToUpdate.save({ transaction: t }) as MVideoImportVideo
217 videoImportUpdated.Video = video
219 videoImportToUpdate.Video = Object.assign(video, { VideoFiles: [ videoFileCreated ] })
221 logger.info('Video %s imported.', video.uuid)
223 return { videoImportUpdated, video: videoForFederation }
226 if (thumbnailModel) thumbnailModel = new ThumbnailModel(thumbnailSave)
227 if (previewModel) previewModel = new ThumbnailModel(previewSave)
229 videoFile = new VideoFileModel(videoFileSave)
235 Notifier.Instance.notifyOnFinishedVideoImport(videoImportUpdated, true)
237 if (video.isBlacklisted()) {
238 const videoBlacklist = Object.assign(video.VideoBlacklist, { Video: video })
240 Notifier.Instance.notifyOnVideoAutoBlacklist(videoBlacklist)
242 Notifier.Instance.notifyOnNewVideoIfNeeded(video)
245 // Create transcoding jobs?
246 if (video.state === VideoState.TO_TRANSCODE) {
247 await addOptimizeOrMergeAudioJob(videoImportUpdated.Video, videoFile, videoImport.User)
252 if (tempVideoPath) await remove(tempVideoPath)
253 } catch (errUnlink) {
254 logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink })
257 videoImport.error = err.message
258 if (videoImport.state !== VideoImportState.REJECTED) {
259 videoImport.state = VideoImportState.FAILED
261 await videoImport.save()
263 Notifier.Instance.notifyOnFinishedVideoImport(videoImport, false)