]>
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 | ||
87 | async getResetPasswordLink (userId: number) { | |
88 | return this.getValue(this.generateResetPasswordKey(userId)) | |
89 | } | |
90 | ||
a1587156 | 91 | /* ************ Email verification ************ */ |
6e46de09 | 92 | |
d9eaee39 JM |
93 | async setVerifyEmailVerificationString (userId: number) { |
94 | const generatedString = await generateRandomString(32) | |
95 | ||
96 | await this.setValue(this.generateVerifyEmailKey(userId), generatedString, USER_EMAIL_VERIFY_LIFETIME) | |
97 | ||
98 | return generatedString | |
99 | } | |
100 | ||
101 | async getVerifyEmailLink (userId: number) { | |
102 | return this.getValue(this.generateVerifyEmailKey(userId)) | |
103 | } | |
104 | ||
a1587156 | 105 | /* ************ Contact form per IP ************ */ |
a4101923 C |
106 | |
107 | async setContactFormIp (ip: string) { | |
108 | return this.setValue(this.generateContactFormKey(ip), '1', CONTACT_FORM_LIFETIME) | |
109 | } | |
110 | ||
0f6acda1 | 111 | async doesContactFormIpExist (ip: string) { |
a4101923 C |
112 | return this.exists(this.generateContactFormKey(ip)) |
113 | } | |
114 | ||
a1587156 | 115 | /* ************ Views per IP ************ */ |
6e46de09 | 116 | |
6b616860 | 117 | setIPVideoView (ip: string, videoUUID: string) { |
6e46de09 | 118 | return this.setValue(this.generateViewKey(ip, videoUUID), '1', VIDEO_VIEW_LIFETIME) |
b5c0e955 C |
119 | } |
120 | ||
0f6acda1 | 121 | async doesVideoIPViewExist (ip: string, videoUUID: string) { |
6e46de09 | 122 | return this.exists(this.generateViewKey(ip, videoUUID)) |
b5c0e955 C |
123 | } |
124 | ||
db48de85 C |
125 | /* ************ Tracker IP block ************ */ |
126 | ||
127 | setTrackerBlockIP (ip: string) { | |
128 | return this.setValue(this.generateTrackerBlockIPKey(ip), '1', TRACKER_RATE_LIMITS.BLOCK_IP_LIFETIME) | |
129 | } | |
130 | ||
131 | async doesTrackerBlockIPExist (ip: string) { | |
132 | return this.exists(this.generateTrackerBlockIPKey(ip)) | |
133 | } | |
134 | ||
a1587156 | 135 | /* ************ API cache ************ */ |
6e46de09 | 136 | |
4195cd2b | 137 | async getCachedRoute (req: express.Request) { |
6e46de09 | 138 | const cached = await this.getObject(this.generateCachedRouteKey(req)) |
4195cd2b C |
139 | |
140 | return cached as CachedRoute | |
141 | } | |
142 | ||
fd4484f1 | 143 | setCachedRoute (req: express.Request, body: any, lifetime: number, contentType?: string, statusCode?: number) { |
a1587156 C |
144 | const cached: CachedRoute = Object.assign( |
145 | {}, | |
146 | { body: body.toString() }, | |
147 | (contentType) ? { contentType } : null, | |
148 | (statusCode) ? { statusCode: statusCode.toString() } : null | |
c1e791ba | 149 | ) |
4195cd2b | 150 | |
6e46de09 | 151 | return this.setObject(this.generateCachedRouteKey(req), cached, lifetime) |
4195cd2b C |
152 | } |
153 | ||
a1587156 | 154 | /* ************ Video views ************ */ |
6e46de09 | 155 | |
6b616860 C |
156 | addVideoView (videoId: number) { |
157 | const keyIncr = this.generateVideoViewKey(videoId) | |
158 | const keySet = this.generateVideosViewKey() | |
159 | ||
160 | return Promise.all([ | |
161 | this.addToSet(keySet, videoId.toString()), | |
162 | this.increment(keyIncr) | |
163 | ]) | |
164 | } | |
165 | ||
166 | async getVideoViews (videoId: number, hour: number) { | |
167 | const key = this.generateVideoViewKey(videoId, hour) | |
168 | ||
169 | const valueString = await this.getValue(key) | |
6040f87d C |
170 | const valueInt = parseInt(valueString, 10) |
171 | ||
172 | if (isNaN(valueInt)) { | |
173 | logger.error('Cannot get videos views of video %d in hour %d: views number is NaN (%s).', videoId, hour, valueString) | |
174 | return undefined | |
175 | } | |
176 | ||
177 | return valueInt | |
6b616860 C |
178 | } |
179 | ||
180 | async getVideosIdViewed (hour: number) { | |
181 | const key = this.generateVideosViewKey(hour) | |
182 | ||
183 | const stringIds = await this.getSet(key) | |
184 | return stringIds.map(s => parseInt(s, 10)) | |
185 | } | |
186 | ||
187 | deleteVideoViews (videoId: number, hour: number) { | |
188 | const keySet = this.generateVideosViewKey(hour) | |
189 | const keyIncr = this.generateVideoViewKey(videoId, hour) | |
190 | ||
191 | return Promise.all([ | |
192 | this.deleteFromSet(keySet, videoId.toString()), | |
193 | this.deleteKey(keyIncr) | |
194 | ]) | |
195 | } | |
196 | ||
a1587156 | 197 | /* ************ Keys generation ************ */ |
6e46de09 C |
198 | |
199 | generateCachedRouteKey (req: express.Request) { | |
200 | return req.method + '-' + req.originalUrl | |
201 | } | |
202 | ||
203 | private generateVideosViewKey (hour?: number) { | |
6b616860 C |
204 | if (!hour) hour = new Date().getHours() |
205 | ||
206 | return `videos-view-h${hour}` | |
207 | } | |
208 | ||
6e46de09 | 209 | private generateVideoViewKey (videoId: number, hour?: number) { |
6b616860 C |
210 | if (!hour) hour = new Date().getHours() |
211 | ||
212 | return `video-view-${videoId}-h${hour}` | |
213 | } | |
214 | ||
6e46de09 | 215 | private generateResetPasswordKey (userId: number) { |
b40f0575 C |
216 | return 'reset-password-' + userId |
217 | } | |
218 | ||
6e46de09 | 219 | private generateVerifyEmailKey (userId: number) { |
d9eaee39 JM |
220 | return 'verify-email-' + userId |
221 | } | |
222 | ||
6e46de09 | 223 | private generateViewKey (ip: string, videoUUID: string) { |
a4101923 C |
224 | return `views-${videoUUID}-${ip}` |
225 | } | |
226 | ||
db48de85 C |
227 | private generateTrackerBlockIPKey (ip: string) { |
228 | return `tracker-block-ip-${ip}` | |
229 | } | |
230 | ||
a4101923 C |
231 | private generateContactFormKey (ip: string) { |
232 | return 'contact-form-' + ip | |
b40f0575 C |
233 | } |
234 | ||
a1587156 | 235 | /* ************ Redis helpers ************ */ |
b40f0575 | 236 | |
ecb4e35f C |
237 | private getValue (key: string) { |
238 | return new Promise<string>((res, rej) => { | |
239 | this.client.get(this.prefix + key, (err, value) => { | |
240 | if (err) return rej(err) | |
241 | ||
242 | return res(value) | |
243 | }) | |
244 | }) | |
245 | } | |
246 | ||
6b616860 C |
247 | private getSet (key: string) { |
248 | return new Promise<string[]>((res, rej) => { | |
249 | this.client.smembers(this.prefix + key, (err, value) => { | |
250 | if (err) return rej(err) | |
251 | ||
252 | return res(value) | |
253 | }) | |
254 | }) | |
255 | } | |
256 | ||
257 | private addToSet (key: string, value: string) { | |
258 | return new Promise<string[]>((res, rej) => { | |
259 | this.client.sadd(this.prefix + key, value, err => err ? rej(err) : res()) | |
260 | }) | |
261 | } | |
262 | ||
263 | private deleteFromSet (key: string, value: string) { | |
264 | return new Promise<void>((res, rej) => { | |
265 | this.client.srem(this.prefix + key, value, err => err ? rej(err) : res()) | |
266 | }) | |
267 | } | |
268 | ||
269 | private deleteKey (key: string) { | |
270 | return new Promise<void>((res, rej) => { | |
271 | this.client.del(this.prefix + key, err => err ? rej(err) : res()) | |
272 | }) | |
273 | } | |
274 | ||
6e46de09 C |
275 | private deleteFieldInHash (key: string, field: string) { |
276 | return new Promise<void>((res, rej) => { | |
277 | this.client.hdel(this.prefix + key, field, err => err ? rej(err) : res()) | |
278 | }) | |
279 | } | |
280 | ||
ecb4e35f C |
281 | private setValue (key: string, value: string, expirationMilliseconds: number) { |
282 | return new Promise<void>((res, rej) => { | |
283 | this.client.set(this.prefix + key, value, 'PX', expirationMilliseconds, (err, ok) => { | |
284 | if (err) return rej(err) | |
285 | ||
4195cd2b | 286 | if (ok !== 'OK') return rej(new Error('Redis set result is not OK.')) |
ecb4e35f C |
287 | |
288 | return res() | |
289 | }) | |
290 | }) | |
291 | } | |
292 | ||
a1587156 | 293 | private setObject (key: string, obj: { [id: string]: string }, expirationMilliseconds: number) { |
4195cd2b C |
294 | return new Promise<void>((res, rej) => { |
295 | this.client.hmset(this.prefix + key, obj, (err, ok) => { | |
296 | if (err) return rej(err) | |
297 | if (!ok) return rej(new Error('Redis mset result is not OK.')) | |
298 | ||
299 | this.client.pexpire(this.prefix + key, expirationMilliseconds, (err, ok) => { | |
300 | if (err) return rej(err) | |
301 | if (!ok) return rej(new Error('Redis expiration result is not OK.')) | |
302 | ||
303 | return res() | |
304 | }) | |
305 | }) | |
306 | }) | |
307 | } | |
308 | ||
309 | private getObject (key: string) { | |
a1587156 | 310 | return new Promise<{ [id: string]: string }>((res, rej) => { |
4195cd2b C |
311 | this.client.hgetall(this.prefix + key, (err, value) => { |
312 | if (err) return rej(err) | |
313 | ||
314 | return res(value) | |
315 | }) | |
316 | }) | |
317 | } | |
318 | ||
6e46de09 C |
319 | private setValueInHash (key: string, field: string, value: string) { |
320 | return new Promise<void>((res, rej) => { | |
321 | this.client.hset(this.prefix + key, field, value, (err) => { | |
322 | if (err) return rej(err) | |
323 | ||
324 | return res() | |
325 | }) | |
326 | }) | |
327 | } | |
328 | ||
6b616860 C |
329 | private increment (key: string) { |
330 | return new Promise<number>((res, rej) => { | |
331 | this.client.incr(this.prefix + key, (err, value) => { | |
332 | if (err) return rej(err) | |
333 | ||
334 | return res(value) | |
335 | }) | |
336 | }) | |
337 | } | |
338 | ||
b5c0e955 C |
339 | private exists (key: string) { |
340 | return new Promise<boolean>((res, rej) => { | |
341 | this.client.exists(this.prefix + key, (err, existsNumber) => { | |
342 | if (err) return rej(err) | |
343 | ||
344 | return res(existsNumber === 1) | |
345 | }) | |
346 | }) | |
347 | } | |
348 | ||
ecb4e35f C |
349 | static get Instance () { |
350 | return this.instance || (this.instance = new this()) | |
351 | } | |
352 | } | |
353 | ||
354 | // --------------------------------------------------------------------------- | |
355 | ||
356 | export { | |
357 | Redis | |
358 | } |