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'
|
2017-11-20 10:24:29 +01:00
|
|
|
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)
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2017-10-25 16:03:33 +02:00
|
|
|
private async loadPreviews (key: string) {
|
2017-12-12 17:53:50 +01:00
|
|
|
const video = await VideoModel.loadByUUIDAndPopulateAccountAndServerAndTags(key)
|
2017-10-25 16:03:33 +02:00
|
|
|
if (!video) return undefined
|
2017-07-12 11:56:02 +02:00
|
|
|
|
2017-10-25 16:03:33 +02:00
|
|
|
if (video.isOwned()) return join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName())
|
2017-07-12 11:56:02 +02:00
|
|
|
|
2017-10-25 16:03:33 +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
|
|
|
|
}
|