]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/redis.ts
Fix last commit
[github/Chocobozzz/PeerTube.git] / server / lib / redis.ts
CommitLineData
4195cd2b 1import * as express from 'express'
ecb4e35f
C
2import { createClient, RedisClient } from 'redis'
3import { logger } from '../helpers/logger'
4import { generateRandomString } from '../helpers/utils'
fd4484f1 5import { CONFIG, USER_PASSWORD_RESET_LIFETIME, VIDEO_VIEW_LIFETIME } from '../initializers'
4195cd2b
C
6
7type CachedRoute = {
8 body: string,
2cebd797
C
9 contentType?: string
10 statusCode?: string
4195cd2b 11}
ecb4e35f
C
12
13class Redis {
14
15 private static instance: Redis
16 private initialized = false
17 private client: RedisClient
18 private prefix: string
19
20 private constructor () {}
21
22 init () {
23 // Already initialized
24 if (this.initialized === true) return
25 this.initialized = true
26
19f7b248 27 this.client = createClient(Redis.getRedisClient())
ecb4e35f
C
28
29 this.client.on('error', err => {
d5b7d911 30 logger.error('Error in Redis client.', { err })
ecb4e35f
C
31 process.exit(-1)
32 })
33
34 if (CONFIG.REDIS.AUTH) {
35 this.client.auth(CONFIG.REDIS.AUTH)
36 }
37
38 this.prefix = 'redis-' + CONFIG.WEBSERVER.HOST + '-'
39 }
40
19f7b248
RK
41 static getRedisClient () {
42 return Object.assign({},
43 (CONFIG.REDIS.AUTH && CONFIG.REDIS.AUTH != null) ? { password: CONFIG.REDIS.AUTH } : {},
44 (CONFIG.REDIS.DB) ? { db: CONFIG.REDIS.DB } : {},
45 (CONFIG.REDIS.HOSTNAME && CONFIG.REDIS.PORT) ?
46 { host: CONFIG.REDIS.HOSTNAME, port: CONFIG.REDIS.PORT } :
47 { path: CONFIG.REDIS.SOCKET }
48 )
49 }
50
ecb4e35f
C
51 async setResetPasswordVerificationString (userId: number) {
52 const generatedString = await generateRandomString(32)
53
54 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_RESET_LIFETIME)
55
56 return generatedString
57 }
58
59 async getResetPasswordLink (userId: number) {
60 return this.getValue(this.generateResetPasswordKey(userId))
61 }
62
b5c0e955
C
63 setView (ip: string, videoUUID: string) {
64 return this.setValue(this.buildViewKey(ip, videoUUID), '1', VIDEO_VIEW_LIFETIME)
65 }
66
67 async isViewExists (ip: string, videoUUID: string) {
68 return this.exists(this.buildViewKey(ip, videoUUID))
69 }
70
4195cd2b
C
71 async getCachedRoute (req: express.Request) {
72 const cached = await this.getObject(this.buildCachedRouteKey(req))
73
74 return cached as CachedRoute
75 }
76
fd4484f1 77 setCachedRoute (req: express.Request, body: any, lifetime: number, contentType?: string, statusCode?: number) {
c1e791ba
RK
78 const cached: CachedRoute = Object.assign({}, {
79 body: body.toString()
80 },
81 (contentType) ? { contentType } : null,
82 (statusCode) ? { statusCode: statusCode.toString() } : null
83 )
4195cd2b 84
fd4484f1 85 return this.setObject(this.buildCachedRouteKey(req), cached, lifetime)
4195cd2b
C
86 }
87
b40f0575
C
88 generateResetPasswordKey (userId: number) {
89 return 'reset-password-' + userId
90 }
91
92 buildViewKey (ip: string, videoUUID: string) {
93 return videoUUID + '-' + ip
94 }
95
96 buildCachedRouteKey (req: express.Request) {
97 return req.method + '-' + req.originalUrl
98 }
99
ecb4e35f
C
100 private getValue (key: string) {
101 return new Promise<string>((res, rej) => {
102 this.client.get(this.prefix + key, (err, value) => {
103 if (err) return rej(err)
104
105 return res(value)
106 })
107 })
108 }
109
110 private setValue (key: string, value: string, expirationMilliseconds: number) {
111 return new Promise<void>((res, rej) => {
112 this.client.set(this.prefix + key, value, 'PX', expirationMilliseconds, (err, ok) => {
113 if (err) return rej(err)
114
4195cd2b 115 if (ok !== 'OK') return rej(new Error('Redis set result is not OK.'))
ecb4e35f
C
116
117 return res()
118 })
119 })
120 }
121
4195cd2b
C
122 private setObject (key: string, obj: { [ id: string ]: string }, expirationMilliseconds: number) {
123 return new Promise<void>((res, rej) => {
124 this.client.hmset(this.prefix + key, obj, (err, ok) => {
125 if (err) return rej(err)
126 if (!ok) return rej(new Error('Redis mset result is not OK.'))
127
128 this.client.pexpire(this.prefix + key, expirationMilliseconds, (err, ok) => {
129 if (err) return rej(err)
130 if (!ok) return rej(new Error('Redis expiration result is not OK.'))
131
132 return res()
133 })
134 })
135 })
136 }
137
138 private getObject (key: string) {
139 return new Promise<{ [ id: string ]: string }>((res, rej) => {
140 this.client.hgetall(this.prefix + key, (err, value) => {
141 if (err) return rej(err)
142
143 return res(value)
144 })
145 })
146 }
147
b5c0e955
C
148 private exists (key: string) {
149 return new Promise<boolean>((res, rej) => {
150 this.client.exists(this.prefix + key, (err, existsNumber) => {
151 if (err) return rej(err)
152
153 return res(existsNumber === 1)
154 })
155 })
156 }
157
ecb4e35f
C
158 static get Instance () {
159 return this.instance || (this.instance = new this())
160 }
161}
162
163// ---------------------------------------------------------------------------
164
165export {
166 Redis
167}