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'
8 import { doRequestAndSaveToFile } from '@server/helpers/requests'
10 type GetPathParam = { videoId: string, language: string }
12 class VideosCaptionCache extends AbstractVideoStaticFileCache <GetPathParam> {
14 private static readonly KEY_DELIMITER = '%'
15 private static instance: VideosCaptionCache
17 private constructor () {
21 static get Instance () {
22 return this.instance || (this.instance = new this())
25 async getFilePathImpl (params: GetPathParam) {
26 const videoCaption = await VideoCaptionModel.loadByVideoIdAndLanguage(params.videoId, params.language)
27 if (!videoCaption) return undefined
29 if (videoCaption.isOwned()) return { isOwned: true, path: join(CONFIG.STORAGE.CAPTIONS_DIR, videoCaption.getCaptionName()) }
31 const key = params.videoId + VideosCaptionCache.KEY_DELIMITER + params.language
32 return this.loadRemoteFile(key)
35 protected async loadRemoteFile (key: string) {
36 logger.debug('Loading remote caption file %s.', key)
38 const [ videoId, language ] = key.split(VideosCaptionCache.KEY_DELIMITER)
40 const videoCaption = await VideoCaptionModel.loadByVideoIdAndLanguage(videoId, language)
41 if (!videoCaption) return undefined
43 if (videoCaption.isOwned()) throw new Error('Cannot load remote caption of owned video.')
45 // Used to fetch the path
46 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
47 if (!video) return undefined
49 const remoteUrl = videoCaption.getFileUrl(video)
50 const destPath = join(FILES_CACHE.VIDEO_CAPTIONS.DIRECTORY, videoCaption.getCaptionName())
52 await doRequestAndSaveToFile({ uri: remoteUrl }, destPath)
54 return { isOwned: false, path: destPath }