]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - 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
1 import * as asyncLRU from 'async-lru'
2 import { join } from 'path'
3 import { createWriteStream } from 'fs'
4
5 import { database as db, CONFIG, CACHE } from '../../initializers'
6 import { logger, unlinkPromise } from '../../helpers'
7 import { VideoInstance } from '../../models'
8 import { fetchRemotePreview } from '../../lib'
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
45 private async loadPreviews (key: string) {
46 const video = await db.Video.loadByUUIDAndPopulateAuthorAndPodAndTags(key)
47 if (!video) return undefined
48
49 if (video.isOwned()) return join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName())
50
51 const res = await this.saveRemotePreviewAndReturnPath(video)
52
53 return res
54 }
55
56 private saveRemotePreviewAndReturnPath (video: VideoInstance) {
57 const req = fetchRemotePreview(video)
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 }