]>
Commit | Line | Data |
---|---|---|
f981dae8 | 1 | import * as asyncLRU from 'async-lru' |
f981dae8 | 2 | import { createWriteStream } from 'fs' |
3fd3ab2d | 3 | import { join } from 'path' |
da854ddd C |
4 | import { unlinkPromise } from '../../helpers/core-utils' |
5 | import { logger } from '../../helpers/logger' | |
3fd3ab2d C |
6 | import { CACHE, CONFIG } from '../../initializers' |
7 | import { VideoModel } from '../../models/video/video' | |
8 | import { fetchRemoteVideoPreview } from '../activitypub' | |
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 | ||
8fa5653a C |
37 | async getPreviewPath (key: string) { |
38 | const video = await VideoModel.loadByUUID(key) | |
39 | if (!video) return undefined | |
40 | ||
41 | if (video.isOwned()) return join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()) | |
42 | ||
f981dae8 C |
43 | return new Promise<string>((res, rej) => { |
44 | this.lru.get(key, (err, value) => { | |
45 | err ? rej(err) : res(value) | |
46 | }) | |
47 | }) | |
48 | } | |
49 | ||
f5028693 | 50 | private async loadPreviews (key: string) { |
5f0805d3 | 51 | const video = await VideoModel.loadByUUIDAndPopulateAccountAndServerAndTags(key) |
f5028693 | 52 | if (!video) return undefined |
f981dae8 | 53 | |
8fa5653a | 54 | if (video.isOwned()) throw new Error('Cannot load preview of owned video.') |
f981dae8 | 55 | |
d50acfab | 56 | return this.saveRemotePreviewAndReturnPath(video) |
f981dae8 C |
57 | } |
58 | ||
3fd3ab2d | 59 | private saveRemotePreviewAndReturnPath (video: VideoModel) { |
f981dae8 | 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 | } |