2017-07-12 05:56:02 -04:00
|
|
|
import * as asyncLRU from 'async-lru'
|
|
|
|
import { join } from 'path'
|
|
|
|
import { createWriteStream } from 'fs'
|
|
|
|
|
|
|
|
import { database as db, CONFIG, CACHE } from '../../initializers'
|
2017-11-20 04:24:29 -05:00
|
|
|
import { logger, unlinkPromise } from '../../helpers'
|
2017-07-12 05:56:02 -04:00
|
|
|
import { VideoInstance } from '../../models'
|
2017-11-20 04:24:29 -05:00
|
|
|
import { fetchRemoteVideoPreview } from '../activitypub/videos'
|
2017-07-12 05:56:02 -04: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 10:03:33 -04:00
|
|
|
private async loadPreviews (key: string) {
|
2017-11-15 05:00:25 -05:00
|
|
|
const video = await db.Video.loadByUUIDAndPopulateAccountAndServerAndTags(key)
|
2017-10-25 10:03:33 -04:00
|
|
|
if (!video) return undefined
|
2017-07-12 05:56:02 -04:00
|
|
|
|
2017-10-25 10:03:33 -04:00
|
|
|
if (video.isOwned()) return join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName())
|
2017-07-12 05:56:02 -04:00
|
|
|
|
2017-10-25 10:03:33 -04:00
|
|
|
const res = await this.saveRemotePreviewAndReturnPath(video)
|
|
|
|
|
|
|
|
return res
|
2017-07-12 05:56:02 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
private saveRemotePreviewAndReturnPath (video: VideoInstance) {
|
2017-11-10 11:27:49 -05:00
|
|
|
const req = fetchRemoteVideoPreview(video)
|
2017-07-12 05:56:02 -04: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
|
|
|
|
}
|