1 import * as asyncLRU from 'async-lru'
2 import { createWriteStream } from 'fs'
3 import { join } from 'path'
4 import { unlinkPromise } from '../../helpers/core-utils'
5 import { logger } from '../../helpers/logger'
6 import { CACHE, CONFIG } from '../../initializers'
7 import { VideoModel } from '../../models/video/video'
8 import { fetchRemoteVideoPreview } from '../activitypub'
10 class VideosPreviewCache {
12 private static instance: VideosPreviewCache
16 private constructor () { }
18 static get Instance () {
19 return this.instance || (this.instance = new this())
23 this.lru = new asyncLRU({
26 this.loadPreviews(key)
27 .then(res => cb(null, res))
28 .catch(err => cb(err))
32 this.lru.on('evict', (obj: { key: string, value: string }) => {
33 unlinkPromise(obj.value).then(() => logger.debug('%s evicted from VideosPreviewCache', obj.value))
37 async getPreviewPath (key: string) {
38 const video = await VideoModel.loadByUUID(key)
39 if (!video) return undefined
41 if (video.isOwned()) return join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName())
43 return new Promise<string>((res, rej) => {
44 this.lru.get(key, (err, value) => {
45 err ? rej(err) : res(value)
50 private async loadPreviews (key: string) {
51 const video = await VideoModel.loadByUUIDAndPopulateAccountAndServerAndTags(key)
52 if (!video) return undefined
54 if (video.isOwned()) throw new Error('Cannot load preview of owned video.')
56 return this.saveRemotePreviewAndReturnPath(video)
59 private saveRemotePreviewAndReturnPath (video: VideoModel) {
60 return new Promise<string>((res, rej) => {
61 const req = fetchRemoteVideoPreview(video, rej)
62 const path = join(CACHE.DIRECTORIES.PREVIEWS, video.getPreviewName())
63 const stream = createWriteStream(path)
66 .on('error', (err) => rej(err))
67 .on('finish', () => res(path))