aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/lib/files-cache/videos-torrent-cache.ts
blob: c8188b79fddcf622c88d4f978663523a8618e09c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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'
import { MVideo, MVideoFile } from '@server/types/models'

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

    if (file.getVideo().isOwned()) {
      const downloadName = this.buildDownloadName(file.getVideo(), file)

      return { isOwned: true, path: join(CONFIG.STORAGE.TORRENTS_DIR, file.torrentFilename), downloadName }
    }

    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.loadFull(file.getVideo().id)
    if (!video) return undefined

    const remoteUrl = file.getRemoteTorrentUrl(video)
    const destPath = join(FILES_CACHE.TORRENTS.DIRECTORY, file.torrentFilename)

    await doRequestAndSaveToFile(remoteUrl, destPath)

    const downloadName = this.buildDownloadName(video, file)

    return { isOwned: false, path: destPath, downloadName }
  }

  private buildDownloadName (video: MVideo, file: MVideoFile) {
    return `${video.name}-${file.resolution}p.torrent`
  }
}

export {
  VideosTorrentCache
}