1 import { join } from 'path'
2 import { FILES_CACHE, STATIC_PATHS } 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'
6 import { buildRemoteVideoBaseUrl } from '@server/helpers/activitypub'
8 class VideosPreviewCache extends AbstractVideoStaticFileCache <string> {
10 private static instance: VideosPreviewCache
12 private constructor () {
16 static get Instance () {
17 return this.instance || (this.instance = new this())
20 async getFilePathImpl (videoUUID: string) {
21 const video = await VideoModel.loadByUUID(videoUUID)
22 if (!video) return undefined
24 if (video.isOwned()) return { isOwned: true, path: video.getPreview().getPath() }
26 return this.loadRemoteFile(videoUUID)
29 protected async loadRemoteFile (key: string) {
30 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(key)
31 if (!video) return undefined
33 if (video.isOwned()) throw new Error('Cannot load remote preview of owned video.')
35 const preview = video.getPreview()
36 const destPath = join(FILES_CACHE.PREVIEWS.DIRECTORY, preview.filename)
38 const remoteUrl = preview.getFileUrl(video)
39 await doRequestAndSaveToFile({ uri: remoteUrl }, destPath)
41 return { isOwned: false, path: destPath }