ニジカ投稿局 https://tv.nizika.tv
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

79 lines
2.0 KiB

  1. import { LRUCache } from 'lru-cache'
  2. import { LRU_CACHE } from '@server/initializers/constants.js'
  3. import { MUserAccountUrl } from '@server/types/models/index.js'
  4. import { pick } from '@peertube/peertube-core-utils'
  5. import { buildUUID } from '@peertube/peertube-node-utils'
  6. // ---------------------------------------------------------------------------
  7. // Create temporary tokens that can be used as URL query parameters to access video static files
  8. // ---------------------------------------------------------------------------
  9. class VideoTokensManager {
  10. private static instance: VideoTokensManager
  11. private readonly lruCache = new LRUCache<string, { videoUUID: string, user?: MUserAccountUrl }>({
  12. max: LRU_CACHE.VIDEO_TOKENS.MAX_SIZE,
  13. ttl: LRU_CACHE.VIDEO_TOKENS.TTL
  14. })
  15. private constructor () {}
  16. createForAuthUser (options: {
  17. user: MUserAccountUrl
  18. videoUUID: string
  19. }) {
  20. const { token, expires } = this.generateVideoToken()
  21. this.lruCache.set(token, pick(options, [ 'user', 'videoUUID' ]))
  22. return { token, expires }
  23. }
  24. createForPasswordProtectedVideo (options: {
  25. videoUUID: string
  26. }) {
  27. const { token, expires } = this.generateVideoToken()
  28. this.lruCache.set(token, pick(options, [ 'videoUUID' ]))
  29. return { token, expires }
  30. }
  31. hasToken (options: {
  32. token: string
  33. videoUUID: string
  34. }) {
  35. const value = this.lruCache.get(options.token)
  36. if (!value) return false
  37. return value.videoUUID === options.videoUUID
  38. }
  39. getUserFromToken (options: {
  40. token: string
  41. }) {
  42. const value = this.lruCache.get(options.token)
  43. if (!value) return undefined
  44. return value.user
  45. }
  46. static get Instance () {
  47. return this.instance || (this.instance = new this())
  48. }
  49. private generateVideoToken () {
  50. const token = buildUUID()
  51. const expires = new Date(new Date().getTime() + LRU_CACHE.VIDEO_TOKENS.TTL)
  52. return { token, expires }
  53. }
  54. }
  55. // ---------------------------------------------------------------------------
  56. export {
  57. VideoTokensManager
  58. }