]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/cache/abstract-video-static-file-cache.ts
Fix comment deletion with mastodon
[github/Chocobozzz/PeerTube.git] / server / lib / cache / abstract-video-static-file-cache.ts
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'
6
7 export abstract class AbstractVideoStaticFileCache <T> {
8
9 protected lru
10
11 abstract getFilePath (params: T): Promise<string>
12
13 // Load and save the remote file, then return the local path from filesystem
14 protected abstract loadRemoteFile (key: string): Promise<string>
15
16 init (max: number, maxAge: number) {
17 this.lru = new AsyncLRU({
18 max,
19 maxAge,
20 load: (key, cb) => {
21 this.loadRemoteFile(key)
22 .then(res => cb(null, res))
23 .catch(err => cb(err))
24 }
25 })
26
27 this.lru.on('evict', (obj: { key: string, value: string }) => {
28 remove(obj.value)
29 .then(() => logger.debug('%s evicted from %s', obj.value, this.constructor.name))
30 })
31 }
32
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)
37 })
38 })
39 }
40
41 protected saveRemoteVideoFileAndReturnPath (video: VideoModel, remoteStaticPath: string, destPath: string) {
42 return new Promise<string>((res, rej) => {
43 const req = fetchRemoteVideoStaticFile(video, remoteStaticPath, rej)
44
45 const stream = createWriteStream(destPath)
46
47 req.pipe(stream)
48 .on('error', (err) => rej(err))
49 .on('finish', () => res(destPath))
50 })
51 }
52 }