2017-07-12 04:56:02 -05:00
|
|
|
import * as asyncLRU from 'async-lru'
|
|
|
|
import { createWriteStream } from 'fs'
|
2017-12-12 10:53:50 -06:00
|
|
|
import { join } from 'path'
|
2017-11-20 03:24:29 -06:00
|
|
|
import { logger, unlinkPromise } from '../../helpers'
|
2017-12-12 10:53:50 -06:00
|
|
|
import { CACHE, CONFIG } from '../../initializers'
|
|
|
|
import { VideoModel } from '../../models/video/video'
|
|
|
|
import { fetchRemoteVideoPreview } from '../activitypub'
|
2017-07-12 04:56:02 -05: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))
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2017-12-20 04:05:10 -06:00
|
|
|
async getPreviewPath (key: string) {
|
|
|
|
const video = await VideoModel.loadByUUID(key)
|
|
|
|
if (!video) return undefined
|
|
|
|
|
|
|
|
if (video.isOwned()) return join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName())
|
|
|
|
|
2017-07-12 04:56:02 -05:00
|
|
|
return new Promise<string>((res, rej) => {
|
|
|
|
this.lru.get(key, (err, value) => {
|
|
|
|
err ? rej(err) : res(value)
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2017-10-25 09:03:33 -05:00
|
|
|
private async loadPreviews (key: string) {
|
2017-12-20 10:49:58 -06:00
|
|
|
const video = await VideoModel.loadByUUIDAndPopulateAccountAndServerAndTags(key)
|
2017-10-25 09:03:33 -05:00
|
|
|
if (!video) return undefined
|
2017-07-12 04:56:02 -05:00
|
|
|
|
2017-12-20 04:05:10 -06:00
|
|
|
if (video.isOwned()) throw new Error('Cannot load preview of owned video.')
|
2017-07-12 04:56:02 -05:00
|
|
|
|
2017-12-27 13:03:37 -06:00
|
|
|
return this.saveRemotePreviewAndReturnPath(video)
|
2017-07-12 04:56:02 -05:00
|
|
|
}
|
|
|
|
|
2017-12-12 10:53:50 -06:00
|
|
|
private saveRemotePreviewAndReturnPath (video: VideoModel) {
|
2017-07-12 04:56:02 -05:00
|
|
|
return new Promise<string>((res, rej) => {
|
2017-12-27 13:03:37 -06:00
|
|
|
const req = fetchRemoteVideoPreview(video, rej)
|
2017-07-12 04:56:02 -05:00
|
|
|
const path = join(CACHE.DIRECTORIES.PREVIEWS, video.getPreviewName())
|
|
|
|
const stream = createWriteStream(path)
|
|
|
|
|
|
|
|
req.pipe(stream)
|
2017-12-27 13:03:37 -06:00
|
|
|
.on('error', (err) => rej(err))
|
|
|
|
.on('finish', () => res(path))
|
2017-07-12 04:56:02 -05:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export {
|
|
|
|
VideosPreviewCache
|
|
|
|
}
|