aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/lib/files-cache/videos-caption-cache.ts
blob: 440c3fde81c2de19c4c763ad0d217e659e4ca4f0 (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
import { join } from 'path'
import { FILES_CACHE } from '../../initializers/constants'
import { VideoModel } from '../../models/video/video'
import { VideoCaptionModel } from '../../models/video/video-caption'
import { AbstractVideoStaticFileCache } from './abstract-video-static-file-cache'
import { CONFIG } from '../../initializers/config'
import { logger } from '../../helpers/logger'
import { fetchRemoteVideoStaticFile } from '../activitypub'

type GetPathParam = { videoId: string, language: string }

class VideosCaptionCache extends AbstractVideoStaticFileCache <GetPathParam> {

  private static readonly KEY_DELIMITER = '%'
  private static instance: VideosCaptionCache

  private constructor () {
    super()
  }

  static get Instance () {
    return this.instance || (this.instance = new this())
  }

  async getFilePathImpl (params: GetPathParam) {
    const videoCaption = await VideoCaptionModel.loadByVideoIdAndLanguage(params.videoId, params.language)
    if (!videoCaption) return undefined

    if (videoCaption.isOwned()) return { isOwned: true, path: join(CONFIG.STORAGE.CAPTIONS_DIR, videoCaption.getCaptionName()) }

    const key = params.videoId + VideosCaptionCache.KEY_DELIMITER + params.language
    return this.loadRemoteFile(key)
  }

  protected async loadRemoteFile (key: string) {
    logger.debug('Loading remote caption file %s.', key)

    const [ videoId, language ] = key.split(VideosCaptionCache.KEY_DELIMITER)

    const videoCaption = await VideoCaptionModel.loadByVideoIdAndLanguage(videoId, language)
    if (!videoCaption) return undefined

    if (videoCaption.isOwned()) throw new Error('Cannot load remote caption of owned video.')

    // Used to fetch the path
    const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
    if (!video) return undefined

    // FIXME: use URL
    const remoteStaticPath = videoCaption.getCaptionStaticPath()
    const destPath = join(FILES_CACHE.VIDEO_CAPTIONS.DIRECTORY, videoCaption.getCaptionName())

    await fetchRemoteVideoStaticFile(video, remoteStaticPath, destPath)

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

export {
  VideosCaptionCache
}