2023-05-22 11:04:39 -04:00
|
|
|
import { LRUCache } from 'lru-cache'
|
2022-10-12 10:09:02 -04:00
|
|
|
import { LRU_CACHE } from '@server/initializers/constants'
|
2022-12-20 03:15:49 -05:00
|
|
|
import { MUserAccountUrl } from '@server/types/models'
|
|
|
|
import { pick } from '@shared/core-utils'
|
2022-10-12 10:09:02 -04:00
|
|
|
import { buildUUID } from '@shared/extra-utils'
|
|
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// Create temporary tokens that can be used as URL query parameters to access video static files
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
class VideoTokensManager {
|
|
|
|
|
|
|
|
private static instance: VideoTokensManager
|
|
|
|
|
2023-06-29 03:48:55 -04:00
|
|
|
private readonly lruCache = new LRUCache<string, { videoUUID: string, user?: MUserAccountUrl }>({
|
2022-10-12 10:09:02 -04:00
|
|
|
max: LRU_CACHE.VIDEO_TOKENS.MAX_SIZE,
|
|
|
|
ttl: LRU_CACHE.VIDEO_TOKENS.TTL
|
|
|
|
})
|
|
|
|
|
|
|
|
private constructor () {}
|
|
|
|
|
2023-06-29 03:48:55 -04:00
|
|
|
createForAuthUser (options: {
|
2022-12-20 03:15:49 -05:00
|
|
|
user: MUserAccountUrl
|
|
|
|
videoUUID: string
|
|
|
|
}) {
|
2023-06-29 03:48:55 -04:00
|
|
|
const { token, expires } = this.generateVideoToken()
|
2022-10-12 10:09:02 -04:00
|
|
|
|
2022-12-20 03:15:49 -05:00
|
|
|
this.lruCache.set(token, pick(options, [ 'user', 'videoUUID' ]))
|
2022-10-12 10:09:02 -04:00
|
|
|
|
|
|
|
return { token, expires }
|
|
|
|
}
|
|
|
|
|
2023-06-29 03:48:55 -04:00
|
|
|
createForPasswordProtectedVideo (options: {
|
|
|
|
videoUUID: string
|
|
|
|
}) {
|
|
|
|
const { token, expires } = this.generateVideoToken()
|
|
|
|
|
|
|
|
this.lruCache.set(token, pick(options, [ 'videoUUID' ]))
|
|
|
|
|
|
|
|
return { token, expires }
|
|
|
|
}
|
|
|
|
|
2022-10-12 10:09:02 -04:00
|
|
|
hasToken (options: {
|
|
|
|
token: string
|
|
|
|
videoUUID: string
|
|
|
|
}) {
|
|
|
|
const value = this.lruCache.get(options.token)
|
|
|
|
if (!value) return false
|
|
|
|
|
2022-12-20 03:15:49 -05:00
|
|
|
return value.videoUUID === options.videoUUID
|
|
|
|
}
|
|
|
|
|
|
|
|
getUserFromToken (options: {
|
|
|
|
token: string
|
|
|
|
}) {
|
|
|
|
const value = this.lruCache.get(options.token)
|
|
|
|
if (!value) return undefined
|
|
|
|
|
|
|
|
return value.user
|
2022-10-12 10:09:02 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
static get Instance () {
|
|
|
|
return this.instance || (this.instance = new this())
|
|
|
|
}
|
2023-06-29 03:48:55 -04:00
|
|
|
|
|
|
|
private generateVideoToken () {
|
|
|
|
const token = buildUUID()
|
|
|
|
const expires = new Date(new Date().getTime() + LRU_CACHE.VIDEO_TOKENS.TTL)
|
|
|
|
|
|
|
|
return { token, expires }
|
|
|
|
}
|
2022-10-12 10:09:02 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
|
|
export {
|
|
|
|
VideoTokensManager
|
|
|
|
}
|