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, fetchRemoteVideoPreview } from '../../helpers'
7 import { VideoInstance } from '../../models'
9 class VideosPreviewCache {
11 private static instance: VideosPreviewCache
15 private constructor () { }
17 static get Instance () {
18 return this.instance || (this.instance = new this())
22 this.lru = new asyncLRU({
25 this.loadPreviews(key)
26 .then(res => cb(null, res))
27 .catch(err => cb(err))
31 this.lru.on('evict', (obj: { key: string, value: string }) => {
32 unlinkPromise(obj.value).then(() => logger.debug('%s evicted from VideosPreviewCache', obj.value))
36 getPreviewPath (key: string) {
37 return new Promise<string>((res, rej) => {
38 this.lru.get(key, (err, value) => {
39 err ? rej(err) : res(value)
44 private async loadPreviews (key: string) {
45 const video = await db.Video.loadByUUIDAndPopulateAccountAndServerAndTags(key)
46 if (!video) return undefined
48 if (video.isOwned()) return join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName())
50 const res = await this.saveRemotePreviewAndReturnPath(video)
55 private saveRemotePreviewAndReturnPath (video: VideoInstance) {
56 const req = fetchRemoteVideoPreview(video)
58 return new Promise<string>((res, rej) => {
59 const path = join(CACHE.DIRECTORIES.PREVIEWS, video.getPreviewName())
60 const stream = createWriteStream(path)
63 .on('finish', () => res(path))
64 .on('error', (err) => rej(err))