1 import * as express from 'express'
2 import { createClient, RedisClient } from 'redis'
3 import { logger } from '../helpers/logger'
4 import { generateRandomString } from '../helpers/utils'
8 USER_EMAIL_VERIFY_LIFETIME,
9 USER_PASSWORD_RESET_LIFETIME,
11 } from '../initializers'
21 private static instance: Redis
22 private initialized = false
23 private client: RedisClient
24 private prefix: string
26 private constructor () {}
29 // Already initialized
30 if (this.initialized === true) return
31 this.initialized = true
33 this.client = createClient(Redis.getRedisClient())
35 this.client.on('error', err => {
36 logger.error('Error in Redis client.', { err })
40 if (CONFIG.REDIS.AUTH) {
41 this.client.auth(CONFIG.REDIS.AUTH)
44 this.prefix = 'redis-' + CONFIG.WEBSERVER.HOST + '-'
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 }
57 /************* Forgot password *************/
59 async setResetPasswordVerificationString (userId: number) {
60 const generatedString = await generateRandomString(32)
62 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_RESET_LIFETIME)
64 return generatedString
67 async getResetPasswordLink (userId: number) {
68 return this.getValue(this.generateResetPasswordKey(userId))
71 /************* Email verification *************/
73 async setVerifyEmailVerificationString (userId: number) {
74 const generatedString = await generateRandomString(32)
76 await this.setValue(this.generateVerifyEmailKey(userId), generatedString, USER_EMAIL_VERIFY_LIFETIME)
78 return generatedString
81 async getVerifyEmailLink (userId: number) {
82 return this.getValue(this.generateVerifyEmailKey(userId))
85 /************* Contact form per IP *************/
87 async setContactFormIp (ip: string) {
88 return this.setValue(this.generateContactFormKey(ip), '1', CONTACT_FORM_LIFETIME)
91 async doesContactFormIpExist (ip: string) {
92 return this.exists(this.generateContactFormKey(ip))
95 /************* Views per IP *************/
97 setIPVideoView (ip: string, videoUUID: string) {
98 return this.setValue(this.generateViewKey(ip, videoUUID), '1', VIDEO_VIEW_LIFETIME)
101 async doesVideoIPViewExist (ip: string, videoUUID: string) {
102 return this.exists(this.generateViewKey(ip, videoUUID))
105 /************* API cache *************/
107 async getCachedRoute (req: express.Request) {
108 const cached = await this.getObject(this.generateCachedRouteKey(req))
110 return cached as CachedRoute
113 setCachedRoute (req: express.Request, body: any, lifetime: number, contentType?: string, statusCode?: number) {
114 const cached: CachedRoute = Object.assign({}, {
115 body: body.toString()
117 (contentType) ? { contentType } : null,
118 (statusCode) ? { statusCode: statusCode.toString() } : null
121 return this.setObject(this.generateCachedRouteKey(req), cached, lifetime)
124 /************* Video views *************/
126 addVideoView (videoId: number) {
127 const keyIncr = this.generateVideoViewKey(videoId)
128 const keySet = this.generateVideosViewKey()
131 this.addToSet(keySet, videoId.toString()),
132 this.increment(keyIncr)
136 async getVideoViews (videoId: number, hour: number) {
137 const key = this.generateVideoViewKey(videoId, hour)
139 const valueString = await this.getValue(key)
140 const valueInt = parseInt(valueString, 10)
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)
150 async getVideosIdViewed (hour: number) {
151 const key = this.generateVideosViewKey(hour)
153 const stringIds = await this.getSet(key)
154 return stringIds.map(s => parseInt(s, 10))
157 deleteVideoViews (videoId: number, hour: number) {
158 const keySet = this.generateVideosViewKey(hour)
159 const keyIncr = this.generateVideoViewKey(videoId, hour)
162 this.deleteFromSet(keySet, videoId.toString()),
163 this.deleteKey(keyIncr)
167 /************* Keys generation *************/
169 generateCachedRouteKey (req: express.Request) {
170 return req.method + '-' + req.originalUrl
173 private generateVideosViewKey (hour?: number) {
174 if (!hour) hour = new Date().getHours()
176 return `videos-view-h${hour}`
179 private generateVideoViewKey (videoId: number, hour?: number) {
180 if (!hour) hour = new Date().getHours()
182 return `video-view-${videoId}-h${hour}`
185 private generateResetPasswordKey (userId: number) {
186 return 'reset-password-' + userId
189 private generateVerifyEmailKey (userId: number) {
190 return 'verify-email-' + userId
193 private generateViewKey (ip: string, videoUUID: string) {
194 return `views-${videoUUID}-${ip}`
197 private generateContactFormKey (ip: string) {
198 return 'contact-form-' + ip
201 /************* Redis helpers *************/
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)
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)
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())
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())
235 private deleteKey (key: string) {
236 return new Promise<void>((res, rej) => {
237 this.client.del(this.prefix + key, err => err ? rej(err) : res())
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())
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)
252 if (ok !== 'OK') return rej(new Error('Redis set result is not OK.'))
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.'))
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.'))
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)
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)
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)
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)
310 return res(existsNumber === 1)
315 static get Instance () {
316 return this.instance || (this.instance = new this())
320 // ---------------------------------------------------------------------------