Refractor activity pub lib/helpers
[oweals/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, fetchRemoteVideoPreview } from '../../helpers'
7 import { VideoInstance } from '../../models'
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
36   getPreviewPath (key: string) {
37     return new Promise<string>((res, rej) => {
38       this.lru.get(key, (err, value) => {
39         err ? rej(err) : res(value)
40       })
41     })
42   }
43
44   private async loadPreviews (key: string) {
45     const video = await db.Video.loadByUUIDAndPopulateAccountAndServerAndTags(key)
46     if (!video) return undefined
47
48     if (video.isOwned()) return join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName())
49
50     const res = await this.saveRemotePreviewAndReturnPath(video)
51
52     return res
53   }
54
55   private saveRemotePreviewAndReturnPath (video: VideoInstance) {
56     const req = fetchRemoteVideoPreview(video)
57
58     return new Promise<string>((res, rej) => {
59       const path = join(CACHE.DIRECTORIES.PREVIEWS, video.getPreviewName())
60       const stream = createWriteStream(path)
61
62       req.pipe(stream)
63          .on('finish', () => res(path))
64          .on('error', (err) => rej(err))
65     })
66   }
67 }
68
69 export {
70   VideosPreviewCache
71 }