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 { 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 videoFileData = {
120 extname: extname(tempVideoPath),
121 resolution: videoFileResolution,
124 videoId: videoImport.videoId
126 videoFile = new VideoFileModel(videoFileData)
128 const hookName = options.type === 'youtube-dl'
129 ? 'filter:api.video.post-import-url.accept.result'
130 : 'filter:api.video.post-import-torrent.accept.result'
132 // Check we accept this video
133 const acceptParameters = {
135 video: videoImport.Video,
136 videoFilePath: tempVideoPath,
138 user: videoImport.User
140 const acceptedResult = await Hooks.wrapFun(isPostImportVideoAccepted, acceptParameters, hookName)
142 if (acceptedResult.accepted !== true) {
143 logger.info('Refused imported video.', { acceptedResult, acceptParameters })
145 videoImport.state = VideoImportState.REJECTED
146 await videoImport.save()
148 throw new Error(acceptedResult.errorMessage)
151 // Video is accepted, resuming preparation
152 const videoWithFiles = Object.assign(videoImport.Video, { VideoFiles: [ videoFile ], VideoStreamingPlaylists: [] })
153 // To clean files if the import fails
154 const videoImportWithFiles: MVideoImportDefaultFiles = Object.assign(videoImport, { Video: videoWithFiles })
157 videoDestFile = getVideoFilePath(videoImportWithFiles.Video, videoFile)
158 await move(tempVideoPath, videoDestFile)
159 tempVideoPath = null // This path is not used anymore
161 // Generate miniature if the import did not created it
162 let thumbnailModel: MThumbnail
163 let thumbnailSave: object
164 if (!videoImportWithFiles.Video.getMiniature()) {
165 thumbnailModel = await generateVideoMiniature({
166 video: videoImportWithFiles.Video,
168 type: ThumbnailType.MINIATURE
170 thumbnailSave = thumbnailModel.toJSON()
173 // Generate preview if the import did not created it
174 let previewModel: MThumbnail
175 let previewSave: object
176 if (!videoImportWithFiles.Video.getPreview()) {
177 previewModel = await generateVideoMiniature({
178 video: videoImportWithFiles.Video,
180 type: ThumbnailType.PREVIEW
182 previewSave = previewModel.toJSON()
186 await createTorrentAndSetInfoHash(videoImportWithFiles.Video, videoFile)
188 const videoFileSave = videoFile.toJSON()
190 const { videoImportUpdated, video } = await retryTransactionWrapper(() => {
191 return sequelizeTypescript.transaction(async t => {
192 const videoImportToUpdate = videoImportWithFiles as MVideoImportVideo
195 const video = await VideoModel.load(videoImportToUpdate.videoId, t)
196 if (!video) throw new Error('Video linked to import ' + videoImportToUpdate.videoId + ' does not exist anymore.')
198 const videoFileCreated = await videoFile.save({ transaction: t })
200 // Update video DB object
201 video.duration = duration
202 video.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED
203 await video.save({ transaction: t })
205 if (thumbnailModel) await video.addAndSaveThumbnail(thumbnailModel, t)
206 if (previewModel) await video.addAndSaveThumbnail(previewModel, t)
208 // Now we can federate the video (reload from database, we need more attributes)
209 const videoForFederation = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.uuid, t)
210 await federateVideoIfNeeded(videoForFederation, true, t)
212 // Update video import object
213 videoImportToUpdate.state = VideoImportState.SUCCESS
214 const videoImportUpdated = await videoImportToUpdate.save({ transaction: t }) as MVideoImportVideo
215 videoImportUpdated.Video = video
217 videoImportToUpdate.Video = Object.assign(video, { VideoFiles: [ videoFileCreated ] })
219 logger.info('Video %s imported.', video.uuid)
221 return { videoImportUpdated, video: videoForFederation }
224 if (thumbnailModel) thumbnailModel = new ThumbnailModel(thumbnailSave)
225 if (previewModel) previewModel = new ThumbnailModel(previewSave)
227 videoFile = new VideoFileModel(videoFileSave)
233 Notifier.Instance.notifyOnFinishedVideoImport(videoImportUpdated, true)
235 if (video.isBlacklisted()) {
236 const videoBlacklist = Object.assign(video.VideoBlacklist, { Video: video })
238 Notifier.Instance.notifyOnVideoAutoBlacklist(videoBlacklist)
240 Notifier.Instance.notifyOnNewVideoIfNeeded(video)
243 // Create transcoding jobs?
244 if (video.state === VideoState.TO_TRANSCODE) {
245 await addOptimizeOrMergeAudioJob(videoImportUpdated.Video, videoFile, videoImport.User)
250 if (tempVideoPath) await remove(tempVideoPath)
251 } catch (errUnlink) {
252 logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink })
255 videoImport.error = err.message
256 if (videoImport.state !== VideoImportState.REJECTED) {
257 videoImport.state = VideoImportState.FAILED
259 await videoImport.save()
261 Notifier.Instance.notifyOnFinishedVideoImport(videoImport, false)