Migrate to bull
[oweals/peertube.git] / server / lib / redis.ts
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'
6
7 type CachedRoute = {
8   body: string,
9   contentType?: string
10   statusCode?: string
11 }
12
13 class Redis {
14
15   private static instance: Redis
16   private initialized = false
17   private client: RedisClient
18   private prefix: string
19
20   private constructor () {}
21
22   init () {
23     // Already initialized
24     if (this.initialized === true) return
25     this.initialized = true
26
27     this.client = createClient({
28       host: CONFIG.REDIS.HOSTNAME,
29       port: CONFIG.REDIS.PORT,
30       db: CONFIG.REDIS.DB
31     })
32
33     this.client.on('error', err => {
34       logger.error('Error in Redis client.', { err })
35       process.exit(-1)
36     })
37
38     if (CONFIG.REDIS.AUTH) {
39       this.client.auth(CONFIG.REDIS.AUTH)
40     }
41
42     this.prefix = 'redis-' + CONFIG.WEBSERVER.HOST + '-'
43   }
44
45   async setResetPasswordVerificationString (userId: number) {
46     const generatedString = await generateRandomString(32)
47
48     await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_RESET_LIFETIME)
49
50     return generatedString
51   }
52
53   async getResetPasswordLink (userId: number) {
54     return this.getValue(this.generateResetPasswordKey(userId))
55   }
56
57   setView (ip: string, videoUUID: string) {
58     return this.setValue(this.buildViewKey(ip, videoUUID), '1', VIDEO_VIEW_LIFETIME)
59   }
60
61   async isViewExists (ip: string, videoUUID: string) {
62     return this.exists(this.buildViewKey(ip, videoUUID))
63   }
64
65   async getCachedRoute (req: express.Request) {
66     const cached = await this.getObject(this.buildCachedRouteKey(req))
67
68     return cached as CachedRoute
69   }
70
71   setCachedRoute (req: express.Request, body: any, lifetime: number, contentType?: string, statusCode?: number) {
72     const cached: CachedRoute = {
73       body: body.toString(),
74       contentType,
75       statusCode: statusCode.toString()
76     }
77
78     return this.setObject(this.buildCachedRouteKey(req), cached, lifetime)
79   }
80
81   generateResetPasswordKey (userId: number) {
82     return 'reset-password-' + userId
83   }
84
85   buildViewKey (ip: string, videoUUID: string) {
86     return videoUUID + '-' + ip
87   }
88
89   buildCachedRouteKey (req: express.Request) {
90     return req.method + '-' + req.originalUrl
91   }
92
93   private getValue (key: string) {
94     return new Promise<string>((res, rej) => {
95       this.client.get(this.prefix + key, (err, value) => {
96         if (err) return rej(err)
97
98         return res(value)
99       })
100     })
101   }
102
103   private setValue (key: string, value: string, expirationMilliseconds: number) {
104     return new Promise<void>((res, rej) => {
105       this.client.set(this.prefix + key, value, 'PX', expirationMilliseconds, (err, ok) => {
106         if (err) return rej(err)
107
108         if (ok !== 'OK') return rej(new Error('Redis set result is not OK.'))
109
110         return res()
111       })
112     })
113   }
114
115   private setObject (key: string, obj: { [ id: string ]: string }, expirationMilliseconds: number) {
116     return new Promise<void>((res, rej) => {
117       this.client.hmset(this.prefix + key, obj, (err, ok) => {
118         if (err) return rej(err)
119         if (!ok) return rej(new Error('Redis mset result is not OK.'))
120
121         this.client.pexpire(this.prefix + key, expirationMilliseconds, (err, ok) => {
122           if (err) return rej(err)
123           if (!ok) return rej(new Error('Redis expiration result is not OK.'))
124
125           return res()
126         })
127       })
128     })
129   }
130
131   private getObject (key: string) {
132     return new Promise<{ [ id: string ]: string }>((res, rej) => {
133       this.client.hgetall(this.prefix + key, (err, value) => {
134         if (err) return rej(err)
135
136         return res(value)
137       })
138     })
139   }
140
141   private exists (key: string) {
142     return new Promise<boolean>((res, rej) => {
143       this.client.exists(this.prefix + key, (err, existsNumber) => {
144         if (err) return rej(err)
145
146         return res(existsNumber === 1)
147       })
148     })
149   }
150
151   static get Instance () {
152     return this.instance || (this.instance = new this())
153   }
154 }
155
156 // ---------------------------------------------------------------------------
157
158 export {
159   Redis
160 }