Remove ability to delete video imports
[oweals/peertube.git] / server / lib / cache / abstract-video-static-file-cache.ts
1 import * as AsyncLRU from 'async-lru'
2 import { createWriteStream } from 'fs'
3 import { unlinkPromise } from '../../helpers/core-utils'
4 import { logger } from '../../helpers/logger'
5 import { VideoModel } from '../../models/video/video'
6 import { fetchRemoteVideoStaticFile } from '../activitypub'
7
8 export abstract class AbstractVideoStaticFileCache <T> {
9
10   protected lru
11
12   abstract getFilePath (params: T): Promise<string>
13
14   // Load and save the remote file, then return the local path from filesystem
15   protected abstract loadRemoteFile (key: string): Promise<string>
16
17   init (max: number, maxAge: number) {
18     this.lru = new AsyncLRU({
19       max,
20       maxAge,
21       load: (key, cb) => {
22         this.loadRemoteFile(key)
23           .then(res => cb(null, res))
24           .catch(err => cb(err))
25       }
26     })
27
28     this.lru.on('evict', (obj: { key: string, value: string }) => {
29       unlinkPromise(obj.value)
30         .then(() => logger.debug('%s evicted from %s', obj.value, this.constructor.name))
31     })
32   }
33
34   protected loadFromLRU (key: string) {
35     return new Promise<string>((res, rej) => {
36       this.lru.get(key, (err, value) => {
37         err ? rej(err) : res(value)
38       })
39     })
40   }
41
42   protected saveRemoteVideoFileAndReturnPath (video: VideoModel, remoteStaticPath: string, destPath: string) {
43     return new Promise<string>((res, rej) => {
44       const req = fetchRemoteVideoStaticFile(video, remoteStaticPath, rej)
45
46       const stream = createWriteStream(destPath)
47
48       req.pipe(stream)
49          .on('error', (err) => rej(err))
50          .on('finish', () => res(destPath))
51     })
52   }
53 }