]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/cache/videos-preview-cache.ts
0eb43efcc03dc10c7aab65a929b1e64bfa2f1734
[github/Chocobozzz/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 { logger, unlinkPromise } from '../../helpers'
5 import { CACHE, CONFIG } from '../../initializers'
6 import { VideoModel } from '../../models/video/video'
7 import { fetchRemoteVideoPreview } from '../activitypub'
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 async getPreviewPath (key: string) {
37 const video = await VideoModel.loadByUUID(key)
38 if (!video) return undefined
39
40 if (video.isOwned()) return join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName())
41
42 return new Promise<string>((res, rej) => {
43 this.lru.get(key, (err, value) => {
44 err ? rej(err) : res(value)
45 })
46 })
47 }
48
49 private async loadPreviews (key: string) {
50 const video = await VideoModel.loadByUUIDAndPopulateAccountAndServerAndTags(key)
51 if (!video) return undefined
52
53 if (video.isOwned()) throw new Error('Cannot load preview of owned video.')
54
55 const res = await this.saveRemotePreviewAndReturnPath(video)
56
57 return res
58 }
59
60 private saveRemotePreviewAndReturnPath (video: VideoModel) {
61 const req = fetchRemoteVideoPreview(video)
62
63 return new Promise<string>((res, rej) => {
64 const path = join(CACHE.DIRECTORIES.PREVIEWS, video.getPreviewName())
65 const stream = createWriteStream(path)
66
67 req.pipe(stream)
68 .on('finish', () => res(path))
69 .on('error', (err) => rej(err))
70 })
71 }
72 }
73
74 export {
75 VideosPreviewCache
76 }