1
0
Fork 0
peertube/server/lib/files-cache/abstract-video-static-file-...

41 lines
1.4 KiB
TypeScript
Raw Normal View History

2018-08-27 14:23:34 +00:00
import { createWriteStream, remove } from 'fs-extra'
2018-07-12 17:02:00 +00:00
import { logger } from '../../helpers/logger'
import { VideoModel } from '../../models/video/video'
import { fetchRemoteVideoStaticFile } from '../activitypub'
import * as memoizee from 'memoizee'
2018-07-12 17:02:00 +00:00
export abstract class AbstractVideoStaticFileCache <T> {
getFilePath: (params: T) => Promise<string>
2018-07-12 17:02:00 +00:00
abstract getFilePathImpl (params: T): Promise<string>
2018-07-12 17:02:00 +00:00
// Load and save the remote file, then return the local path from filesystem
protected abstract loadRemoteFile (key: string): Promise<string>
2018-07-16 12:22:16 +00:00
init (max: number, maxAge: number) {
this.getFilePath = memoizee(this.getFilePathImpl, {
2018-07-16 12:22:16 +00:00
maxAge,
max,
promise: true,
dispose: (value: string) => {
remove(value)
.then(() => logger.debug('%s evicted from %s', value, this.constructor.name))
.catch(err => logger.error('Cannot remove %s from cache %s.', value, this.constructor.name, { err }))
2018-07-12 17:02:00 +00:00
}
})
}
protected saveRemoteVideoFileAndReturnPath (video: VideoModel, remoteStaticPath: string, destPath: string) {
return new Promise<string>((res, rej) => {
const req = fetchRemoteVideoStaticFile(video, remoteStaticPath, rej)
const stream = createWriteStream(destPath)
req.pipe(stream)
.on('error', (err) => rej(err))
.on('finish', () => res(destPath))
})
}
}