PeerTube/server/lib/files-cache/videos-caption-cache.ts

61 lines
2.1 KiB
TypeScript
Raw Normal View History

2018-07-12 19:02:00 +02:00
import { join } from 'path'
import { FILES_CACHE } from '../../initializers/constants'
2018-07-12 19:02:00 +02:00
import { VideoModel } from '../../models/video/video'
import { VideoCaptionModel } from '../../models/video/video-caption'
import { AbstractVideoStaticFileCache } from './abstract-video-static-file-cache'
2019-04-11 11:33:44 +02:00
import { CONFIG } from '../../initializers/config'
2019-04-23 09:50:57 +02:00
import { logger } from '../../helpers/logger'
import { doRequestAndSaveToFile } from '@server/helpers/requests'
2018-07-12 19:02:00 +02:00
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) {
2018-07-12 19:02:00 +02:00
const videoCaption = await VideoCaptionModel.loadByVideoIdAndLanguage(params.videoId, params.language)
if (!videoCaption) return undefined
2019-04-23 09:50:57 +02:00
if (videoCaption.isOwned()) return { isOwned: true, path: join(CONFIG.STORAGE.CAPTIONS_DIR, videoCaption.getCaptionName()) }
2018-07-12 19:02:00 +02:00
const key = params.videoId + VideosCaptionCache.KEY_DELIMITER + params.language
return this.loadRemoteFile(key)
2018-07-12 19:02:00 +02:00
}
protected async loadRemoteFile (key: string) {
2019-04-23 09:50:57 +02:00
logger.debug('Loading remote caption file %s.', key)
2018-07-12 19:02:00 +02:00
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)
2018-07-12 19:02:00 +02:00
if (!video) return undefined
const remoteUrl = videoCaption.getFileUrl(video)
2019-03-19 14:23:17 +01:00
const destPath = join(FILES_CACHE.VIDEO_CAPTIONS.DIRECTORY, videoCaption.getCaptionName())
2018-07-12 19:02:00 +02:00
await doRequestAndSaveToFile({ uri: remoteUrl }, destPath)
2019-04-23 09:50:57 +02:00
2019-04-24 09:28:06 +02:00
return { isOwned: false, path: destPath }
2018-07-12 19:02:00 +02:00
}
}
export {
VideosCaptionCache
}