]>
Commit | Line | Data |
---|---|---|
f981dae8 | 1 | import * as asyncLRU from 'async-lru' |
f981dae8 | 2 | import { createWriteStream } from 'fs' |
3fd3ab2d | 3 | import { join } from 'path' |
892211e8 | 4 | import { logger, unlinkPromise } from '../../helpers' |
3fd3ab2d C |
5 | import { CACHE, CONFIG } from '../../initializers' |
6 | import { VideoModel } from '../../models/video/video' | |
7 | import { fetchRemoteVideoPreview } from '../activitypub' | |
f981dae8 C |
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 | ||
8fa5653a C |
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 | ||
f981dae8 C |
42 | return new Promise<string>((res, rej) => { |
43 | this.lru.get(key, (err, value) => { | |
44 | err ? rej(err) : res(value) | |
45 | }) | |
46 | }) | |
47 | } | |
48 | ||
f5028693 | 49 | private async loadPreviews (key: string) { |
5f0805d3 | 50 | const video = await VideoModel.loadByUUIDAndPopulateAccountAndServerAndTags(key) |
f5028693 | 51 | if (!video) return undefined |
f981dae8 | 52 | |
8fa5653a | 53 | if (video.isOwned()) throw new Error('Cannot load preview of owned video.') |
f981dae8 | 54 | |
d50acfab | 55 | return this.saveRemotePreviewAndReturnPath(video) |
f981dae8 C |
56 | } |
57 | ||
3fd3ab2d | 58 | private saveRemotePreviewAndReturnPath (video: VideoModel) { |
f981dae8 C |
59 | |
60 | return new Promise<string>((res, rej) => { | |
d50acfab | 61 | const req = fetchRemoteVideoPreview(video, rej) |
f981dae8 C |
62 | const path = join(CACHE.DIRECTORIES.PREVIEWS, video.getPreviewName()) |
63 | const stream = createWriteStream(path) | |
64 | ||
65 | req.pipe(stream) | |
d50acfab C |
66 | .on('error', (err) => rej(err)) |
67 | .on('finish', () => res(path)) | |
f981dae8 C |
68 | }) |
69 | } | |
70 | } | |
71 | ||
72 | export { | |
73 | VideosPreviewCache | |
74 | } |