PeerTube/server/core/lib/files-cache/video-captions-simple-file-...

61 lines
1.8 KiB
TypeScript
Raw Normal View History

2018-07-12 12:02:00 -05:00
import { join } from 'path'
import { logger } from '@server/helpers/logger.js'
import { doRequestAndSaveToFile } from '@server/helpers/requests.js'
import { FILES_CACHE } from '../../initializers/constants.js'
import { VideoModel } from '../../models/video/video.js'
import { VideoCaptionModel } from '../../models/video/video-caption.js'
import { AbstractSimpleFileCache } from './shared/abstract-simple-file-cache.js'
2018-07-12 12:02:00 -05:00
2023-06-06 08:59:51 -05:00
class VideoCaptionsSimpleFileCache extends AbstractSimpleFileCache <string> {
2018-07-12 12:02:00 -05:00
2023-06-06 08:59:51 -05:00
private static instance: VideoCaptionsSimpleFileCache
2018-07-12 12:02:00 -05:00
private constructor () {
super()
}
static get Instance () {
return this.instance || (this.instance = new this())
}
2021-02-15 07:08:16 -06:00
async getFilePathImpl (filename: string) {
const videoCaption = await VideoCaptionModel.loadWithVideoByFilename(filename)
2018-07-12 12:02:00 -05:00
if (!videoCaption) return undefined
2023-06-06 08:59:51 -05:00
if (videoCaption.isOwned()) {
2024-02-12 03:47:52 -06:00
return { isOwned: true, path: videoCaption.getFSPath() }
2023-06-06 08:59:51 -05:00
}
2018-07-12 12:02:00 -05:00
2021-02-15 07:08:16 -06:00
return this.loadRemoteFile(filename)
2018-07-12 12:02:00 -05:00
}
2021-02-15 07:08:16 -06:00
// Key is the caption filename
2018-07-12 12:02:00 -05:00
protected async loadRemoteFile (key: string) {
2021-02-15 07:08:16 -06:00
const videoCaption = await VideoCaptionModel.loadWithVideoByFilename(key)
2018-07-12 12:02:00 -05: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 07:57:51 -05:00
const video = await VideoModel.loadFull(videoCaption.videoId)
2018-07-12 12:02:00 -05:00
if (!video) return undefined
const remoteUrl = videoCaption.getFileUrl(video)
2021-02-15 07:08:16 -06:00
const destPath = join(FILES_CACHE.VIDEO_CAPTIONS.DIRECTORY, videoCaption.filename)
2018-07-12 12:02:00 -05:00
2022-06-30 02:25:17 -05:00
try {
await doRequestAndSaveToFile(remoteUrl, destPath)
2019-04-23 02:50:57 -05:00
2022-06-30 02:25:17 -05:00
return { isOwned: false, path: destPath }
} catch (err) {
logger.info('Cannot fetch remote caption file %s.', remoteUrl, { err })
return undefined
}
2018-07-12 12:02:00 -05:00
}
}
export {
2023-06-06 08:59:51 -05:00
VideoCaptionsSimpleFileCache
2018-07-12 12:02:00 -05:00
}