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'
8 import { MVideo, MVideoFile } from '@server/types/models'
10 class VideosTorrentCache extends AbstractVideoStaticFileCache <string> {
12 private static instance: VideosTorrentCache
14 private constructor () {
18 static get Instance () {
19 return this.instance || (this.instance = new this())
22 async getFilePathImpl (filename: string) {
23 const file = await VideoFileModel.loadWithVideoOrPlaylistByTorrentFilename(filename)
24 if (!file) return undefined
26 if (file.getVideo().isOwned()) {
27 const downloadName = this.buildDownloadName(file.getVideo(), file)
29 return { isOwned: true, path: join(CONFIG.STORAGE.TORRENTS_DIR, file.torrentFilename), downloadName }
32 return this.loadRemoteFile(filename)
35 // Key is the torrent filename
36 protected async loadRemoteFile (key: string) {
37 const file = await VideoFileModel.loadWithVideoOrPlaylistByTorrentFilename(key)
38 if (!file) return undefined
40 if (file.getVideo().isOwned()) throw new Error('Cannot load remote file of owned video.')
42 // Used to fetch the path
43 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(file.getVideo().id)
44 if (!video) return undefined
46 const remoteUrl = file.getRemoteTorrentUrl(video)
47 const destPath = join(FILES_CACHE.TORRENTS.DIRECTORY, file.torrentFilename)
49 await doRequestAndSaveToFile(remoteUrl, destPath)
51 const downloadName = this.buildDownloadName(video, file)
53 return { isOwned: false, path: destPath, downloadName }
56 private buildDownloadName (video: MVideo, file: MVideoFile) {
57 return `${video.name}-${file.resolution}p.torrent`