1 import { join } from 'path'
2 import { FILES_CACHE } from '../../initializers/constants'
3 import { VideoModel } from '../../models/video/video'
4 import { AbstractVideoStaticFileCache } from './abstract-video-static-file-cache'
5 import { doRequestAndSaveToFile } from '@server/helpers/requests'
7 class VideosPreviewCache extends AbstractVideoStaticFileCache <string> {
9 private static instance: VideosPreviewCache
11 private constructor () {
15 static get Instance () {
16 return this.instance || (this.instance = new this())
19 async getFilePathImpl (videoUUID: string) {
20 const video = await VideoModel.loadByUUID(videoUUID)
21 if (!video) return undefined
23 if (video.isOwned()) return { isOwned: true, path: video.getPreview().getPath() }
25 return this.loadRemoteFile(videoUUID)
28 protected async loadRemoteFile (key: string) {
29 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(key)
30 if (!video) return undefined
32 if (video.isOwned()) throw new Error('Cannot load remote preview of owned video.')
34 const preview = video.getPreview()
35 const destPath = join(FILES_CACHE.PREVIEWS.DIRECTORY, preview.filename)
37 const remoteUrl = preview.getFileUrl(video)
38 await doRequestAndSaveToFile({ uri: remoteUrl }, destPath)
40 return { isOwned: false, path: destPath }