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