1 import { join } from 'path'
2 import { doRequestAndSaveToFile } from '@server/helpers/requests'
3 import { VideoFileModel } from '@server/models/video/video-file'
4 import { CONFIG } from '../../initializers/config'
5 import { FILES_CACHE } from '../../initializers/constants'
6 import { VideoModel } from '../../models/video/video'
7 import { AbstractVideoStaticFileCache } from './abstract-video-static-file-cache'
9 class VideosTorrentCache extends AbstractVideoStaticFileCache <string> {
11 private static instance: VideosTorrentCache
13 private constructor () {
17 static get Instance () {
18 return this.instance || (this.instance = new this())
21 async getFilePathImpl (filename: string) {
22 const file = await VideoFileModel.loadWithVideoOrPlaylistByTorrentFilename(filename)
23 if (!file) return undefined
25 if (file.getVideo().isOwned()) return { isOwned: true, path: join(CONFIG.STORAGE.TORRENTS_DIR, file.torrentFilename) }
27 return this.loadRemoteFile(filename)
30 // Key is the torrent filename
31 protected async loadRemoteFile (key: string) {
32 const file = await VideoFileModel.loadWithVideoOrPlaylistByTorrentFilename(key)
33 if (!file) return undefined
35 if (file.getVideo().isOwned()) throw new Error('Cannot load remote file of owned video.')
37 // Used to fetch the path
38 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(file.getVideo().id)
39 if (!video) return undefined
41 const remoteUrl = file.getRemoteTorrentUrl(video)
42 const destPath = join(FILES_CACHE.TORRENTS.DIRECTORY, file.torrentFilename)
44 await doRequestAndSaveToFile(remoteUrl, destPath)
46 const downloadName = `${video.name}-${file.resolution}p.torrent`
48 return { isOwned: false, path: destPath, downloadName }