aboutsummaryrefslogblamecommitdiffhomepage
path: root/server/lib/video-tokens-manager.ts
blob: 17aa29cdda707f9dc2e3893557d3e8aae3d389aa (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12
13
14

                                                          

                                                      









                                                                                                
                                                                                                  





                                         



                         



                                                                               
                                                                    










                                                  









                                                  











                                                                              
import LRUCache from 'lru-cache'
import { LRU_CACHE } from '@server/initializers/constants'
import { MUserAccountUrl } from '@server/types/models'
import { pick } from '@shared/core-utils'
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

  private readonly lruCache = new LRUCache<string, { videoUUID: string, user: MUserAccountUrl }>({
    max: LRU_CACHE.VIDEO_TOKENS.MAX_SIZE,
    ttl: LRU_CACHE.VIDEO_TOKENS.TTL
  })

  private constructor () {}

  create (options: {
    user: MUserAccountUrl
    videoUUID: string
  }) {
    const token = buildUUID()

    const expires = new Date(new Date().getTime() + LRU_CACHE.VIDEO_TOKENS.TTL)

    this.lruCache.set(token, pick(options, [ 'user', 'videoUUID' ]))

    return { token, expires }
  }

  hasToken (options: {
    token: string
    videoUUID: string
  }) {
    const value = this.lruCache.get(options.token)
    if (!value) return false

    return value.videoUUID === options.videoUUID
  }

  getUserFromToken (options: {
    token: string
  }) {
    const value = this.lruCache.get(options.token)
    if (!value) return undefined

    return value.user
  }

  static get Instance () {
    return this.instance || (this.instance = new this())
  }
}

// ---------------------------------------------------------------------------

export {
  VideoTokensManager
}