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