1 import { join } from 'path'
2 import { logger } from '@server/helpers/logger'
3 import { doRequestAndSaveToFile } from '@server/helpers/requests'
4 import { CONFIG } from '../../initializers/config'
5 import { FILES_CACHE } from '../../initializers/constants'
6 import { VideoModel } from '../../models/video/video'
7 import { VideoCaptionModel } from '../../models/video/video-caption'
8 import { AbstractVideoStaticFileCache } from './abstract-video-static-file-cache'
10 class VideosCaptionCache extends AbstractVideoStaticFileCache <string> {
12 private static instance: VideosCaptionCache
14 private constructor () {
18 static get Instance () {
19 return this.instance || (this.instance = new this())
22 async getFilePathImpl (filename: string) {
23 const videoCaption = await VideoCaptionModel.loadWithVideoByFilename(filename)
24 if (!videoCaption) return undefined
26 if (videoCaption.isOwned()) return { isOwned: true, path: join(CONFIG.STORAGE.CAPTIONS_DIR, videoCaption.filename) }
28 return this.loadRemoteFile(filename)
31 // Key is the caption filename
32 protected async loadRemoteFile (key: string) {
33 const videoCaption = await VideoCaptionModel.loadWithVideoByFilename(key)
34 if (!videoCaption) return undefined
36 if (videoCaption.isOwned()) throw new Error('Cannot load remote caption of owned video.')
38 // Used to fetch the path
39 const video = await VideoModel.loadFull(videoCaption.videoId)
40 if (!video) return undefined
42 const remoteUrl = videoCaption.getFileUrl(video)
43 const destPath = join(FILES_CACHE.VIDEO_CAPTIONS.DIRECTORY, videoCaption.filename)
46 await doRequestAndSaveToFile(remoteUrl, destPath)
48 return { isOwned: false, path: destPath }
50 logger.info('Cannot fetch remote caption file %s.', remoteUrl, { err })