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 { getVideoFilePath } from '@server/lib/video-paths'
6 import { UserModel } from '@server/models/account/user'
7 import { MVideoFile, MVideoWithFile } 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 await updateVideoFile(video, payload.filePath)
28 const user = await UserModel.loadByChannelActorId(video.VideoChannel.actorId)
29 await onNewWebTorrentFileResolution(video, user)
34 // ---------------------------------------------------------------------------
37 processVideoFileImport
40 // ---------------------------------------------------------------------------
42 async function updateVideoFile (video: MVideoWithFile, inputFilePath: string) {
43 const { videoFileResolution } = await getVideoFileResolution(inputFilePath)
44 const { size } = await stat(inputFilePath)
45 const fps = await getVideoFileFPS(inputFilePath)
47 let updatedVideoFile = new VideoFileModel({
48 resolution: videoFileResolution,
49 extname: extname(inputFilePath),
55 const currentVideoFile = video.VideoFiles.find(videoFile => videoFile.resolution === updatedVideoFile.resolution)
57 if (currentVideoFile) {
58 // Remove old file and old torrent
59 await video.removeFile(currentVideoFile)
60 await video.removeTorrent(currentVideoFile)
61 // Remove the old video file from the array
62 video.VideoFiles = video.VideoFiles.filter(f => f !== currentVideoFile)
64 // Update the database
65 currentVideoFile.extname = updatedVideoFile.extname
66 currentVideoFile.size = updatedVideoFile.size
67 currentVideoFile.fps = updatedVideoFile.fps
69 updatedVideoFile = currentVideoFile
72 const outputPath = getVideoFilePath(video, updatedVideoFile)
73 await copy(inputFilePath, outputPath)
75 await createTorrentAndSetInfoHash(video, updatedVideoFile)
77 await updatedVideoFile.save()
79 video.VideoFiles.push(updatedVideoFile)