1 import * as express from 'express'
2 import { createClient, RedisClient } from 'redis'
3 import { logger } from '../helpers/logger'
4 import { generateRandomString } from '../helpers/utils'
7 USER_EMAIL_VERIFY_LIFETIME,
8 USER_PASSWORD_RESET_LIFETIME,
9 USER_PASSWORD_CREATE_LIFETIME,
12 } from '../initializers/constants'
13 import { CONFIG } from '../initializers/config'
23 private static instance: Redis
24 private initialized = false
25 private client: RedisClient
26 private prefix: string
28 private constructor () {
32 // Already initialized
33 if (this.initialized === true) return
34 this.initialized = true
36 this.client = createClient(Redis.getRedisClientOptions())
38 this.client.on('error', err => {
39 logger.error('Error in Redis client.', { err })
43 if (CONFIG.REDIS.AUTH) {
44 this.client.auth(CONFIG.REDIS.AUTH)
47 this.prefix = 'redis-' + WEBSERVER.HOST + '-'
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 }
68 /* ************ Forgot password ************ */
70 async setResetPasswordVerificationString (userId: number) {
71 const generatedString = await generateRandomString(32)
73 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_RESET_LIFETIME)
75 return generatedString
78 async setCreatePasswordVerificationString (userId: number) {
79 const generatedString = await generateRandomString(32)
81 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_CREATE_LIFETIME)
83 return generatedString
86 async getResetPasswordLink (userId: number) {
87 return this.getValue(this.generateResetPasswordKey(userId))
90 /* ************ Email verification ************ */
92 async setVerifyEmailVerificationString (userId: number) {
93 const generatedString = await generateRandomString(32)
95 await this.setValue(this.generateVerifyEmailKey(userId), generatedString, USER_EMAIL_VERIFY_LIFETIME)
97 return generatedString
100 async getVerifyEmailLink (userId: number) {
101 return this.getValue(this.generateVerifyEmailKey(userId))
104 /* ************ Contact form per IP ************ */
106 async setContactFormIp (ip: string) {
107 return this.setValue(this.generateContactFormKey(ip), '1', CONTACT_FORM_LIFETIME)
110 async doesContactFormIpExist (ip: string) {
111 return this.exists(this.generateContactFormKey(ip))
114 /* ************ Views per IP ************ */
116 setIPVideoView (ip: string, videoUUID: string) {
117 return this.setValue(this.generateViewKey(ip, videoUUID), '1', VIDEO_VIEW_LIFETIME)
120 async doesVideoIPViewExist (ip: string, videoUUID: string) {
121 return this.exists(this.generateViewKey(ip, videoUUID))
124 /* ************ API cache ************ */
126 async getCachedRoute (req: express.Request) {
127 const cached = await this.getObject(this.generateCachedRouteKey(req))
129 return cached as CachedRoute
132 setCachedRoute (req: express.Request, body: any, lifetime: number, contentType?: string, statusCode?: number) {
133 const cached: CachedRoute = Object.assign(
135 { body: body.toString() },
136 (contentType) ? { contentType } : null,
137 (statusCode) ? { statusCode: statusCode.toString() } : null
140 return this.setObject(this.generateCachedRouteKey(req), cached, lifetime)
143 /* ************ Video views ************ */
145 addVideoView (videoId: number) {
146 const keyIncr = this.generateVideoViewKey(videoId)
147 const keySet = this.generateVideosViewKey()
150 this.addToSet(keySet, videoId.toString()),
151 this.increment(keyIncr)
155 async getVideoViews (videoId: number, hour: number) {
156 const key = this.generateVideoViewKey(videoId, hour)
158 const valueString = await this.getValue(key)
159 const valueInt = parseInt(valueString, 10)
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)
169 async getVideosIdViewed (hour: number) {
170 const key = this.generateVideosViewKey(hour)
172 const stringIds = await this.getSet(key)
173 return stringIds.map(s => parseInt(s, 10))
176 deleteVideoViews (videoId: number, hour: number) {
177 const keySet = this.generateVideosViewKey(hour)
178 const keyIncr = this.generateVideoViewKey(videoId, hour)
181 this.deleteFromSet(keySet, videoId.toString()),
182 this.deleteKey(keyIncr)
186 /* ************ Keys generation ************ */
188 generateCachedRouteKey (req: express.Request) {
189 return req.method + '-' + req.originalUrl
192 private generateVideosViewKey (hour?: number) {
193 if (!hour) hour = new Date().getHours()
195 return `videos-view-h${hour}`
198 private generateVideoViewKey (videoId: number, hour?: number) {
199 if (!hour) hour = new Date().getHours()
201 return `video-view-${videoId}-h${hour}`
204 private generateResetPasswordKey (userId: number) {
205 return 'reset-password-' + userId
208 private generateVerifyEmailKey (userId: number) {
209 return 'verify-email-' + userId
212 private generateViewKey (ip: string, videoUUID: string) {
213 return `views-${videoUUID}-${ip}`
216 private generateContactFormKey (ip: string) {
217 return 'contact-form-' + ip
220 /* ************ Redis helpers ************ */
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)
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)
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())
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())
254 private deleteKey (key: string) {
255 return new Promise<void>((res, rej) => {
256 this.client.del(this.prefix + key, err => err ? rej(err) : res())
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())
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)
271 if (ok !== 'OK') return rej(new Error('Redis set result is not OK.'))
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.'))
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.'))
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)
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)
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)
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)
329 return res(existsNumber === 1)
334 static get Instance () {
335 return this.instance || (this.instance = new this())
339 // ---------------------------------------------------------------------------