]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/cache/videos-preview-cache.ts
Add transition on play/loading player
[github/Chocobozzz/PeerTube.git] / server / lib / cache / videos-preview-cache.ts
CommitLineData
f981dae8 1import * as asyncLRU from 'async-lru'
f981dae8 2import { createWriteStream } from 'fs'
3fd3ab2d 3import { join } from 'path'
892211e8 4import { logger, unlinkPromise } from '../../helpers'
3fd3ab2d
C
5import { CACHE, CONFIG } from '../../initializers'
6import { VideoModel } from '../../models/video/video'
7import { fetchRemoteVideoPreview } from '../activitypub'
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
8fa5653a
C
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
f981dae8
C
42 return new Promise<string>((res, rej) => {
43 this.lru.get(key, (err, value) => {
44 err ? rej(err) : res(value)
45 })
46 })
47 }
48
f5028693 49 private async loadPreviews (key: string) {
8fa5653a 50 const video = await VideoModel.loadByUUID(key)
f5028693 51 if (!video) return undefined
f981dae8 52
8fa5653a 53 if (video.isOwned()) throw new Error('Cannot load preview of owned video.')
f981dae8 54
f5028693
C
55 const res = await this.saveRemotePreviewAndReturnPath(video)
56
57 return res
f981dae8
C
58 }
59
3fd3ab2d 60 private saveRemotePreviewAndReturnPath (video: VideoModel) {
571389d4 61 const req = fetchRemoteVideoPreview(video)
f981dae8
C
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
74export {
75 VideosPreviewCache
76}