aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/lib/cache/abstract-video-static-file-cache.ts
diff options
context:
space:
mode:
Diffstat (limited to 'server/lib/cache/abstract-video-static-file-cache.ts')
-rw-r--r--server/lib/cache/abstract-video-static-file-cache.ts54
1 files changed, 54 insertions, 0 deletions
diff --git a/server/lib/cache/abstract-video-static-file-cache.ts b/server/lib/cache/abstract-video-static-file-cache.ts
new file mode 100644
index 000000000..7eeeb6b3a
--- /dev/null
+++ b/server/lib/cache/abstract-video-static-file-cache.ts
@@ -0,0 +1,54 @@
1import * as AsyncLRU from 'async-lru'
2import { createWriteStream } from 'fs'
3import { join } from 'path'
4import { unlinkPromise } from '../../helpers/core-utils'
5import { logger } from '../../helpers/logger'
6import { CACHE, CONFIG } from '../../initializers'
7import { VideoModel } from '../../models/video/video'
8import { fetchRemoteVideoStaticFile } from '../activitypub'
9import { VideoCaptionModel } from '../../models/video/video-caption'
10
11export 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}