]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/files-cache/videos-torrent-cache.ts
Merge branch 'release/3.1.0' into develop
[github/Chocobozzz/PeerTube.git] / server / lib / files-cache / videos-torrent-cache.ts
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'
9
10 class 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
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 }
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
49 await doRequestAndSaveToFile(remoteUrl, destPath)
50
51 const downloadName = this.buildDownloadName(video, file)
52
53 return { isOwned: false, path: destPath, downloadName }
54 }
55
56 private buildDownloadName (video: MVideo, file: MVideoFile) {
57 return `${video.name}-${file.resolution}p.torrent`
58 }
59 }
60
61 export {
62 VideosTorrentCache
63 }