]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/cache/abstract-video-static-file-cache.ts
Increase test timeout for imports
[github/Chocobozzz/PeerTube.git] / server / lib / cache / abstract-video-static-file-cache.ts
CommitLineData
40e87e9e
C
1import * as AsyncLRU from 'async-lru'
2import { createWriteStream } from 'fs'
40e87e9e
C
3import { unlinkPromise } from '../../helpers/core-utils'
4import { logger } from '../../helpers/logger'
40e87e9e
C
5import { VideoModel } from '../../models/video/video'
6import { fetchRemoteVideoStaticFile } from '../activitypub'
40e87e9e
C
7
8export 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
f4001cf4 17 init (max: number, maxAge: number) {
40e87e9e
C
18 this.lru = new AsyncLRU({
19 max,
f4001cf4 20 maxAge,
40e87e9e
C
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 }) => {
f4001cf4
C
29 unlinkPromise(obj.value)
30 .then(() => logger.debug('%s evicted from %s', obj.value, this.constructor.name))
40e87e9e
C
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}