1 import { Job } from 'bullmq'
2 import { createTorrentAndSetInfoHash, updateTorrentMetadata } from '@server/helpers/webtorrent'
3 import { VideoModel } from '@server/models/video/video'
4 import { VideoFileModel } from '@server/models/video/video-file'
5 import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist'
6 import { ManageVideoTorrentPayload } from '@shared/models'
7 import { logger } from '../../../helpers/logger'
9 async function processManageVideoTorrent (job: Job) {
10 const payload = job.data as ManageVideoTorrentPayload
11 logger.info('Processing torrent in job %s.', job.id)
13 if (payload.action === 'create') return doCreateAction(payload)
14 if (payload.action === 'update-metadata') return doUpdateMetadataAction(payload)
17 // ---------------------------------------------------------------------------
20 processManageVideoTorrent
23 // ---------------------------------------------------------------------------
25 async function doCreateAction (payload: ManageVideoTorrentPayload & { action: 'create' }) {
26 const [ video, file ] = await Promise.all([
27 loadVideoOrLog(payload.videoId),
28 loadFileOrLog(payload.videoFileId)
31 if (!video || !file) return
33 await createTorrentAndSetInfoHash(video, file)
35 // Refresh videoFile because the createTorrentAndSetInfoHash could be long
36 const refreshedFile = await VideoFileModel.loadWithVideo(file.id)
37 // File does not exist anymore, remove the generated torrent
38 if (!refreshedFile) return file.removeTorrent()
40 refreshedFile.infoHash = file.infoHash
41 refreshedFile.torrentFilename = file.torrentFilename
43 return refreshedFile.save()
46 async function doUpdateMetadataAction (payload: ManageVideoTorrentPayload & { action: 'update-metadata' }) {
47 const [ video, streamingPlaylist, file ] = await Promise.all([
48 loadVideoOrLog(payload.videoId),
49 loadStreamingPlaylistOrLog(payload.streamingPlaylistId),
50 loadFileOrLog(payload.videoFileId)
53 if ((!video && !streamingPlaylist) || !file) return
55 await updateTorrentMetadata(video || streamingPlaylist, file)
60 async function loadVideoOrLog (videoId: number) {
61 if (!videoId) return undefined
63 const video = await VideoModel.load(videoId)
65 logger.debug('Do not process torrent for video %d: does not exist anymore.', videoId)
71 async function loadStreamingPlaylistOrLog (streamingPlaylistId: number) {
72 if (!streamingPlaylistId) return undefined
74 const streamingPlaylist = await VideoStreamingPlaylistModel.loadWithVideo(streamingPlaylistId)
75 if (!streamingPlaylist) {
76 logger.debug('Do not process torrent for streaming playlist %d: does not exist anymore.', streamingPlaylistId)
79 return streamingPlaylist
82 async function loadFileOrLog (videoFileId: number) {
83 if (!videoFileId) return undefined
85 const file = await VideoFileModel.loadWithVideo(videoFileId)
88 logger.debug('Do not process torrent for file %d: does not exist anymore.', videoFileId)