]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/files-cache/videos-torrent-cache.ts
Fix email action button label for reports
[github/Chocobozzz/PeerTube.git] / server / lib / files-cache / videos-torrent-cache.ts
CommitLineData
90a8bd30
C
1import { join } from 'path'
2import { doRequestAndSaveToFile } from '@server/helpers/requests'
3import { VideoFileModel } from '@server/models/video/video-file'
4import { CONFIG } from '../../initializers/config'
5import { FILES_CACHE } from '../../initializers/constants'
6import { VideoModel } from '../../models/video/video'
7import { AbstractVideoStaticFileCache } from './abstract-video-static-file-cache'
4bc45da3 8import { MVideo, MVideoFile } from '@server/types/models'
90a8bd30
C
9
10class VideosTorrentCache extends AbstractVideoStaticFileCache <string> {
11
12 private static instance: VideosTorrentCache
13
14 private constructor () {
15 super()
16 }
17
18 static get Instance () {
19 return this.instance || (this.instance = new this())
20 }
21
22 async getFilePathImpl (filename: string) {
23 const file = await VideoFileModel.loadWithVideoOrPlaylistByTorrentFilename(filename)
24 if (!file) return undefined
25
4bc45da3
C
26 if (file.getVideo().isOwned()) {
27 const downloadName = this.buildDownloadName(file.getVideo(), file)
28
29 return { isOwned: true, path: join(CONFIG.STORAGE.TORRENTS_DIR, file.torrentFilename), downloadName }
30 }
90a8bd30
C
31
32 return this.loadRemoteFile(filename)
33 }
34
35 // Key is the torrent filename
36 protected async loadRemoteFile (key: string) {
37 const file = await VideoFileModel.loadWithVideoOrPlaylistByTorrentFilename(key)
38 if (!file) return undefined
39
40 if (file.getVideo().isOwned()) throw new Error('Cannot load remote file of owned video.')
41
42 // Used to fetch the path
43 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(file.getVideo().id)
44 if (!video) return undefined
45
46 const remoteUrl = file.getRemoteTorrentUrl(video)
47 const destPath = join(FILES_CACHE.TORRENTS.DIRECTORY, file.torrentFilename)
48
db4b15f2 49 await doRequestAndSaveToFile(remoteUrl, destPath)
90a8bd30 50
4bc45da3 51 const downloadName = this.buildDownloadName(video, file)
90a8bd30
C
52
53 return { isOwned: false, path: destPath, downloadName }
54 }
4bc45da3
C
55
56 private buildDownloadName (video: MVideo, file: MVideoFile) {
57 return `${video.name}-${file.resolution}p.torrent`
58 }
90a8bd30
C
59}
60
61export {
62 VideosTorrentCache
63}