1 import * as Bull from 'bull'
2 import { move, remove, stat } from 'fs-extra'
3 import { extname } from 'path'
4 import { getLowercaseExtension } from '@server/helpers/core-utils'
5 import { retryTransactionWrapper } from '@server/helpers/database-utils'
6 import { YoutubeDL } from '@server/helpers/youtube-dl'
7 import { isPostImportVideoAccepted } from '@server/lib/moderation'
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 { addOptimizeOrMergeAudioJob } from '@server/lib/video'
12 import { generateVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
13 import { ThumbnailModel } from '@server/models/video/thumbnail'
14 import { MVideoImportDefault, MVideoImportDefaultFiles, MVideoImportVideo } from '@server/types/models/video/video-import'
17 VideoImportTorrentPayload,
18 VideoImportTorrentPayloadType,
19 VideoImportYoutubeDLPayload,
20 VideoImportYoutubeDLPayloadType,
22 } from '../../../../shared'
23 import { VideoImportState } from '../../../../shared/models/videos'
24 import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
25 import { getDurationFromVideoFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils'
26 import { logger } from '../../../helpers/logger'
27 import { getSecureTorrentName } from '../../../helpers/utils'
28 import { createTorrentAndSetInfoHash, downloadWebTorrentVideo } from '../../../helpers/webtorrent'
29 import { CONFIG } from '../../../initializers/config'
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'
40 async function processVideoImport (job: Bull.Job) {
41 const payload = job.data as VideoImportPayload
43 if (payload.type === 'youtube-dl') return processYoutubeDLImport(job, payload)
44 if (payload.type === 'magnet-uri' || payload.type === 'torrent-file') return processTorrentImport(job, payload)
47 // ---------------------------------------------------------------------------
53 // ---------------------------------------------------------------------------
55 async function processTorrentImport (job: Bull.Job, payload: VideoImportTorrentPayload) {
56 logger.info('Processing torrent video import in job %d.', job.id)
58 const videoImport = await getVideoImportOrDie(payload.videoImportId)
62 videoImportId: payload.videoImportId
65 torrentName: videoImport.torrentName ? getSecureTorrentName(videoImport.torrentName) : undefined,
66 magnetUri: videoImport.magnetUri
68 return processFile(() => downloadWebTorrentVideo(target, VIDEO_IMPORT_TIMEOUT), videoImport, options)
71 async function processYoutubeDLImport (job: Bull.Job, payload: VideoImportYoutubeDLPayload) {
72 logger.info('Processing youtubeDL video import in job %d.', job.id)
74 const videoImport = await getVideoImportOrDie(payload.videoImportId)
77 videoImportId: videoImport.id
80 const youtubeDL = new YoutubeDL(videoImport.targetUrl, ServerConfigManager.Instance.getEnabledResolutions('vod'))
83 () => youtubeDL.downloadYoutubeDLVideo(payload.fileExt, VIDEO_IMPORT_TIMEOUT),
89 async function getVideoImportOrDie (videoImportId: number) {
90 const videoImport = await VideoImportModel.loadAndPopulateVideo(videoImportId)
91 if (!videoImport || !videoImport.Video) {
92 throw new Error('Cannot import video %s: the video import or video linked to this import does not exist anymore.')
98 type ProcessFileOptions = {
99 type: VideoImportYoutubeDLPayloadType | VideoImportTorrentPayloadType
100 videoImportId: number
102 async function processFile (downloader: () => Promise<string>, videoImport: MVideoImportDefault, options: ProcessFileOptions) {
103 let tempVideoPath: string
104 let videoDestFile: 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 { videoFileResolution } = await getVideoFileResolution(tempVideoPath)
119 const fps = await getVideoFileFPS(tempVideoPath)
120 const duration = await getDurationFromVideoFile(tempVideoPath)
122 // Prepare video file object for creation in database
123 const fileExt = getLowercaseExtension(tempVideoPath)
124 const videoFileData = {
126 resolution: videoFileResolution,
128 filename: generateVideoFilename(videoImport.Video, false, videoFileResolution, fileExt),
130 videoId: videoImport.videoId
132 videoFile = new VideoFileModel(videoFileData)
134 const hookName = options.type === 'youtube-dl'
135 ? 'filter:api.video.post-import-url.accept.result'
136 : 'filter:api.video.post-import-torrent.accept.result'
138 // Check we accept this video
139 const acceptParameters = {
141 video: videoImport.Video,
142 videoFilePath: tempVideoPath,
144 user: videoImport.User
146 const acceptedResult = await Hooks.wrapFun(isPostImportVideoAccepted, acceptParameters, hookName)
148 if (acceptedResult.accepted !== true) {
149 logger.info('Refused imported video.', { acceptedResult, acceptParameters })
151 videoImport.state = VideoImportState.REJECTED
152 await videoImport.save()
154 throw new Error(acceptedResult.errorMessage)
157 // Video is accepted, resuming preparation
158 const videoWithFiles = Object.assign(videoImport.Video, { VideoFiles: [ videoFile ], VideoStreamingPlaylists: [] })
159 // To clean files if the import fails
160 const videoImportWithFiles: MVideoImportDefaultFiles = Object.assign(videoImport, { Video: videoWithFiles })
163 videoDestFile = getVideoFilePath(videoImportWithFiles.Video, videoFile)
164 await move(tempVideoPath, videoDestFile)
165 tempVideoPath = null // This path is not used anymore
167 // Generate miniature if the import did not created it
168 let thumbnailModel: MThumbnail
169 let thumbnailSave: object
170 if (!videoImportWithFiles.Video.getMiniature()) {
171 thumbnailModel = await generateVideoMiniature({
172 video: videoImportWithFiles.Video,
174 type: ThumbnailType.MINIATURE
176 thumbnailSave = thumbnailModel.toJSON()
179 // Generate preview if the import did not created it
180 let previewModel: MThumbnail
181 let previewSave: object
182 if (!videoImportWithFiles.Video.getPreview()) {
183 previewModel = await generateVideoMiniature({
184 video: videoImportWithFiles.Video,
186 type: ThumbnailType.PREVIEW
188 previewSave = previewModel.toJSON()
192 await createTorrentAndSetInfoHash(videoImportWithFiles.Video, videoFile)
194 const videoFileSave = videoFile.toJSON()
196 const { videoImportUpdated, video } = await retryTransactionWrapper(() => {
197 return sequelizeTypescript.transaction(async t => {
198 const videoImportToUpdate = videoImportWithFiles as MVideoImportVideo
201 const video = await VideoModel.load(videoImportToUpdate.videoId, t)
202 if (!video) throw new Error('Video linked to import ' + videoImportToUpdate.videoId + ' does not exist anymore.')
204 const videoFileCreated = await videoFile.save({ transaction: t })
206 // Update video DB object
207 video.duration = duration
208 video.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED
209 await video.save({ transaction: t })
211 if (thumbnailModel) await video.addAndSaveThumbnail(thumbnailModel, t)
212 if (previewModel) await video.addAndSaveThumbnail(previewModel, t)
214 // Now we can federate the video (reload from database, we need more attributes)
215 const videoForFederation = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.uuid, t)
216 await federateVideoIfNeeded(videoForFederation, true, t)
218 // Update video import object
219 videoImportToUpdate.state = VideoImportState.SUCCESS
220 const videoImportUpdated = await videoImportToUpdate.save({ transaction: t }) as MVideoImportVideo
221 videoImportUpdated.Video = video
223 videoImportToUpdate.Video = Object.assign(video, { VideoFiles: [ videoFileCreated ] })
225 logger.info('Video %s imported.', video.uuid)
227 return { videoImportUpdated, video: videoForFederation }
230 if (thumbnailModel) thumbnailModel = new ThumbnailModel(thumbnailSave)
231 if (previewModel) previewModel = new ThumbnailModel(previewSave)
233 videoFile = new VideoFileModel(videoFileSave)
239 Notifier.Instance.notifyOnFinishedVideoImport(videoImportUpdated, true)
241 if (video.isBlacklisted()) {
242 const videoBlacklist = Object.assign(video.VideoBlacklist, { Video: video })
244 Notifier.Instance.notifyOnVideoAutoBlacklist(videoBlacklist)
246 Notifier.Instance.notifyOnNewVideoIfNeeded(video)
249 // Create transcoding jobs?
250 if (video.state === VideoState.TO_TRANSCODE) {
251 await addOptimizeOrMergeAudioJob(videoImportUpdated.Video, videoFile, videoImport.User)
256 if (tempVideoPath) await remove(tempVideoPath)
257 } catch (errUnlink) {
258 logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink })
261 videoImport.error = err.message
262 if (videoImport.state !== VideoImportState.REJECTED) {
263 videoImport.state = VideoImportState.FAILED
265 await videoImport.save()
267 Notifier.Instance.notifyOnFinishedVideoImport(videoImport, false)