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({
28 host: CONFIG.REDIS.HOSTNAME,
29 port: CONFIG.REDIS.PORT,
33 this.client.on('error', err => {
34 logger.error('Error in Redis client.', { err })
38 if (CONFIG.REDIS.AUTH) {
39 this.client.auth(CONFIG.REDIS.AUTH)
42 this.prefix = 'redis-' + CONFIG.WEBSERVER.HOST + '-'
45 async setResetPasswordVerificationString (userId: number) {
46 const generatedString = await generateRandomString(32)
48 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_RESET_LIFETIME)
50 return generatedString
53 async getResetPasswordLink (userId: number) {
54 return this.getValue(this.generateResetPasswordKey(userId))
57 setView (ip: string, videoUUID: string) {
58 return this.setValue(this.buildViewKey(ip, videoUUID), '1', VIDEO_VIEW_LIFETIME)
61 async isViewExists (ip: string, videoUUID: string) {
62 return this.exists(this.buildViewKey(ip, videoUUID))
65 async getCachedRoute (req: express.Request) {
66 const cached = await this.getObject(this.buildCachedRouteKey(req))
68 return cached as CachedRoute
71 setCachedRoute (req: express.Request, body: any, lifetime: number, contentType?: string, statusCode?: number) {
72 const cached: CachedRoute = {
73 body: body.toString(),
75 statusCode: statusCode.toString()
78 return this.setObject(this.buildCachedRouteKey(req), cached, lifetime)
81 listJobs (jobsPrefix: string, state: string, mode: 'alpha', order: 'ASC' | 'DESC', offset: number, count: number) {
82 return new Promise<string[]>((res, rej) => {
83 this.client.sort(jobsPrefix + ':jobs:' + state, 'by', mode, order, 'LIMIT', offset.toString(), count.toString(), (err, values) => {
84 if (err) return rej(err)
91 private getValue (key: string) {
92 return new Promise<string>((res, rej) => {
93 this.client.get(this.prefix + key, (err, value) => {
94 if (err) return rej(err)
101 private setValue (key: string, value: string, expirationMilliseconds: number) {
102 return new Promise<void>((res, rej) => {
103 this.client.set(this.prefix + key, value, 'PX', expirationMilliseconds, (err, ok) => {
104 if (err) return rej(err)
106 if (ok !== 'OK') return rej(new Error('Redis set result is not OK.'))
113 private setObject (key: string, obj: { [ id: string ]: string }, expirationMilliseconds: number) {
114 return new Promise<void>((res, rej) => {
115 this.client.hmset(this.prefix + key, obj, (err, ok) => {
116 if (err) return rej(err)
117 if (!ok) return rej(new Error('Redis mset result is not OK.'))
119 this.client.pexpire(this.prefix + key, expirationMilliseconds, (err, ok) => {
120 if (err) return rej(err)
121 if (!ok) return rej(new Error('Redis expiration result is not OK.'))
129 private getObject (key: string) {
130 return new Promise<{ [ id: string ]: string }>((res, rej) => {
131 this.client.hgetall(this.prefix + key, (err, value) => {
132 if (err) return rej(err)
139 private exists (key: string) {
140 return new Promise<boolean>((res, rej) => {
141 this.client.exists(this.prefix + key, (err, existsNumber) => {
142 if (err) return rej(err)
144 return res(existsNumber === 1)
149 private generateResetPasswordKey (userId: number) {
150 return 'reset-password-' + userId
153 private buildViewKey (ip: string, videoUUID: string) {
154 return videoUUID + '-' + ip
157 private buildCachedRouteKey (req: express.Request) {
158 return req.method + '-' + req.originalUrl
161 static get Instance () {
162 return this.instance || (this.instance = new this())
166 // ---------------------------------------------------------------------------