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, FEEDS, 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
32 this.client.on('error', err => {
33 logger.error('Error in Redis client.', { err })
37 if (CONFIG.REDIS.AUTH) {
38 this.client.auth(CONFIG.REDIS.AUTH)
41 this.prefix = 'redis-' + CONFIG.WEBSERVER.HOST + '-'
44 async setResetPasswordVerificationString (userId: number) {
45 const generatedString = await generateRandomString(32)
47 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_RESET_LIFETIME)
49 return generatedString
52 async getResetPasswordLink (userId: number) {
53 return this.getValue(this.generateResetPasswordKey(userId))
56 setView (ip: string, videoUUID: string) {
57 return this.setValue(this.buildViewKey(ip, videoUUID), '1', VIDEO_VIEW_LIFETIME)
60 async isViewExists (ip: string, videoUUID: string) {
61 return this.exists(this.buildViewKey(ip, videoUUID))
64 async getCachedRoute (req: express.Request) {
65 const cached = await this.getObject(this.buildCachedRouteKey(req))
67 return cached as CachedRoute
70 setCachedRoute (req: express.Request, body: any, contentType?: string, statusCode?: number) {
71 const cached: CachedRoute = {
72 body: body.toString(),
74 statusCode: statusCode.toString()
77 return this.setObject(this.buildCachedRouteKey(req), cached, FEEDS.CACHE_LIFETIME)
80 listJobs (jobsPrefix: string, state: string, mode: 'alpha', order: 'ASC' | 'DESC', offset: number, count: number) {
81 return new Promise<string[]>((res, rej) => {
82 this.client.sort(jobsPrefix + ':jobs:' + state, 'by', mode, order, 'LIMIT', offset.toString(), count.toString(), (err, values) => {
83 if (err) return rej(err)
90 private getValue (key: string) {
91 return new Promise<string>((res, rej) => {
92 this.client.get(this.prefix + key, (err, value) => {
93 if (err) return rej(err)
100 private setValue (key: string, value: string, expirationMilliseconds: number) {
101 return new Promise<void>((res, rej) => {
102 this.client.set(this.prefix + key, value, 'PX', expirationMilliseconds, (err, ok) => {
103 if (err) return rej(err)
105 if (ok !== 'OK') return rej(new Error('Redis set result is not OK.'))
112 private setObject (key: string, obj: { [ id: string ]: string }, expirationMilliseconds: number) {
113 return new Promise<void>((res, rej) => {
114 this.client.hmset(this.prefix + key, obj, (err, ok) => {
115 if (err) return rej(err)
116 if (!ok) return rej(new Error('Redis mset result is not OK.'))
118 this.client.pexpire(this.prefix + key, expirationMilliseconds, (err, ok) => {
119 if (err) return rej(err)
120 if (!ok) return rej(new Error('Redis expiration result is not OK.'))
128 private getObject (key: string) {
129 return new Promise<{ [ id: string ]: string }>((res, rej) => {
130 this.client.hgetall(this.prefix + key, (err, value) => {
131 if (err) return rej(err)
138 private exists (key: string) {
139 return new Promise<boolean>((res, rej) => {
140 this.client.exists(this.prefix + key, (err, existsNumber) => {
141 if (err) return rej(err)
143 return res(existsNumber === 1)
148 private generateResetPasswordKey (userId: number) {
149 return 'reset-password-' + userId
152 private buildViewKey (ip: string, videoUUID: string) {
153 return videoUUID + '-' + ip
156 private buildCachedRouteKey (req: express.Request) {
157 return req.method + '-' + req.originalUrl
160 static get Instance () {
161 return this.instance || (this.instance = new this())
165 // ---------------------------------------------------------------------------