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