1 import { createClient, RedisClient } from 'redis'
2 import { logger } from '../helpers/logger'
3 import { generateRandomString } from '../helpers/utils'
4 import { CONFIG, USER_PASSWORD_RESET_LIFETIME, VIDEO_VIEW_LIFETIME } from '../initializers'
8 private static instance: Redis
9 private initialized = false
10 private client: RedisClient
11 private prefix: string
13 private constructor () {}
16 // Already initialized
17 if (this.initialized === true) return
18 this.initialized = true
20 this.client = createClient({
21 host: CONFIG.REDIS.HOSTNAME,
22 port: CONFIG.REDIS.PORT
25 this.client.on('error', err => {
26 logger.error('Error in Redis client.', err)
30 if (CONFIG.REDIS.AUTH) {
31 this.client.auth(CONFIG.REDIS.AUTH)
34 this.prefix = 'redis-' + CONFIG.WEBSERVER.HOST + '-'
37 async setResetPasswordVerificationString (userId: number) {
38 const generatedString = await generateRandomString(32)
40 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_RESET_LIFETIME)
42 return generatedString
45 async getResetPasswordLink (userId: number) {
46 return this.getValue(this.generateResetPasswordKey(userId))
49 setView (ip: string, videoUUID: string) {
50 return this.setValue(this.buildViewKey(ip, videoUUID), '1', VIDEO_VIEW_LIFETIME)
53 async isViewExists (ip: string, videoUUID: string) {
54 return this.exists(this.buildViewKey(ip, videoUUID))
57 listJobs (jobsPrefix: string, state: string, mode: 'alpha', order: 'ASC' | 'DESC', offset: number, count: number) {
58 return new Promise<string[]>((res, rej) => {
59 this.client.sort(jobsPrefix + ':jobs:' + state, 'by', mode, order, 'LIMIT', offset.toString(), count.toString(), (err, values) => {
60 if (err) return rej(err)
67 private getValue (key: string) {
68 return new Promise<string>((res, rej) => {
69 this.client.get(this.prefix + key, (err, value) => {
70 if (err) return rej(err)
77 private setValue (key: string, value: string, expirationMilliseconds: number) {
78 return new Promise<void>((res, rej) => {
79 this.client.set(this.prefix + key, value, 'PX', expirationMilliseconds, (err, ok) => {
80 if (err) return rej(err)
82 if (ok !== 'OK') return rej(new Error('Redis result is not OK.'))
89 private exists (key: string) {
90 return new Promise<boolean>((res, rej) => {
91 this.client.exists(this.prefix + key, (err, existsNumber) => {
92 if (err) return rej(err)
94 return res(existsNumber === 1)
99 private generateResetPasswordKey (userId: number) {
100 return 'reset-password-' + userId
103 private buildViewKey (ip: string, videoUUID: string) {
104 return videoUUID + '-' + ip
107 static get Instance () {
108 return this.instance || (this.instance = new this())
112 // ---------------------------------------------------------------------------