1 import { createWriteStream, remove } from 'fs-extra'
2 import { logger } from '../../helpers/logger'
3 import { VideoModel } from '../../models/video/video'
4 import { fetchRemoteVideoStaticFile } from '../activitypub'
5 import * as memoizee from 'memoizee'
7 export abstract class AbstractVideoStaticFileCache <T> {
9 getFilePath: (params: T) => Promise<string>
11 abstract getFilePathImpl (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.getFilePath = memoizee(this.getFilePathImpl, {
21 dispose: (value: string) => {
23 .then(() => logger.debug('%s evicted from %s', value, this.constructor.name))
24 .catch(err => logger.error('Cannot remove %s from cache %s.', value, this.constructor.name, { err }))
29 protected saveRemoteVideoFileAndReturnPath (video: VideoModel, remoteStaticPath: string, destPath: string) {
30 return new Promise<string>((res, rej) => {
31 const req = fetchRemoteVideoStaticFile(video, remoteStaticPath, rej)
33 const stream = createWriteStream(destPath)
36 .on('error', (err) => rej(err))
37 .on('finish', () => res(destPath))