1 import { join } from 'path'
2 import { logger } from '@server/helpers/logger'
3 import { doRequestAndSaveToFile } from '@server/helpers/requests'
4 import { VideoFileModel } from '@server/models/video/video-file'
5 import { MVideo, MVideoFile } from '@server/types/models'
6 import { CONFIG } from '../../initializers/config'
7 import { FILES_CACHE } from '../../initializers/constants'
8 import { VideoModel } from '../../models/video/video'
9 import { AbstractVideoStaticFileCache } from './abstract-video-static-file-cache'
11 class VideosTorrentCache extends AbstractVideoStaticFileCache <string> {
13 private static instance: VideosTorrentCache
15 private constructor () {
19 static get Instance () {
20 return this.instance || (this.instance = new this())
23 async getFilePathImpl (filename: string) {
24 const file = await VideoFileModel.loadWithVideoOrPlaylistByTorrentFilename(filename)
25 if (!file) return undefined
27 if (file.getVideo().isOwned()) {
28 const downloadName = this.buildDownloadName(file.getVideo(), file)
30 return { isOwned: true, path: join(CONFIG.STORAGE.TORRENTS_DIR, file.torrentFilename), downloadName }
33 return this.loadRemoteFile(filename)
36 // Key is the torrent filename
37 protected async loadRemoteFile (key: string) {
38 const file = await VideoFileModel.loadWithVideoOrPlaylistByTorrentFilename(key)
39 if (!file) return undefined
41 if (file.getVideo().isOwned()) throw new Error('Cannot load remote file of owned video.')
43 // Used to fetch the path
44 const video = await VideoModel.loadFull(file.getVideo().id)
45 if (!video) return undefined
47 const remoteUrl = file.getRemoteTorrentUrl(video)
48 const destPath = join(FILES_CACHE.TORRENTS.DIRECTORY, file.torrentFilename)
51 await doRequestAndSaveToFile(remoteUrl, destPath)
53 const downloadName = this.buildDownloadName(video, file)
55 return { isOwned: false, path: destPath, downloadName }
57 logger.info('Cannot fetch remote torrent file %s.', remoteUrl, { err })
63 private buildDownloadName (video: MVideo, file: MVideoFile) {
64 return `${video.name}-${file.resolution}p.torrent`