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

61 lines
1.8 KiB
TypeScript
Raw Normal View History

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