]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/redis.ts
Refractor activities sending
[github/Chocobozzz/PeerTube.git] / server / lib / redis.ts
1 import * as express from 'express'
2 import { createClient, RedisClient } from 'redis'
3 import { logger } from '../helpers/logger'
4 import { generateRandomString } from '../helpers/utils'
5 import { CONFIG, USER_PASSWORD_RESET_LIFETIME, USER_EMAIL_VERIFY_LIFETIME, VIDEO_VIEW_LIFETIME } from '../initializers'
6
7 type CachedRoute = {
8 body: string,
9 contentType?: string
10 statusCode?: string
11 }
12
13 class 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
27 this.client = createClient(Redis.getRedisClient())
28
29 this.client.on('error', err => {
30 logger.error('Error in Redis client.', { err })
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
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
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
63 async setVerifyEmailVerificationString (userId: number) {
64 const generatedString = await generateRandomString(32)
65
66 await this.setValue(this.generateVerifyEmailKey(userId), generatedString, USER_EMAIL_VERIFY_LIFETIME)
67
68 return generatedString
69 }
70
71 async getVerifyEmailLink (userId: number) {
72 return this.getValue(this.generateVerifyEmailKey(userId))
73 }
74
75 setIPVideoView (ip: string, videoUUID: string) {
76 return this.setValue(this.buildViewKey(ip, videoUUID), '1', VIDEO_VIEW_LIFETIME)
77 }
78
79 async isVideoIPViewExists (ip: string, videoUUID: string) {
80 return this.exists(this.buildViewKey(ip, videoUUID))
81 }
82
83 async getCachedRoute (req: express.Request) {
84 const cached = await this.getObject(this.buildCachedRouteKey(req))
85
86 return cached as CachedRoute
87 }
88
89 setCachedRoute (req: express.Request, body: any, lifetime: number, contentType?: string, statusCode?: number) {
90 const cached: CachedRoute = Object.assign({}, {
91 body: body.toString()
92 },
93 (contentType) ? { contentType } : null,
94 (statusCode) ? { statusCode: statusCode.toString() } : null
95 )
96
97 return this.setObject(this.buildCachedRouteKey(req), cached, lifetime)
98 }
99
100 addVideoView (videoId: number) {
101 const keyIncr = this.generateVideoViewKey(videoId)
102 const keySet = this.generateVideosViewKey()
103
104 return Promise.all([
105 this.addToSet(keySet, videoId.toString()),
106 this.increment(keyIncr)
107 ])
108 }
109
110 async getVideoViews (videoId: number, hour: number) {
111 const key = this.generateVideoViewKey(videoId, hour)
112
113 const valueString = await this.getValue(key)
114 return parseInt(valueString, 10)
115 }
116
117 async getVideosIdViewed (hour: number) {
118 const key = this.generateVideosViewKey(hour)
119
120 const stringIds = await this.getSet(key)
121 return stringIds.map(s => parseInt(s, 10))
122 }
123
124 deleteVideoViews (videoId: number, hour: number) {
125 const keySet = this.generateVideosViewKey(hour)
126 const keyIncr = this.generateVideoViewKey(videoId, hour)
127
128 return Promise.all([
129 this.deleteFromSet(keySet, videoId.toString()),
130 this.deleteKey(keyIncr)
131 ])
132 }
133
134 generateVideosViewKey (hour?: number) {
135 if (!hour) hour = new Date().getHours()
136
137 return `videos-view-h${hour}`
138 }
139
140 generateVideoViewKey (videoId: number, hour?: number) {
141 if (!hour) hour = new Date().getHours()
142
143 return `video-view-${videoId}-h${hour}`
144 }
145
146 generateResetPasswordKey (userId: number) {
147 return 'reset-password-' + userId
148 }
149
150 generateVerifyEmailKey (userId: number) {
151 return 'verify-email-' + userId
152 }
153
154 buildViewKey (ip: string, videoUUID: string) {
155 return videoUUID + '-' + ip
156 }
157
158 buildCachedRouteKey (req: express.Request) {
159 return req.method + '-' + req.originalUrl
160 }
161
162 private getValue (key: string) {
163 return new Promise<string>((res, rej) => {
164 this.client.get(this.prefix + key, (err, value) => {
165 if (err) return rej(err)
166
167 return res(value)
168 })
169 })
170 }
171
172 private getSet (key: string) {
173 return new Promise<string[]>((res, rej) => {
174 this.client.smembers(this.prefix + key, (err, value) => {
175 if (err) return rej(err)
176
177 return res(value)
178 })
179 })
180 }
181
182 private addToSet (key: string, value: string) {
183 return new Promise<string[]>((res, rej) => {
184 this.client.sadd(this.prefix + key, value, err => err ? rej(err) : res())
185 })
186 }
187
188 private deleteFromSet (key: string, value: string) {
189 return new Promise<void>((res, rej) => {
190 this.client.srem(this.prefix + key, value, err => err ? rej(err) : res())
191 })
192 }
193
194 private deleteKey (key: string) {
195 return new Promise<void>((res, rej) => {
196 this.client.del(this.prefix + key, err => err ? rej(err) : res())
197 })
198 }
199
200 private setValue (key: string, value: string, expirationMilliseconds: number) {
201 return new Promise<void>((res, rej) => {
202 this.client.set(this.prefix + key, value, 'PX', expirationMilliseconds, (err, ok) => {
203 if (err) return rej(err)
204
205 if (ok !== 'OK') return rej(new Error('Redis set result is not OK.'))
206
207 return res()
208 })
209 })
210 }
211
212 private setObject (key: string, obj: { [ id: string ]: string }, expirationMilliseconds: number) {
213 return new Promise<void>((res, rej) => {
214 this.client.hmset(this.prefix + key, obj, (err, ok) => {
215 if (err) return rej(err)
216 if (!ok) return rej(new Error('Redis mset result is not OK.'))
217
218 this.client.pexpire(this.prefix + key, expirationMilliseconds, (err, ok) => {
219 if (err) return rej(err)
220 if (!ok) return rej(new Error('Redis expiration result is not OK.'))
221
222 return res()
223 })
224 })
225 })
226 }
227
228 private getObject (key: string) {
229 return new Promise<{ [ id: string ]: string }>((res, rej) => {
230 this.client.hgetall(this.prefix + key, (err, value) => {
231 if (err) return rej(err)
232
233 return res(value)
234 })
235 })
236 }
237
238 private increment (key: string) {
239 return new Promise<number>((res, rej) => {
240 this.client.incr(this.prefix + key, (err, value) => {
241 if (err) return rej(err)
242
243 return res(value)
244 })
245 })
246 }
247
248 private exists (key: string) {
249 return new Promise<boolean>((res, rej) => {
250 this.client.exists(this.prefix + key, (err, existsNumber) => {
251 if (err) return rej(err)
252
253 return res(existsNumber === 1)
254 })
255 })
256 }
257
258 static get Instance () {
259 return this.instance || (this.instance = new this())
260 }
261 }
262
263 // ---------------------------------------------------------------------------
264
265 export {
266 Redis
267 }