1
0
Fork 0
peertube/server/lib/files-cache/videos-caption-cache.ts

60 lines
1.9 KiB
TypeScript
Raw Normal View History

2018-07-12 17:02:00 +00:00
import { join } from 'path'
2022-06-30 07:25:17 +00:00
import { logger } from '@server/helpers/logger'
2021-02-15 13:08:16 +00:00
import { doRequestAndSaveToFile } from '@server/helpers/requests'
import { CONFIG } from '../../initializers/config'
import { FILES_CACHE } from '../../initializers/constants'
2018-07-12 17:02:00 +00:00
import { VideoModel } from '../../models/video/video'
import { VideoCaptionModel } from '../../models/video/video-caption'
import { AbstractVideoStaticFileCache } from './abstract-video-static-file-cache'
2021-02-15 13:08:16 +00:00
class VideosCaptionCache extends AbstractVideoStaticFileCache <string> {
2018-07-12 17:02:00 +00:00
private static instance: VideosCaptionCache
private constructor () {
super()
}
static get Instance () {
return this.instance || (this.instance = new this())
}
2021-02-15 13:08:16 +00:00
async getFilePathImpl (filename: string) {
const videoCaption = await VideoCaptionModel.loadWithVideoByFilename(filename)
2018-07-12 17:02:00 +00:00
if (!videoCaption) return undefined
2021-02-15 13:08:16 +00:00
if (videoCaption.isOwned()) return { isOwned: true, path: join(CONFIG.STORAGE.CAPTIONS_DIR, videoCaption.filename) }
2018-07-12 17:02:00 +00:00
2021-02-15 13:08:16 +00:00
return this.loadRemoteFile(filename)
2018-07-12 17:02:00 +00:00
}
2021-02-15 13:08:16 +00:00
// Key is the caption filename
2018-07-12 17:02:00 +00:00
protected async loadRemoteFile (key: string) {
2021-02-15 13:08:16 +00:00
const videoCaption = await VideoCaptionModel.loadWithVideoByFilename(key)
2018-07-12 17:02:00 +00:00
if (!videoCaption) return undefined
if (videoCaption.isOwned()) throw new Error('Cannot load remote caption of owned video.')
// Used to fetch the path
2022-06-28 12:57:51 +00:00
const video = await VideoModel.loadFull(videoCaption.videoId)
2018-07-12 17:02:00 +00:00
if (!video) return undefined
const remoteUrl = videoCaption.getFileUrl(video)
2021-02-15 13:08:16 +00:00
const destPath = join(FILES_CACHE.VIDEO_CAPTIONS.DIRECTORY, videoCaption.filename)
2018-07-12 17:02:00 +00:00
2022-06-30 07:25:17 +00:00
try {
await doRequestAndSaveToFile(remoteUrl, destPath)
2019-04-23 07:50:57 +00:00
2022-06-30 07:25:17 +00:00
return { isOwned: false, path: destPath }
} catch (err) {
logger.info('Cannot fetch remote caption file %s.', remoteUrl, { err })
return undefined
}
2018-07-12 17:02:00 +00:00
}
}
export {
VideosCaptionCache
}