1 import * as AsyncLRU from 'async-lru'
2 import { createWriteStream } from 'fs'
3 import { unlinkPromise } from '../../helpers/core-utils'
4 import { logger } from '../../helpers/logger'
5 import { VideoModel } from '../../models/video/video'
6 import { fetchRemoteVideoStaticFile } from '../activitypub'
8 export abstract class AbstractVideoStaticFileCache <T> {
12 abstract getFilePath (params: T): Promise<string>
14 // Load and save the remote file, then return the local path from filesystem
15 protected abstract loadRemoteFile (key: string): Promise<string>
17 init (max: number, maxAge: number) {
18 this.lru = new AsyncLRU({
22 this.loadRemoteFile(key)
23 .then(res => cb(null, res))
24 .catch(err => cb(err))
28 this.lru.on('evict', (obj: { key: string, value: string }) => {
29 unlinkPromise(obj.value)
30 .then(() => logger.debug('%s evicted from %s', obj.value, this.constructor.name))
34 protected loadFromLRU (key: string) {
35 return new Promise<string>((res, rej) => {
36 this.lru.get(key, (err, value) => {
37 err ? rej(err) : res(value)
42 protected saveRemoteVideoFileAndReturnPath (video: VideoModel, remoteStaticPath: string, destPath: string) {
43 return new Promise<string>((res, rej) => {
44 const req = fetchRemoteVideoStaticFile(video, remoteStaticPath, rej)
46 const stream = createWriteStream(destPath)
49 .on('error', (err) => rej(err))
50 .on('finish', () => res(destPath))