1 import { join } from 'path'
2 import { doRequestAndSaveToFile } from '@server/helpers/requests'
3 import { CONFIG } from '../../initializers/config'
4 import { FILES_CACHE } from '../../initializers/constants'
5 import { VideoModel } from '../../models/video/video'
6 import { VideoCaptionModel } from '../../models/video/video-caption'
7 import { AbstractVideoStaticFileCache } from './abstract-video-static-file-cache'
9 class VideosCaptionCache extends AbstractVideoStaticFileCache <string> {
11 private static instance: VideosCaptionCache
13 private constructor () {
17 static get Instance () {
18 return this.instance || (this.instance = new this())
21 async getFilePathImpl (filename: string) {
22 const videoCaption = await VideoCaptionModel.loadWithVideoByFilename(filename)
23 if (!videoCaption) return undefined
25 if (videoCaption.isOwned()) return { isOwned: true, path: join(CONFIG.STORAGE.CAPTIONS_DIR, videoCaption.filename) }
27 return this.loadRemoteFile(filename)
30 // Key is the caption filename
31 protected async loadRemoteFile (key: string) {
32 const videoCaption = await VideoCaptionModel.loadWithVideoByFilename(key)
33 if (!videoCaption) return undefined
35 if (videoCaption.isOwned()) throw new Error('Cannot load remote caption of owned video.')
37 // Used to fetch the path
38 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoCaption.videoId)
39 if (!video) return undefined
41 const remoteUrl = videoCaption.getFileUrl(video)
42 const destPath = join(FILES_CACHE.VIDEO_CAPTIONS.DIRECTORY, videoCaption.filename)
44 await doRequestAndSaveToFile(remoteUrl, destPath)
46 return { isOwned: false, path: destPath }