]>
Commit | Line | Data |
---|---|---|
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 { | |
6 | CONTACT_FORM_LIFETIME, | |
7 | USER_EMAIL_VERIFY_LIFETIME, | |
8 | USER_PASSWORD_RESET_LIFETIME, | |
9 | USER_PASSWORD_CREATE_LIFETIME, | |
10 | VIDEO_VIEW_LIFETIME, | |
11 | WEBSERVER, | |
12 | TRACKER_RATE_LIMITS | |
13 | } from '../initializers/constants' | |
14 | import { CONFIG } from '../initializers/config' | |
15 | ||
16 | type CachedRoute = { | |
17 | body: string | |
18 | contentType?: string | |
19 | statusCode?: string | |
20 | } | |
21 | ||
22 | class Redis { | |
23 | ||
24 | private static instance: Redis | |
25 | private initialized = false | |
26 | private client: RedisClient | |
27 | private prefix: string | |
28 | ||
29 | private constructor () { | |
30 | } | |
31 | ||
32 | init () { | |
33 | // Already initialized | |
34 | if (this.initialized === true) return | |
35 | this.initialized = true | |
36 | ||
37 | this.client = createClient(Redis.getRedisClientOptions()) | |
38 | ||
39 | this.client.on('error', err => { | |
40 | logger.error('Error in Redis client.', { err }) | |
41 | process.exit(-1) | |
42 | }) | |
43 | ||
44 | if (CONFIG.REDIS.AUTH) { | |
45 | this.client.auth(CONFIG.REDIS.AUTH) | |
46 | } | |
47 | ||
48 | this.prefix = 'redis-' + WEBSERVER.HOST + '-' | |
49 | } | |
50 | ||
51 | static getRedisClientOptions () { | |
52 | return Object.assign({}, | |
53 | (CONFIG.REDIS.AUTH && CONFIG.REDIS.AUTH != null) ? { password: CONFIG.REDIS.AUTH } : {}, | |
54 | (CONFIG.REDIS.DB) ? { db: CONFIG.REDIS.DB } : {}, | |
55 | (CONFIG.REDIS.HOSTNAME && CONFIG.REDIS.PORT) | |
56 | ? { host: CONFIG.REDIS.HOSTNAME, port: CONFIG.REDIS.PORT } | |
57 | : { path: CONFIG.REDIS.SOCKET } | |
58 | ) | |
59 | } | |
60 | ||
61 | getClient () { | |
62 | return this.client | |
63 | } | |
64 | ||
65 | getPrefix () { | |
66 | return this.prefix | |
67 | } | |
68 | ||
69 | /* ************ Forgot password ************ */ | |
70 | ||
71 | async setResetPasswordVerificationString (userId: number) { | |
72 | const generatedString = await generateRandomString(32) | |
73 | ||
74 | await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_RESET_LIFETIME) | |
75 | ||
76 | return generatedString | |
77 | } | |
78 | ||
79 | async setCreatePasswordVerificationString (userId: number) { | |
80 | const generatedString = await generateRandomString(32) | |
81 | ||
82 | await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_CREATE_LIFETIME) | |
83 | ||
84 | return generatedString | |
85 | } | |
86 | ||
87 | async removePasswordVerificationString (userId: number) { | |
88 | return this.removeValue(this.generateResetPasswordKey(userId)) | |
89 | } | |
90 | ||
91 | async getResetPasswordLink (userId: number) { | |
92 | return this.getValue(this.generateResetPasswordKey(userId)) | |
93 | } | |
94 | ||
95 | /* ************ Email verification ************ */ | |
96 | ||
97 | async setVerifyEmailVerificationString (userId: number) { | |
98 | const generatedString = await generateRandomString(32) | |
99 | ||
100 | await this.setValue(this.generateVerifyEmailKey(userId), generatedString, USER_EMAIL_VERIFY_LIFETIME) | |
101 | ||
102 | return generatedString | |
103 | } | |
104 | ||
105 | async getVerifyEmailLink (userId: number) { | |
106 | return this.getValue(this.generateVerifyEmailKey(userId)) | |
107 | } | |
108 | ||
109 | /* ************ Contact form per IP ************ */ | |
110 | ||
111 | async setContactFormIp (ip: string) { | |
112 | return this.setValue(this.generateContactFormKey(ip), '1', CONTACT_FORM_LIFETIME) | |
113 | } | |
114 | ||
115 | async doesContactFormIpExist (ip: string) { | |
116 | return this.exists(this.generateContactFormKey(ip)) | |
117 | } | |
118 | ||
119 | /* ************ Views per IP ************ */ | |
120 | ||
121 | setIPVideoView (ip: string, videoUUID: string) { | |
122 | return this.setValue(this.generateViewKey(ip, videoUUID), '1', VIDEO_VIEW_LIFETIME) | |
123 | } | |
124 | ||
125 | async doesVideoIPViewExist (ip: string, videoUUID: string) { | |
126 | return this.exists(this.generateViewKey(ip, videoUUID)) | |
127 | } | |
128 | ||
129 | /* ************ Tracker IP block ************ */ | |
130 | ||
131 | setTrackerBlockIP (ip: string) { | |
132 | return this.setValue(this.generateTrackerBlockIPKey(ip), '1', TRACKER_RATE_LIMITS.BLOCK_IP_LIFETIME) | |
133 | } | |
134 | ||
135 | async doesTrackerBlockIPExist (ip: string) { | |
136 | return this.exists(this.generateTrackerBlockIPKey(ip)) | |
137 | } | |
138 | ||
139 | /* ************ API cache ************ */ | |
140 | ||
141 | async getCachedRoute (req: express.Request) { | |
142 | const cached = await this.getObject(this.generateCachedRouteKey(req)) | |
143 | ||
144 | return cached as CachedRoute | |
145 | } | |
146 | ||
147 | setCachedRoute (req: express.Request, body: any, lifetime: number, contentType?: string, statusCode?: number) { | |
148 | const cached: CachedRoute = Object.assign( | |
149 | {}, | |
150 | { body: body.toString() }, | |
151 | (contentType) ? { contentType } : null, | |
152 | (statusCode) ? { statusCode: statusCode.toString() } : null | |
153 | ) | |
154 | ||
155 | return this.setObject(this.generateCachedRouteKey(req), cached, lifetime) | |
156 | } | |
157 | ||
158 | /* ************ Video views ************ */ | |
159 | ||
160 | addVideoView (videoId: number) { | |
161 | const keyIncr = this.generateVideoViewKey(videoId) | |
162 | const keySet = this.generateVideosViewKey() | |
163 | ||
164 | return Promise.all([ | |
165 | this.addToSet(keySet, videoId.toString()), | |
166 | this.increment(keyIncr) | |
167 | ]) | |
168 | } | |
169 | ||
170 | async getVideoViews (videoId: number, hour: number) { | |
171 | const key = this.generateVideoViewKey(videoId, hour) | |
172 | ||
173 | const valueString = await this.getValue(key) | |
174 | const valueInt = parseInt(valueString, 10) | |
175 | ||
176 | if (isNaN(valueInt)) { | |
177 | logger.error('Cannot get videos views of video %d in hour %d: views number is NaN (%s).', videoId, hour, valueString) | |
178 | return undefined | |
179 | } | |
180 | ||
181 | return valueInt | |
182 | } | |
183 | ||
184 | async getVideosIdViewed (hour: number) { | |
185 | const key = this.generateVideosViewKey(hour) | |
186 | ||
187 | const stringIds = await this.getSet(key) | |
188 | return stringIds.map(s => parseInt(s, 10)) | |
189 | } | |
190 | ||
191 | deleteVideoViews (videoId: number, hour: number) { | |
192 | const keySet = this.generateVideosViewKey(hour) | |
193 | const keyIncr = this.generateVideoViewKey(videoId, hour) | |
194 | ||
195 | return Promise.all([ | |
196 | this.deleteFromSet(keySet, videoId.toString()), | |
197 | this.deleteKey(keyIncr) | |
198 | ]) | |
199 | } | |
200 | ||
201 | /* ************ Keys generation ************ */ | |
202 | ||
203 | generateCachedRouteKey (req: express.Request) { | |
204 | return req.method + '-' + req.originalUrl | |
205 | } | |
206 | ||
207 | private generateVideosViewKey (hour?: number) { | |
208 | if (!hour) hour = new Date().getHours() | |
209 | ||
210 | return `videos-view-h${hour}` | |
211 | } | |
212 | ||
213 | private generateVideoViewKey (videoId: number, hour?: number) { | |
214 | if (!hour) hour = new Date().getHours() | |
215 | ||
216 | return `video-view-${videoId}-h${hour}` | |
217 | } | |
218 | ||
219 | private generateResetPasswordKey (userId: number) { | |
220 | return 'reset-password-' + userId | |
221 | } | |
222 | ||
223 | private generateVerifyEmailKey (userId: number) { | |
224 | return 'verify-email-' + userId | |
225 | } | |
226 | ||
227 | private generateViewKey (ip: string, videoUUID: string) { | |
228 | return `views-${videoUUID}-${ip}` | |
229 | } | |
230 | ||
231 | private generateTrackerBlockIPKey (ip: string) { | |
232 | return `tracker-block-ip-${ip}` | |
233 | } | |
234 | ||
235 | private generateContactFormKey (ip: string) { | |
236 | return 'contact-form-' + ip | |
237 | } | |
238 | ||
239 | /* ************ Redis helpers ************ */ | |
240 | ||
241 | private getValue (key: string) { | |
242 | return new Promise<string>((res, rej) => { | |
243 | this.client.get(this.prefix + key, (err, value) => { | |
244 | if (err) return rej(err) | |
245 | ||
246 | return res(value) | |
247 | }) | |
248 | }) | |
249 | } | |
250 | ||
251 | private getSet (key: string) { | |
252 | return new Promise<string[]>((res, rej) => { | |
253 | this.client.smembers(this.prefix + key, (err, value) => { | |
254 | if (err) return rej(err) | |
255 | ||
256 | return res(value) | |
257 | }) | |
258 | }) | |
259 | } | |
260 | ||
261 | private addToSet (key: string, value: string) { | |
262 | return new Promise<string[]>((res, rej) => { | |
263 | this.client.sadd(this.prefix + key, value, err => err ? rej(err) : res()) | |
264 | }) | |
265 | } | |
266 | ||
267 | private deleteFromSet (key: string, value: string) { | |
268 | return new Promise<void>((res, rej) => { | |
269 | this.client.srem(this.prefix + key, value, err => err ? rej(err) : res()) | |
270 | }) | |
271 | } | |
272 | ||
273 | private deleteKey (key: string) { | |
274 | return new Promise<void>((res, rej) => { | |
275 | this.client.del(this.prefix + key, err => err ? rej(err) : res()) | |
276 | }) | |
277 | } | |
278 | ||
279 | private deleteFieldInHash (key: string, field: string) { | |
280 | return new Promise<void>((res, rej) => { | |
281 | this.client.hdel(this.prefix + key, field, err => err ? rej(err) : res()) | |
282 | }) | |
283 | } | |
284 | ||
285 | private setValue (key: string, value: string, expirationMilliseconds: number) { | |
286 | return new Promise<void>((res, rej) => { | |
287 | this.client.set(this.prefix + key, value, 'PX', expirationMilliseconds, (err, ok) => { | |
288 | if (err) return rej(err) | |
289 | ||
290 | if (ok !== 'OK') return rej(new Error('Redis set result is not OK.')) | |
291 | ||
292 | return res() | |
293 | }) | |
294 | }) | |
295 | } | |
296 | ||
297 | private removeValue (key: string) { | |
298 | return new Promise<void>((res, rej) => { | |
299 | this.client.del(this.prefix + key, err => { | |
300 | if (err) return rej(err) | |
301 | ||
302 | return res() | |
303 | }) | |
304 | }) | |
305 | } | |
306 | ||
307 | private setObject (key: string, obj: { [id: string]: string }, expirationMilliseconds: number) { | |
308 | return new Promise<void>((res, rej) => { | |
309 | this.client.hmset(this.prefix + key, obj, (err, ok) => { | |
310 | if (err) return rej(err) | |
311 | if (!ok) return rej(new Error('Redis mset result is not OK.')) | |
312 | ||
313 | this.client.pexpire(this.prefix + key, expirationMilliseconds, (err, ok) => { | |
314 | if (err) return rej(err) | |
315 | if (!ok) return rej(new Error('Redis expiration result is not OK.')) | |
316 | ||
317 | return res() | |
318 | }) | |
319 | }) | |
320 | }) | |
321 | } | |
322 | ||
323 | private getObject (key: string) { | |
324 | return new Promise<{ [id: string]: string }>((res, rej) => { | |
325 | this.client.hgetall(this.prefix + key, (err, value) => { | |
326 | if (err) return rej(err) | |
327 | ||
328 | return res(value) | |
329 | }) | |
330 | }) | |
331 | } | |
332 | ||
333 | private setValueInHash (key: string, field: string, value: string) { | |
334 | return new Promise<void>((res, rej) => { | |
335 | this.client.hset(this.prefix + key, field, value, (err) => { | |
336 | if (err) return rej(err) | |
337 | ||
338 | return res() | |
339 | }) | |
340 | }) | |
341 | } | |
342 | ||
343 | private increment (key: string) { | |
344 | return new Promise<number>((res, rej) => { | |
345 | this.client.incr(this.prefix + key, (err, value) => { | |
346 | if (err) return rej(err) | |
347 | ||
348 | return res(value) | |
349 | }) | |
350 | }) | |
351 | } | |
352 | ||
353 | private exists (key: string) { | |
354 | return new Promise<boolean>((res, rej) => { | |
355 | this.client.exists(this.prefix + key, (err, existsNumber) => { | |
356 | if (err) return rej(err) | |
357 | ||
358 | return res(existsNumber === 1) | |
359 | }) | |
360 | }) | |
361 | } | |
362 | ||
363 | static get Instance () { | |
364 | return this.instance || (this.instance = new this()) | |
365 | } | |
366 | } | |
367 | ||
368 | // --------------------------------------------------------------------------- | |
369 | ||
370 | export { | |
371 | Redis | |
372 | } |