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