1 import * as asyncLRU from 'async-lru'
2 import { join } from 'path'
3 import { createWriteStream } from 'fs'
5 import { database as db, CONFIG, CACHE } from '../../initializers'
6 import { logger, unlinkPromise } from '../../helpers'
7 import { VideoInstance } from '../../models'
8 import { fetchRemotePreview } from '../../lib'
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 getPreviewPath (key: string) {
38 return new Promise<string>((res, rej) => {
39 this.lru.get(key, (err, value) => {
40 err ? rej(err) : res(value)
45 private async loadPreviews (key: string) {
46 const video = await db.Video.loadByUUIDAndPopulateAccountAndPodAndTags(key)
47 if (!video) return undefined
49 if (video.isOwned()) return join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName())
51 const res = await this.saveRemotePreviewAndReturnPath(video)
56 private saveRemotePreviewAndReturnPath (video: VideoInstance) {
57 const req = fetchRemotePreview(video)
59 return new Promise<string>((res, rej) => {
60 const path = join(CACHE.DIRECTORIES.PREVIEWS, video.getPreviewName())
61 const stream = createWriteStream(path)
64 .on('finish', () => res(path))
65 .on('error', (err) => rej(err))