aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/lib/files-cache/abstract-video-static-file-cache.ts
diff options
context:
space:
mode:
authorChocobozzz <me@florianbigard.com>2019-03-19 14:23:17 +0100
committerChocobozzz <me@florianbigard.com>2019-03-19 14:30:43 +0100
commitd74d29ad9e35929491cf37223398d2535ab23de0 (patch)
tree2812c9acbc05be0603eb671f8e6bd81086cf84d5 /server/lib/files-cache/abstract-video-static-file-cache.ts
parent9f79ade627f0044606a9fbbe16ca0154661d12b9 (diff)
downloadPeerTube-d74d29ad9e35929491cf37223398d2535ab23de0.tar.gz
PeerTube-d74d29ad9e35929491cf37223398d2535ab23de0.tar.zst
PeerTube-d74d29ad9e35929491cf37223398d2535ab23de0.zip
Limit user tokens cache
Diffstat (limited to 'server/lib/files-cache/abstract-video-static-file-cache.ts')
-rw-r--r--server/lib/files-cache/abstract-video-static-file-cache.ts52
1 files changed, 52 insertions, 0 deletions
diff --git a/server/lib/files-cache/abstract-video-static-file-cache.ts b/server/lib/files-cache/abstract-video-static-file-cache.ts
new file mode 100644
index 000000000..7512f2b9d
--- /dev/null
+++ b/server/lib/files-cache/abstract-video-static-file-cache.ts
@@ -0,0 +1,52 @@
1import * as AsyncLRU from 'async-lru'
2import { createWriteStream, remove } from 'fs-extra'
3import { logger } from '../../helpers/logger'
4import { VideoModel } from '../../models/video/video'
5import { fetchRemoteVideoStaticFile } from '../activitypub'
6
7export 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}