]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/files-cache/videos-preview-cache.ts
7bfeb57833e6304fa96cce89d4b80193c1a1ec92
[github/Chocobozzz/PeerTube.git] / server / lib / files-cache / videos-preview-cache.ts
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'
7
8 class VideosPreviewCache extends AbstractVideoStaticFileCache <string> {
9
10 private static instance: VideosPreviewCache
11
12 private constructor () {
13 super()
14 }
15
16 static get Instance () {
17 return this.instance || (this.instance = new this())
18 }
19
20 async getFilePathImpl (videoUUID: string) {
21 const video = await VideoModel.loadByUUID(videoUUID)
22 if (!video) return undefined
23
24 if (video.isOwned()) return { isOwned: true, path: video.getPreview().getPath() }
25
26 return this.loadRemoteFile(videoUUID)
27 }
28
29 protected async loadRemoteFile (key: string) {
30 const video = await VideoModel.loadAndPopulateAccountAndServerAndTags(key)
31 if (!video) return undefined
32
33 if (video.isOwned()) throw new Error('Cannot load remote preview of owned video.')
34
35 const preview = video.getPreview()
36 const destPath = join(FILES_CACHE.PREVIEWS.DIRECTORY, preview.filename)
37
38 const remoteUrl = preview.getFileUrl(video)
39 await doRequestAndSaveToFile({ uri: remoteUrl }, destPath)
40
41 return { isOwned: false, path: destPath }
42 }
43 }
44
45 export {
46 VideosPreviewCache
47 }