PeerTube/server/lib/cache/videos-preview-cache.ts

72 lines
1.8 KiB
TypeScript
Raw Normal View History

2017-07-12 11:56:02 +02:00
import * as asyncLRU from 'async-lru'
import { createWriteStream } from 'fs'
2017-12-12 17:53:50 +01:00
import { join } from 'path'
import { logger, unlinkPromise } from '../../helpers'
2017-12-12 17:53:50 +01:00
import { CACHE, CONFIG } from '../../initializers'
import { VideoModel } from '../../models/video/video'
import { fetchRemoteVideoPreview } from '../activitypub'
2017-07-12 11:56:02 +02:00
class VideosPreviewCache {
private static instance: VideosPreviewCache
private lru
private constructor () { }
static get Instance () {
return this.instance || (this.instance = new this())
}
init (max: number) {
this.lru = new asyncLRU({
max,
load: (key, cb) => {
this.loadPreviews(key)
.then(res => cb(null, res))
.catch(err => cb(err))
}
})
this.lru.on('evict', (obj: { key: string, value: string }) => {
unlinkPromise(obj.value).then(() => logger.debug('%s evicted from VideosPreviewCache', obj.value))
})
}
getPreviewPath (key: string) {
return new Promise<string>((res, rej) => {
this.lru.get(key, (err, value) => {
err ? rej(err) : res(value)
})
})
}
private async loadPreviews (key: string) {
2017-12-12 17:53:50 +01:00
const video = await VideoModel.loadByUUIDAndPopulateAccountAndServerAndTags(key)
if (!video) return undefined
2017-07-12 11:56:02 +02:00
if (video.isOwned()) return join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName())
2017-07-12 11:56:02 +02:00
const res = await this.saveRemotePreviewAndReturnPath(video)
return res
2017-07-12 11:56:02 +02:00
}
2017-12-12 17:53:50 +01:00
private saveRemotePreviewAndReturnPath (video: VideoModel) {
2017-11-10 17:27:49 +01:00
const req = fetchRemoteVideoPreview(video)
2017-07-12 11:56:02 +02:00
return new Promise<string>((res, rej) => {
const path = join(CACHE.DIRECTORIES.PREVIEWS, video.getPreviewName())
const stream = createWriteStream(path)
req.pipe(stream)
.on('finish', () => res(path))
.on('error', (err) => rej(err))
})
}
}
export {
VideosPreviewCache
}