1 import { Job } from 'bullmq'
2 import { copy, stat } from 'fs-extra'
3 import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
4 import { CONFIG } from '@server/initializers/config'
5 import { federateVideoIfNeeded } from '@server/lib/activitypub/videos'
6 import { generateWebTorrentVideoFilename } from '@server/lib/paths'
7 import { buildMoveToObjectStorageJob } from '@server/lib/video'
8 import { VideoPathManager } from '@server/lib/video-path-manager'
9 import { VideoModel } from '@server/models/video/video'
10 import { VideoFileModel } from '@server/models/video/video-file'
11 import { MVideoFullLight } from '@server/types/models'
12 import { getLowercaseExtension } from '@shared/core-utils'
13 import { VideoFileImportPayload, VideoStorage } from '@shared/models'
14 import { getVideoStreamFPS, getVideoStreamDimensionsInfo } from '../../../helpers/ffmpeg'
15 import { logger } from '../../../helpers/logger'
16 import { JobQueue } from '../job-queue'
18 async function processVideoFileImport (job: Job) {
19 const payload = job.data as VideoFileImportPayload
20 logger.info('Processing video file import in job %s.', job.id)
22 const video = await VideoModel.loadFull(payload.videoUUID)
23 // No video, maybe deleted?
25 logger.info('Do not process job %d, video does not exist.', job.id)
29 await updateVideoFile(video, payload.filePath)
31 if (CONFIG.OBJECT_STORAGE.ENABLED) {
32 await JobQueue.Instance.createJob(await buildMoveToObjectStorageJob({ video, previousVideoState: video.state }))
34 await federateVideoIfNeeded(video, false)
40 // ---------------------------------------------------------------------------
43 processVideoFileImport
46 // ---------------------------------------------------------------------------
48 async function updateVideoFile (video: MVideoFullLight, inputFilePath: string) {
49 const { resolution } = await getVideoStreamDimensionsInfo(inputFilePath)
50 const { size } = await stat(inputFilePath)
51 const fps = await getVideoStreamFPS(inputFilePath)
53 const fileExt = getLowercaseExtension(inputFilePath)
55 const currentVideoFile = video.VideoFiles.find(videoFile => videoFile.resolution === resolution)
57 if (currentVideoFile) {
58 // Remove old file and old torrent
59 await video.removeWebTorrentFile(currentVideoFile)
60 // Remove the old video file from the array
61 video.VideoFiles = video.VideoFiles.filter(f => f !== currentVideoFile)
63 await currentVideoFile.destroy()
66 const newVideoFile = new VideoFileModel({
69 filename: generateWebTorrentVideoFilename(resolution, fileExt),
70 storage: VideoStorage.FILE_SYSTEM,
76 const outputPath = VideoPathManager.Instance.getFSVideoFileOutputPath(video, newVideoFile)
77 await copy(inputFilePath, outputPath)
79 video.VideoFiles.push(newVideoFile)
80 await createTorrentAndSetInfoHash(video, newVideoFile)
82 await newVideoFile.save()