]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/video-tokens-manager.ts
Bumped to version v5.2.1
[github/Chocobozzz/PeerTube.git] / server / lib / video-tokens-manager.ts
CommitLineData
83002a82 1import { LRUCache } from 'lru-cache'
3545e72c 2import { LRU_CACHE } from '@server/initializers/constants'
868314e8
C
3import { MUserAccountUrl } from '@server/types/models'
4import { pick } from '@shared/core-utils'
3545e72c
C
5import { 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
11class VideoTokensManager {
12
13 private static instance: VideoTokensManager
14
868314e8 15 private readonly lruCache = new LRUCache<string, { videoUUID: string, user: MUserAccountUrl }>({
3545e72c
C
16 max: LRU_CACHE.VIDEO_TOKENS.MAX_SIZE,
17 ttl: LRU_CACHE.VIDEO_TOKENS.TTL
18 })
19
20 private constructor () {}
21
868314e8
C
22 create (options: {
23 user: MUserAccountUrl
24 videoUUID: string
25 }) {
3545e72c
C
26 const token = buildUUID()
27
28 const expires = new Date(new Date().getTime() + LRU_CACHE.VIDEO_TOKENS.TTL)
29
868314e8 30 this.lruCache.set(token, pick(options, [ 'user', 'videoUUID' ]))
3545e72c
C
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
868314e8
C
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
3545e72c
C
52 }
53
54 static get Instance () {
55 return this.instance || (this.instance = new this())
56 }
57}
58
59// ---------------------------------------------------------------------------
60
61export {
62 VideoTokensManager
63}