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 type GetFilePathResult = { isOwned: boolean, path: string } | undefined
9 export abstract class AbstractVideoStaticFileCache <T> {
11 getFilePath: (params: T) => Promise<GetFilePathResult>
13 abstract getFilePathImpl (params: T): Promise<GetFilePathResult>
15 // Load and save the remote file, then return the local path from filesystem
16 protected abstract loadRemoteFile (key: string): Promise<GetFilePathResult>
18 init (max: number, maxAge: number) {
19 this.getFilePath = memoizee(this.getFilePathImpl, {
23 dispose: (result: GetFilePathResult) => {
24 if (result.isOwned !== true) {
26 .then(() => logger.debug('%s removed from %s', result.path, this.constructor.name))
27 .catch(err => logger.error('Cannot remove %s from cache %s.', result.path, this.constructor.name, { err }))
33 protected saveRemoteVideoFileAndReturnPath (video: VideoModel, remoteStaticPath: string, destPath: string) {
34 return new Promise<string>((res, rej) => {
35 const req = fetchRemoteVideoStaticFile(video, remoteStaticPath, rej)
37 const stream = createWriteStream(destPath)
40 .on('error', (err) => rej(err))
41 .on('finish', () => res(destPath))