1 import * as AsyncLRU from 'async-lru'
2 import { createWriteStream, remove } from 'fs-extra'
3 import { logger } from '../../helpers/logger'
4 import { VideoModel } from '../../models/video/video'
5 import { fetchRemoteVideoStaticFile } from '../activitypub'
7 export abstract class AbstractVideoStaticFileCache <T> {
11 abstract getFilePath (params: T): Promise<string>
13 // Load and save the remote file, then return the local path from filesystem
14 protected abstract loadRemoteFile (key: string): Promise<string>
16 init (max: number, maxAge: number) {
17 this.lru = new AsyncLRU({
21 this.loadRemoteFile(key)
22 .then(res => cb(null, res))
23 .catch(err => cb(err))
27 this.lru.on('evict', (obj: { key: string, value: string }) => {
29 .then(() => logger.debug('%s evicted from %s', obj.value, this.constructor.name))
33 protected loadFromLRU (key: string) {
34 return new Promise<string>((res, rej) => {
35 this.lru.get(key, (err, value) => {
36 err ? rej(err) : res(value)
41 protected saveRemoteVideoFileAndReturnPath (video: VideoModel, remoteStaticPath: string, destPath: string) {
42 return new Promise<string>((res, rej) => {
43 const req = fetchRemoteVideoStaticFile(video, remoteStaticPath, rej)
45 const stream = createWriteStream(destPath)
48 .on('error', (err) => rej(err))
49 .on('finish', () => res(destPath))