Implement captions/subtitles
[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(Redis.getRedisClient())
28
29     this.client.on('error', err => {
30       logger.error('Error in Redis client.', { err })
31       process.exit(-1)
32     })
33
34     if (CONFIG.REDIS.AUTH) {
35       this.client.auth(CONFIG.REDIS.AUTH)
36     }
37
38     this.prefix = 'redis-' + CONFIG.WEBSERVER.HOST + '-'
39   }
40
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 }
48     )
49   }
50
51   async setResetPasswordVerificationString (userId: number) {
52     const generatedString = await generateRandomString(32)
53
54     await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_RESET_LIFETIME)
55
56     return generatedString
57   }
58
59   async getResetPasswordLink (userId: number) {
60     return this.getValue(this.generateResetPasswordKey(userId))
61   }
62
63   setView (ip: string, videoUUID: string) {
64     return this.setValue(this.buildViewKey(ip, videoUUID), '1', VIDEO_VIEW_LIFETIME)
65   }
66
67   async isViewExists (ip: string, videoUUID: string) {
68     return this.exists(this.buildViewKey(ip, videoUUID))
69   }
70
71   async getCachedRoute (req: express.Request) {
72     const cached = await this.getObject(this.buildCachedRouteKey(req))
73
74     return cached as CachedRoute
75   }
76
77   setCachedRoute (req: express.Request, body: any, lifetime: number, contentType?: string, statusCode?: number) {
78     const cached: CachedRoute = {
79       body: body.toString(),
80       contentType,
81       statusCode: statusCode.toString()
82     }
83
84     return this.setObject(this.buildCachedRouteKey(req), cached, lifetime)
85   }
86
87   generateResetPasswordKey (userId: number) {
88     return 'reset-password-' + userId
89   }
90
91   buildViewKey (ip: string, videoUUID: string) {
92     return videoUUID + '-' + ip
93   }
94
95   buildCachedRouteKey (req: express.Request) {
96     return req.method + '-' + req.originalUrl
97   }
98
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)
103
104         return res(value)
105       })
106     })
107   }
108
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)
113
114         if (ok !== 'OK') return rej(new Error('Redis set result is not OK.'))
115
116         return res()
117       })
118     })
119   }
120
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.'))
126
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.'))
130
131           return res()
132         })
133       })
134     })
135   }
136
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)
141
142         return res(value)
143       })
144     })
145   }
146
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)
151
152         return res(existsNumber === 1)
153       })
154     })
155   }
156
157   static get Instance () {
158     return this.instance || (this.instance = new this())
159   }
160 }
161
162 // ---------------------------------------------------------------------------
163
164 export {
165   Redis
166 }