1 import * as Bull from 'bull'
2 import { copy, stat } from 'fs-extra'
3 import { extname } from 'path'
4 import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
5 import { generateVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
6 import { UserModel } from '@server/models/user/user'
7 import { MVideoFullLight } from '@server/types/models'
8 import { VideoFileImportPayload } from '@shared/models'
9 import { getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils'
10 import { logger } from '../../../helpers/logger'
11 import { VideoModel } from '../../../models/video/video'
12 import { VideoFileModel } from '../../../models/video/video-file'
13 import { onNewWebTorrentFileResolution } from './video-transcoding'
15 async function processVideoFileImport (job: Bull.Job) {
16 const payload = job.data as VideoFileImportPayload
17 logger.info('Processing video file import in job %d.', job.id)
19 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(payload.videoUUID)
20 // No video, maybe deleted?
22 logger.info('Do not process job %d, video does not exist.', job.id)
26 const data = await getVideoFileResolution(payload.filePath)
28 await updateVideoFile(video, payload.filePath)
30 const user = await UserModel.loadByChannelActorId(video.VideoChannel.actorId)
32 const newResolutionPayload = {
33 type: 'new-resolution-to-webtorrent' as 'new-resolution-to-webtorrent',
34 videoUUID: video.uuid,
35 resolution: data.videoFileResolution,
36 isPortraitMode: data.isPortraitMode,
40 await onNewWebTorrentFileResolution(video, user, newResolutionPayload)
45 // ---------------------------------------------------------------------------
48 processVideoFileImport
51 // ---------------------------------------------------------------------------
53 async function updateVideoFile (video: MVideoFullLight, inputFilePath: string) {
54 const { videoFileResolution } = await getVideoFileResolution(inputFilePath)
55 const { size } = await stat(inputFilePath)
56 const fps = await getVideoFileFPS(inputFilePath)
58 const fileExt = extname(inputFilePath)
60 const currentVideoFile = video.VideoFiles.find(videoFile => videoFile.resolution === videoFileResolution)
62 if (currentVideoFile) {
63 // Remove old file and old torrent
64 await video.removeFile(currentVideoFile)
65 await currentVideoFile.removeTorrent()
66 // Remove the old video file from the array
67 video.VideoFiles = video.VideoFiles.filter(f => f !== currentVideoFile)
69 await currentVideoFile.destroy()
72 const newVideoFile = new VideoFileModel({
73 resolution: videoFileResolution,
75 filename: generateVideoFilename(video, false, videoFileResolution, fileExt),
81 const outputPath = getVideoFilePath(video, newVideoFile)
82 await copy(inputFilePath, outputPath)
84 video.VideoFiles.push(newVideoFile)
85 await createTorrentAndSetInfoHash(video, newVideoFile)
87 await newVideoFile.save()