1 import { join } from 'path'
2 import { FILES_CACHE } from '../../initializers/constants'
3 import { VideoModel } from '../../models/video/video'
4 import { VideoCaptionModel } from '../../models/video/video-caption'
5 import { AbstractVideoStaticFileCache } from './abstract-video-static-file-cache'
6 import { CONFIG } from '../../initializers/config'
7 import { logger } from '../../helpers/logger'
9 type GetPathParam = { videoId: string, language: string }
11 class VideosCaptionCache extends AbstractVideoStaticFileCache <GetPathParam> {
13 private static readonly KEY_DELIMITER = '%'
14 private static instance: VideosCaptionCache
16 private constructor () {
20 static get Instance () {
21 return this.instance || (this.instance = new this())
24 async getFilePathImpl (params: GetPathParam) {
25 const videoCaption = await VideoCaptionModel.loadByVideoIdAndLanguage(params.videoId, params.language)
26 if (!videoCaption) return undefined
28 if (videoCaption.isOwned()) return { isOwned: true, path: join(CONFIG.STORAGE.CAPTIONS_DIR, videoCaption.getCaptionName()) }
30 const key = params.videoId + VideosCaptionCache.KEY_DELIMITER + params.language
31 return this.loadRemoteFile(key)
34 protected async loadRemoteFile (key: string) {
35 logger.debug('Loading remote caption file %s.', key)
37 const [ videoId, language ] = key.split(VideosCaptionCache.KEY_DELIMITER)
39 const videoCaption = await VideoCaptionModel.loadByVideoIdAndLanguage(videoId, language)
40 if (!videoCaption) return undefined
42 if (videoCaption.isOwned()) throw new Error('Cannot load remote caption of owned video.')
44 // Used to fetch the path
45 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
46 if (!video) return undefined
49 const remoteStaticPath = videoCaption.getCaptionStaticPath()
50 const destPath = join(FILES_CACHE.VIDEO_CAPTIONS.DIRECTORY, videoCaption.getCaptionName())
52 const path = await this.saveRemoteVideoFileAndReturnPath(video, remoteStaticPath, destPath)
54 return { isOwned: false, path }