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