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