]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/cache/videos-preview-cache.ts
Use async/await in lib and initializers
[github/Chocobozzz/PeerTube.git] / server / lib / cache / videos-preview-cache.ts
CommitLineData
f981dae8
C
1import * as asyncLRU from 'async-lru'
2import { join } from 'path'
3import { createWriteStream } from 'fs'
f981dae8
C
4
5import { database as db, CONFIG, CACHE } from '../../initializers'
0b7db72a 6import { logger, unlinkPromise } from '../../helpers'
f981dae8
C
7import { VideoInstance } from '../../models'
8import { fetchRemotePreview } from '../../lib'
9
10class 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
C
45 private async loadPreviews (key: string) {
46 const video = await db.Video.loadByUUIDAndPopulateAuthorAndPodAndTags(key)
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) {
72c7248b 57 const req = fetchRemotePreview(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
70export {
71 VideosPreviewCache
72}