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 { CONFIG, USER_PASSWORD_RESET_LIFETIME, USER_EMAIL_VERIFY_LIFETIME, VIDEO_VIEW_LIFETIME } from '../initializers'
15 private static instance: Redis
16 private initialized = false
17 private client: RedisClient
18 private prefix: string
20 private constructor () {}
23 // Already initialized
24 if (this.initialized === true) return
25 this.initialized = true
27 this.client = createClient(Redis.getRedisClient())
29 this.client.on('error', err => {
30 logger.error('Error in Redis client.', { err })
34 if (CONFIG.REDIS.AUTH) {
35 this.client.auth(CONFIG.REDIS.AUTH)
38 this.prefix = 'redis-' + CONFIG.WEBSERVER.HOST + '-'
41 static getRedisClient () {
42 return Object.assign({},
43 (CONFIG.REDIS.AUTH && CONFIG.REDIS.AUTH != null) ? { password: CONFIG.REDIS.AUTH } : {},
44 (CONFIG.REDIS.DB) ? { db: CONFIG.REDIS.DB } : {},
45 (CONFIG.REDIS.HOSTNAME && CONFIG.REDIS.PORT) ?
46 { host: CONFIG.REDIS.HOSTNAME, port: CONFIG.REDIS.PORT } :
47 { path: CONFIG.REDIS.SOCKET }
51 /************* Forgot password *************/
53 async setResetPasswordVerificationString (userId: number) {
54 const generatedString = await generateRandomString(32)
56 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_RESET_LIFETIME)
58 return generatedString
61 async getResetPasswordLink (userId: number) {
62 return this.getValue(this.generateResetPasswordKey(userId))
65 /************* Email verification *************/
67 async setVerifyEmailVerificationString (userId: number) {
68 const generatedString = await generateRandomString(32)
70 await this.setValue(this.generateVerifyEmailKey(userId), generatedString, USER_EMAIL_VERIFY_LIFETIME)
72 return generatedString
75 async getVerifyEmailLink (userId: number) {
76 return this.getValue(this.generateVerifyEmailKey(userId))
79 /************* Views per IP *************/
81 setIPVideoView (ip: string, videoUUID: string) {
82 return this.setValue(this.generateViewKey(ip, videoUUID), '1', VIDEO_VIEW_LIFETIME)
85 async isVideoIPViewExists (ip: string, videoUUID: string) {
86 return this.exists(this.generateViewKey(ip, videoUUID))
89 /************* API cache *************/
91 async getCachedRoute (req: express.Request) {
92 const cached = await this.getObject(this.generateCachedRouteKey(req))
94 return cached as CachedRoute
97 setCachedRoute (req: express.Request, body: any, lifetime: number, contentType?: string, statusCode?: number) {
98 const cached: CachedRoute = Object.assign({}, {
101 (contentType) ? { contentType } : null,
102 (statusCode) ? { statusCode: statusCode.toString() } : null
105 return this.setObject(this.generateCachedRouteKey(req), cached, lifetime)
108 /************* Video views *************/
110 addVideoView (videoId: number) {
111 const keyIncr = this.generateVideoViewKey(videoId)
112 const keySet = this.generateVideosViewKey()
115 this.addToSet(keySet, videoId.toString()),
116 this.increment(keyIncr)
120 async getVideoViews (videoId: number, hour: number) {
121 const key = this.generateVideoViewKey(videoId, hour)
123 const valueString = await this.getValue(key)
124 return parseInt(valueString, 10)
127 async getVideosIdViewed (hour: number) {
128 const key = this.generateVideosViewKey(hour)
130 const stringIds = await this.getSet(key)
131 return stringIds.map(s => parseInt(s, 10))
134 deleteVideoViews (videoId: number, hour: number) {
135 const keySet = this.generateVideosViewKey(hour)
136 const keyIncr = this.generateVideoViewKey(videoId, hour)
139 this.deleteFromSet(keySet, videoId.toString()),
140 this.deleteKey(keyIncr)
144 /************* Keys generation *************/
146 generateCachedRouteKey (req: express.Request) {
147 return req.method + '-' + req.originalUrl
150 private generateVideosViewKey (hour?: number) {
151 if (!hour) hour = new Date().getHours()
153 return `videos-view-h${hour}`
156 private generateVideoViewKey (videoId: number, hour?: number) {
157 if (!hour) hour = new Date().getHours()
159 return `video-view-${videoId}-h${hour}`
162 private generateResetPasswordKey (userId: number) {
163 return 'reset-password-' + userId
166 private generateVerifyEmailKey (userId: number) {
167 return 'verify-email-' + userId
170 private generateViewKey (ip: string, videoUUID: string) {
171 return videoUUID + '-' + ip
174 /************* Redis helpers *************/
176 private getValue (key: string) {
177 return new Promise<string>((res, rej) => {
178 this.client.get(this.prefix + key, (err, value) => {
179 if (err) return rej(err)
186 private getSet (key: string) {
187 return new Promise<string[]>((res, rej) => {
188 this.client.smembers(this.prefix + key, (err, value) => {
189 if (err) return rej(err)
196 private addToSet (key: string, value: string) {
197 return new Promise<string[]>((res, rej) => {
198 this.client.sadd(this.prefix + key, value, err => err ? rej(err) : res())
202 private deleteFromSet (key: string, value: string) {
203 return new Promise<void>((res, rej) => {
204 this.client.srem(this.prefix + key, value, err => err ? rej(err) : res())
208 private deleteKey (key: string) {
209 return new Promise<void>((res, rej) => {
210 this.client.del(this.prefix + key, err => err ? rej(err) : res())
214 private deleteFieldInHash (key: string, field: string) {
215 return new Promise<void>((res, rej) => {
216 this.client.hdel(this.prefix + key, field, err => err ? rej(err) : res())
220 private setValue (key: string, value: string, expirationMilliseconds: number) {
221 return new Promise<void>((res, rej) => {
222 this.client.set(this.prefix + key, value, 'PX', expirationMilliseconds, (err, ok) => {
223 if (err) return rej(err)
225 if (ok !== 'OK') return rej(new Error('Redis set result is not OK.'))
232 private setObject (key: string, obj: { [ id: string ]: string }, expirationMilliseconds: number) {
233 return new Promise<void>((res, rej) => {
234 this.client.hmset(this.prefix + key, obj, (err, ok) => {
235 if (err) return rej(err)
236 if (!ok) return rej(new Error('Redis mset result is not OK.'))
238 this.client.pexpire(this.prefix + key, expirationMilliseconds, (err, ok) => {
239 if (err) return rej(err)
240 if (!ok) return rej(new Error('Redis expiration result is not OK.'))
248 private getObject (key: string) {
249 return new Promise<{ [ id: string ]: string }>((res, rej) => {
250 this.client.hgetall(this.prefix + key, (err, value) => {
251 if (err) return rej(err)
258 private setValueInHash (key: string, field: string, value: string) {
259 return new Promise<void>((res, rej) => {
260 this.client.hset(this.prefix + key, field, value, (err) => {
261 if (err) return rej(err)
268 private increment (key: string) {
269 return new Promise<number>((res, rej) => {
270 this.client.incr(this.prefix + key, (err, value) => {
271 if (err) return rej(err)
278 private exists (key: string) {
279 return new Promise<boolean>((res, rej) => {
280 this.client.exists(this.prefix + key, (err, existsNumber) => {
281 if (err) return rej(err)
283 return res(existsNumber === 1)
288 static get Instance () {
289 return this.instance || (this.instance = new this())
293 // ---------------------------------------------------------------------------