]>
Commit | Line | Data |
---|---|---|
4195cd2b | 1 | import * as express from 'express' |
ecb4e35f C |
2 | import { createClient, RedisClient } from 'redis' |
3 | import { logger } from '../helpers/logger' | |
4 | import { generateRandomString } from '../helpers/utils' | |
a4101923 | 5 | import { |
a4101923 C |
6 | CONTACT_FORM_LIFETIME, |
7 | USER_EMAIL_VERIFY_LIFETIME, | |
8 | USER_PASSWORD_RESET_LIFETIME, | |
45f1bd72 | 9 | USER_PASSWORD_CREATE_LIFETIME, |
6dd9de95 | 10 | VIDEO_VIEW_LIFETIME, |
db48de85 C |
11 | WEBSERVER, |
12 | TRACKER_RATE_LIMITS | |
74dc3bca | 13 | } from '../initializers/constants' |
6dd9de95 | 14 | import { CONFIG } from '../initializers/config' |
4195cd2b C |
15 | |
16 | type CachedRoute = { | |
a1587156 | 17 | body: string |
2cebd797 C |
18 | contentType?: string |
19 | statusCode?: string | |
4195cd2b | 20 | } |
ecb4e35f C |
21 | |
22 | class Redis { | |
23 | ||
24 | private static instance: Redis | |
25 | private initialized = false | |
26 | private client: RedisClient | |
27 | private prefix: string | |
28 | ||
a1587156 C |
29 | private constructor () { |
30 | } | |
ecb4e35f C |
31 | |
32 | init () { | |
33 | // Already initialized | |
34 | if (this.initialized === true) return | |
35 | this.initialized = true | |
36 | ||
47f6409b | 37 | this.client = createClient(Redis.getRedisClientOptions()) |
ecb4e35f C |
38 | |
39 | this.client.on('error', err => { | |
d5b7d911 | 40 | logger.error('Error in Redis client.', { err }) |
ecb4e35f C |
41 | process.exit(-1) |
42 | }) | |
43 | ||
44 | if (CONFIG.REDIS.AUTH) { | |
45 | this.client.auth(CONFIG.REDIS.AUTH) | |
46 | } | |
47 | ||
6dd9de95 | 48 | this.prefix = 'redis-' + WEBSERVER.HOST + '-' |
ecb4e35f C |
49 | } |
50 | ||
47f6409b | 51 | static getRedisClientOptions () { |
19f7b248 RK |
52 | return Object.assign({}, |
53 | (CONFIG.REDIS.AUTH && CONFIG.REDIS.AUTH != null) ? { password: CONFIG.REDIS.AUTH } : {}, | |
54 | (CONFIG.REDIS.DB) ? { db: CONFIG.REDIS.DB } : {}, | |
a1587156 C |
55 | (CONFIG.REDIS.HOSTNAME && CONFIG.REDIS.PORT) |
56 | ? { host: CONFIG.REDIS.HOSTNAME, port: CONFIG.REDIS.PORT } | |
57 | : { path: CONFIG.REDIS.SOCKET } | |
19f7b248 RK |
58 | ) |
59 | } | |
60 | ||
47f6409b C |
61 | getClient () { |
62 | return this.client | |
63 | } | |
64 | ||
65 | getPrefix () { | |
66 | return this.prefix | |
67 | } | |
68 | ||
a1587156 | 69 | /* ************ Forgot password ************ */ |
6e46de09 | 70 | |
ecb4e35f C |
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 | ||
45f1bd72 JL |
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 | ||
ecb4e35f C |
84 | return generatedString |
85 | } | |
86 | ||
e9c5f123 C |
87 | async removePasswordVerificationString (userId: number) { |
88 | return this.removeValue(this.generateResetPasswordKey(userId)) | |
89 | } | |
90 | ||
ecb4e35f C |
91 | async getResetPasswordLink (userId: number) { |
92 | return this.getValue(this.generateResetPasswordKey(userId)) | |
93 | } | |
94 | ||
a1587156 | 95 | /* ************ Email verification ************ */ |
6e46de09 | 96 | |
d9eaee39 JM |
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 | ||
a1587156 | 109 | /* ************ Contact form per IP ************ */ |
a4101923 C |
110 | |
111 | async setContactFormIp (ip: string) { | |
112 | return this.setValue(this.generateContactFormKey(ip), '1', CONTACT_FORM_LIFETIME) | |
113 | } | |
114 | ||
0f6acda1 | 115 | async doesContactFormIpExist (ip: string) { |
a4101923 C |
116 | return this.exists(this.generateContactFormKey(ip)) |
117 | } | |
118 | ||
a1587156 | 119 | /* ************ Views per IP ************ */ |
6e46de09 | 120 | |
6b616860 | 121 | setIPVideoView (ip: string, videoUUID: string) { |
6e46de09 | 122 | return this.setValue(this.generateViewKey(ip, videoUUID), '1', VIDEO_VIEW_LIFETIME) |
b5c0e955 C |
123 | } |
124 | ||
0f6acda1 | 125 | async doesVideoIPViewExist (ip: string, videoUUID: string) { |
6e46de09 | 126 | return this.exists(this.generateViewKey(ip, videoUUID)) |
b5c0e955 C |
127 | } |
128 | ||
db48de85 C |
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 | ||
a1587156 | 139 | /* ************ API cache ************ */ |
6e46de09 | 140 | |
4195cd2b | 141 | async getCachedRoute (req: express.Request) { |
6e46de09 | 142 | const cached = await this.getObject(this.generateCachedRouteKey(req)) |
4195cd2b C |
143 | |
144 | return cached as CachedRoute | |
145 | } | |
146 | ||
fd4484f1 | 147 | setCachedRoute (req: express.Request, body: any, lifetime: number, contentType?: string, statusCode?: number) { |
a1587156 C |
148 | const cached: CachedRoute = Object.assign( |
149 | {}, | |
150 | { body: body.toString() }, | |
151 | (contentType) ? { contentType } : null, | |
152 | (statusCode) ? { statusCode: statusCode.toString() } : null | |
c1e791ba | 153 | ) |
4195cd2b | 154 | |
6e46de09 | 155 | return this.setObject(this.generateCachedRouteKey(req), cached, lifetime) |
4195cd2b C |
156 | } |
157 | ||
a1587156 | 158 | /* ************ Video views ************ */ |
6e46de09 | 159 | |
6b616860 C |
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) | |
6040f87d C |
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 | |
6b616860 C |
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 | ||
a1587156 | 201 | /* ************ Keys generation ************ */ |
6e46de09 C |
202 | |
203 | generateCachedRouteKey (req: express.Request) { | |
204 | return req.method + '-' + req.originalUrl | |
205 | } | |
206 | ||
207 | private generateVideosViewKey (hour?: number) { | |
6b616860 C |
208 | if (!hour) hour = new Date().getHours() |
209 | ||
210 | return `videos-view-h${hour}` | |
211 | } | |
212 | ||
6e46de09 | 213 | private generateVideoViewKey (videoId: number, hour?: number) { |
6b616860 C |
214 | if (!hour) hour = new Date().getHours() |
215 | ||
216 | return `video-view-${videoId}-h${hour}` | |
217 | } | |
218 | ||
6e46de09 | 219 | private generateResetPasswordKey (userId: number) { |
b40f0575 C |
220 | return 'reset-password-' + userId |
221 | } | |
222 | ||
6e46de09 | 223 | private generateVerifyEmailKey (userId: number) { |
d9eaee39 JM |
224 | return 'verify-email-' + userId |
225 | } | |
226 | ||
6e46de09 | 227 | private generateViewKey (ip: string, videoUUID: string) { |
a4101923 C |
228 | return `views-${videoUUID}-${ip}` |
229 | } | |
230 | ||
db48de85 C |
231 | private generateTrackerBlockIPKey (ip: string) { |
232 | return `tracker-block-ip-${ip}` | |
233 | } | |
234 | ||
a4101923 C |
235 | private generateContactFormKey (ip: string) { |
236 | return 'contact-form-' + ip | |
b40f0575 C |
237 | } |
238 | ||
a1587156 | 239 | /* ************ Redis helpers ************ */ |
b40f0575 | 240 | |
ecb4e35f C |
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 | ||
6b616860 C |
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 | ||
6e46de09 C |
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 | ||
ecb4e35f C |
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 | ||
4195cd2b | 290 | if (ok !== 'OK') return rej(new Error('Redis set result is not OK.')) |
ecb4e35f C |
291 | |
292 | return res() | |
293 | }) | |
294 | }) | |
295 | } | |
296 | ||
e9c5f123 C |
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 | ||
a1587156 | 307 | private setObject (key: string, obj: { [id: string]: string }, expirationMilliseconds: number) { |
4195cd2b C |
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) { | |
a1587156 | 324 | return new Promise<{ [id: string]: string }>((res, rej) => { |
4195cd2b C |
325 | this.client.hgetall(this.prefix + key, (err, value) => { |
326 | if (err) return rej(err) | |
327 | ||
328 | return res(value) | |
329 | }) | |
330 | }) | |
331 | } | |
332 | ||
6e46de09 C |
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 | ||
6b616860 C |
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 | ||
b5c0e955 C |
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 | ||
ecb4e35f C |
363 | static get Instance () { |
364 | return this.instance || (this.instance = new this()) | |
365 | } | |
366 | } | |
367 | ||
368 | // --------------------------------------------------------------------------- | |
369 | ||
370 | export { | |
371 | Redis | |
372 | } |