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, 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 async setResetPasswordVerificationString (userId: number) {
52 const generatedString = await generateRandomString(32)
54 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_RESET_LIFETIME)
56 return generatedString
59 async getResetPasswordLink (userId: number) {
60 return this.getValue(this.generateResetPasswordKey(userId))
63 setView (ip: string, videoUUID: string) {
64 return this.setValue(this.buildViewKey(ip, videoUUID), '1', VIDEO_VIEW_LIFETIME)
67 async isViewExists (ip: string, videoUUID: string) {
68 return this.exists(this.buildViewKey(ip, videoUUID))
71 async getCachedRoute (req: express.Request) {
72 const cached = await this.getObject(this.buildCachedRouteKey(req))
74 return cached as CachedRoute
77 setCachedRoute (req: express.Request, body: any, lifetime: number, contentType?: string, statusCode?: number) {
78 const cached: CachedRoute = {
79 body: body.toString(),
81 statusCode: statusCode.toString()
84 return this.setObject(this.buildCachedRouteKey(req), cached, lifetime)
87 generateResetPasswordKey (userId: number) {
88 return 'reset-password-' + userId
91 buildViewKey (ip: string, videoUUID: string) {
92 return videoUUID + '-' + ip
95 buildCachedRouteKey (req: express.Request) {
96 return req.method + '-' + req.originalUrl
99 private getValue (key: string) {
100 return new Promise<string>((res, rej) => {
101 this.client.get(this.prefix + key, (err, value) => {
102 if (err) return rej(err)
109 private setValue (key: string, value: string, expirationMilliseconds: number) {
110 return new Promise<void>((res, rej) => {
111 this.client.set(this.prefix + key, value, 'PX', expirationMilliseconds, (err, ok) => {
112 if (err) return rej(err)
114 if (ok !== 'OK') return rej(new Error('Redis set result is not OK.'))
121 private setObject (key: string, obj: { [ id: string ]: string }, expirationMilliseconds: number) {
122 return new Promise<void>((res, rej) => {
123 this.client.hmset(this.prefix + key, obj, (err, ok) => {
124 if (err) return rej(err)
125 if (!ok) return rej(new Error('Redis mset result is not OK.'))
127 this.client.pexpire(this.prefix + key, expirationMilliseconds, (err, ok) => {
128 if (err) return rej(err)
129 if (!ok) return rej(new Error('Redis expiration result is not OK.'))
137 private getObject (key: string) {
138 return new Promise<{ [ id: string ]: string }>((res, rej) => {
139 this.client.hgetall(this.prefix + key, (err, value) => {
140 if (err) return rej(err)
147 private exists (key: string) {
148 return new Promise<boolean>((res, rej) => {
149 this.client.exists(this.prefix + key, (err, existsNumber) => {
150 if (err) return rej(err)
152 return res(existsNumber === 1)
157 static get Instance () {
158 return this.instance || (this.instance = new this())
162 // ---------------------------------------------------------------------------