2021-02-16 09:25:53 -06:00
|
|
|
import { join } from 'path'
|
|
|
|
import { doRequestAndSaveToFile } from '@server/helpers/requests'
|
|
|
|
import { VideoFileModel } from '@server/models/video/video-file'
|
|
|
|
import { CONFIG } from '../../initializers/config'
|
|
|
|
import { FILES_CACHE } from '../../initializers/constants'
|
|
|
|
import { VideoModel } from '../../models/video/video'
|
|
|
|
import { AbstractVideoStaticFileCache } from './abstract-video-static-file-cache'
|
2021-03-23 05:54:08 -05:00
|
|
|
import { MVideo, MVideoFile } from '@server/types/models'
|
2021-02-16 09:25:53 -06:00
|
|
|
|
|
|
|
class VideosTorrentCache extends AbstractVideoStaticFileCache <string> {
|
|
|
|
|
|
|
|
private static instance: VideosTorrentCache
|
|
|
|
|
|
|
|
private constructor () {
|
|
|
|
super()
|
|
|
|
}
|
|
|
|
|
|
|
|
static get Instance () {
|
|
|
|
return this.instance || (this.instance = new this())
|
|
|
|
}
|
|
|
|
|
|
|
|
async getFilePathImpl (filename: string) {
|
|
|
|
const file = await VideoFileModel.loadWithVideoOrPlaylistByTorrentFilename(filename)
|
|
|
|
if (!file) return undefined
|
|
|
|
|
2021-03-23 05:54:08 -05:00
|
|
|
if (file.getVideo().isOwned()) {
|
|
|
|
const downloadName = this.buildDownloadName(file.getVideo(), file)
|
|
|
|
|
|
|
|
return { isOwned: true, path: join(CONFIG.STORAGE.TORRENTS_DIR, file.torrentFilename), downloadName }
|
|
|
|
}
|
2021-02-16 09:25:53 -06:00
|
|
|
|
|
|
|
return this.loadRemoteFile(filename)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Key is the torrent filename
|
|
|
|
protected async loadRemoteFile (key: string) {
|
|
|
|
const file = await VideoFileModel.loadWithVideoOrPlaylistByTorrentFilename(key)
|
|
|
|
if (!file) return undefined
|
|
|
|
|
|
|
|
if (file.getVideo().isOwned()) throw new Error('Cannot load remote file of owned video.')
|
|
|
|
|
|
|
|
// Used to fetch the path
|
|
|
|
const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(file.getVideo().id)
|
|
|
|
if (!video) return undefined
|
|
|
|
|
|
|
|
const remoteUrl = file.getRemoteTorrentUrl(video)
|
|
|
|
const destPath = join(FILES_CACHE.TORRENTS.DIRECTORY, file.torrentFilename)
|
|
|
|
|
2021-03-08 07:24:11 -06:00
|
|
|
await doRequestAndSaveToFile(remoteUrl, destPath)
|
2021-02-16 09:25:53 -06:00
|
|
|
|
2021-03-23 05:54:08 -05:00
|
|
|
const downloadName = this.buildDownloadName(video, file)
|
2021-02-16 09:25:53 -06:00
|
|
|
|
|
|
|
return { isOwned: false, path: destPath, downloadName }
|
|
|
|
}
|
2021-03-23 05:54:08 -05:00
|
|
|
|
|
|
|
private buildDownloadName (video: MVideo, file: MVideoFile) {
|
|
|
|
return `${video.name}-${file.resolution}p.torrent`
|
|
|
|
}
|
2021-02-16 09:25:53 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
export {
|
|
|
|
VideosTorrentCache
|
|
|
|
}
|