]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/cache/abstract-video-static-file-cache.ts
Fix thumbnail processing
[github/Chocobozzz/PeerTube.git] / server / lib / cache / abstract-video-static-file-cache.ts
CommitLineData
40e87e9e 1import * as AsyncLRU from 'async-lru'
62689b94 2import { createWriteStream, remove } from 'fs-extra'
40e87e9e 3import { logger } from '../../helpers/logger'
40e87e9e
C
4import { VideoModel } from '../../models/video/video'
5import { fetchRemoteVideoStaticFile } from '../activitypub'
40e87e9e
C
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
f4001cf4 16 init (max: number, maxAge: number) {
40e87e9e
C
17 this.lru = new AsyncLRU({
18 max,
f4001cf4 19 maxAge,
40e87e9e
C
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 }) => {
62689b94 28 remove(obj.value)
f4001cf4 29 .then(() => logger.debug('%s evicted from %s', obj.value, this.constructor.name))
40e87e9e
C
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}