]>
Commit | Line | Data |
---|---|---|
1 | import * as asyncLRU from 'async-lru' | |
2 | import { createWriteStream } from 'fs' | |
3 | import { join } from 'path' | |
4 | import { logger, unlinkPromise } from '../../helpers' | |
5 | import { CACHE, CONFIG } from '../../initializers' | |
6 | import { VideoModel } from '../../models/video/video' | |
7 | import { fetchRemoteVideoPreview } from '../activitypub' | |
8 | ||
9 | class VideosPreviewCache { | |
10 | ||
11 | private static instance: VideosPreviewCache | |
12 | ||
13 | private lru | |
14 | ||
15 | private constructor () { } | |
16 | ||
17 | static get Instance () { | |
18 | return this.instance || (this.instance = new this()) | |
19 | } | |
20 | ||
21 | init (max: number) { | |
22 | this.lru = new asyncLRU({ | |
23 | max, | |
24 | load: (key, cb) => { | |
25 | this.loadPreviews(key) | |
26 | .then(res => cb(null, res)) | |
27 | .catch(err => cb(err)) | |
28 | } | |
29 | }) | |
30 | ||
31 | this.lru.on('evict', (obj: { key: string, value: string }) => { | |
32 | unlinkPromise(obj.value).then(() => logger.debug('%s evicted from VideosPreviewCache', obj.value)) | |
33 | }) | |
34 | } | |
35 | ||
36 | async getPreviewPath (key: string) { | |
37 | const video = await VideoModel.loadByUUID(key) | |
38 | if (!video) return undefined | |
39 | ||
40 | if (video.isOwned()) return join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()) | |
41 | ||
42 | return new Promise<string>((res, rej) => { | |
43 | this.lru.get(key, (err, value) => { | |
44 | err ? rej(err) : res(value) | |
45 | }) | |
46 | }) | |
47 | } | |
48 | ||
49 | private async loadPreviews (key: string) { | |
50 | const video = await VideoModel.loadByUUIDAndPopulateAccountAndServerAndTags(key) | |
51 | if (!video) return undefined | |
52 | ||
53 | if (video.isOwned()) throw new Error('Cannot load preview of owned video.') | |
54 | ||
55 | return this.saveRemotePreviewAndReturnPath(video) | |
56 | } | |
57 | ||
58 | private saveRemotePreviewAndReturnPath (video: VideoModel) { | |
59 | ||
60 | return new Promise<string>((res, rej) => { | |
61 | const req = fetchRemoteVideoPreview(video, rej) | |
62 | const path = join(CACHE.DIRECTORIES.PREVIEWS, video.getPreviewName()) | |
63 | const stream = createWriteStream(path) | |
64 | ||
65 | req.pipe(stream) | |
66 | .on('error', (err) => rej(err)) | |
67 | .on('finish', () => res(path)) | |
68 | }) | |
69 | } | |
70 | } | |
71 | ||
72 | export { | |
73 | VideosPreviewCache | |
74 | } |