]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/cache/videos-preview-cache.ts
Rename Pod -> Server
[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'
571389d4 6import { logger, unlinkPromise, fetchRemoteVideoPreview } from '../../helpers'
f981dae8 7import { VideoInstance } from '../../models'
f981dae8
C
8
9class 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
f5028693 44 private async loadPreviews (key: string) {
60862425 45 const video = await db.Video.loadByUUIDAndPopulateAccountAndServerAndTags(key)
f5028693 46 if (!video) return undefined
f981dae8 47
f5028693 48 if (video.isOwned()) return join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName())
f981dae8 49
f5028693
C
50 const res = await this.saveRemotePreviewAndReturnPath(video)
51
52 return res
f981dae8
C
53 }
54
55 private saveRemotePreviewAndReturnPath (video: VideoInstance) {
571389d4 56 const req = fetchRemoteVideoPreview(video)
f981dae8
C
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
69export {
70 VideosPreviewCache
71}