1 import { Job } from 'bull'
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 { addMoveToObjectStorageJob } 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'
17 async function processVideoFileImport (job: Job) {
18 const payload = job.data as VideoFileImportPayload
19 logger.info('Processing video file import in job %d.', job.id)
21 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(payload.videoUUID)
22 // No video, maybe deleted?
24 logger.info('Do not process job %d, video does not exist.', job.id)
28 await updateVideoFile(video, payload.filePath)
30 if (CONFIG.OBJECT_STORAGE.ENABLED) {
31 await addMoveToObjectStorageJob({ video, previousVideoState: video.state })
33 await federateVideoIfNeeded(video, false)
39 // ---------------------------------------------------------------------------
42 processVideoFileImport
45 // ---------------------------------------------------------------------------
47 async function updateVideoFile (video: MVideoFullLight, inputFilePath: string) {
48 const { resolution } = await getVideoStreamDimensionsInfo(inputFilePath)
49 const { size } = await stat(inputFilePath)
50 const fps = await getVideoStreamFPS(inputFilePath)
52 const fileExt = getLowercaseExtension(inputFilePath)
54 const currentVideoFile = video.VideoFiles.find(videoFile => videoFile.resolution === resolution)
56 if (currentVideoFile) {
57 // Remove old file and old torrent
58 await video.removeWebTorrentFileAndTorrent(currentVideoFile)
59 // Remove the old video file from the array
60 video.VideoFiles = video.VideoFiles.filter(f => f !== currentVideoFile)
62 await currentVideoFile.destroy()
65 const newVideoFile = new VideoFileModel({
68 filename: generateWebTorrentVideoFilename(resolution, fileExt),
69 storage: VideoStorage.FILE_SYSTEM,
75 const outputPath = VideoPathManager.Instance.getFSVideoFileOutputPath(video, newVideoFile)
76 await copy(inputFilePath, outputPath)
78 video.VideoFiles.push(newVideoFile)
79 await createTorrentAndSetInfoHash(video, newVideoFile)
81 await newVideoFile.save()