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