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, USER_EMAIL_VERIFY_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(Redis.getRedisClient())
29 this.client.on('error', err => {
30 logger.error('Error in Redis client.', { err })
34 if (CONFIG.REDIS.AUTH) {
35 this.client.auth(CONFIG.REDIS.AUTH)
38 this.prefix = 'redis-' + CONFIG.WEBSERVER.HOST + '-'
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 }
51 async setResetPasswordVerificationString (userId: number) {
52 const generatedString = await generateRandomString(32)
54 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_RESET_LIFETIME)
56 return generatedString
59 async getResetPasswordLink (userId: number) {
60 return this.getValue(this.generateResetPasswordKey(userId))
63 async setVerifyEmailVerificationString (userId: number) {
64 const generatedString = await generateRandomString(32)
66 await this.setValue(this.generateVerifyEmailKey(userId), generatedString, USER_EMAIL_VERIFY_LIFETIME)
68 return generatedString
71 async getVerifyEmailLink (userId: number) {
72 return this.getValue(this.generateVerifyEmailKey(userId))
75 setIPVideoView (ip: string, videoUUID: string) {
76 return this.setValue(this.buildViewKey(ip, videoUUID), '1', VIDEO_VIEW_LIFETIME)
79 async isVideoIPViewExists (ip: string, videoUUID: string) {
80 return this.exists(this.buildViewKey(ip, videoUUID))
83 async getCachedRoute (req: express.Request) {
84 const cached = await this.getObject(this.buildCachedRouteKey(req))
86 return cached as CachedRoute
89 setCachedRoute (req: express.Request, body: any, lifetime: number, contentType?: string, statusCode?: number) {
90 const cached: CachedRoute = Object.assign({}, {
93 (contentType) ? { contentType } : null,
94 (statusCode) ? { statusCode: statusCode.toString() } : null
97 return this.setObject(this.buildCachedRouteKey(req), cached, lifetime)
100 addVideoView (videoId: number) {
101 const keyIncr = this.generateVideoViewKey(videoId)
102 const keySet = this.generateVideosViewKey()
105 this.addToSet(keySet, videoId.toString()),
106 this.increment(keyIncr)
110 async getVideoViews (videoId: number, hour: number) {
111 const key = this.generateVideoViewKey(videoId, hour)
113 const valueString = await this.getValue(key)
114 return parseInt(valueString, 10)
117 async getVideosIdViewed (hour: number) {
118 const key = this.generateVideosViewKey(hour)
120 const stringIds = await this.getSet(key)
121 return stringIds.map(s => parseInt(s, 10))
124 deleteVideoViews (videoId: number, hour: number) {
125 const keySet = this.generateVideosViewKey(hour)
126 const keyIncr = this.generateVideoViewKey(videoId, hour)
129 this.deleteFromSet(keySet, videoId.toString()),
130 this.deleteKey(keyIncr)
134 generateVideosViewKey (hour?: number) {
135 if (!hour) hour = new Date().getHours()
137 return `videos-view-h${hour}`
140 generateVideoViewKey (videoId: number, hour?: number) {
141 if (!hour) hour = new Date().getHours()
143 return `video-view-${videoId}-h${hour}`
146 generateResetPasswordKey (userId: number) {
147 return 'reset-password-' + userId
150 generateVerifyEmailKey (userId: number) {
151 return 'verify-email-' + userId
154 buildViewKey (ip: string, videoUUID: string) {
155 return videoUUID + '-' + ip
158 buildCachedRouteKey (req: express.Request) {
159 return req.method + '-' + req.originalUrl
162 private getValue (key: string) {
163 return new Promise<string>((res, rej) => {
164 this.client.get(this.prefix + key, (err, value) => {
165 if (err) return rej(err)
172 private getSet (key: string) {
173 return new Promise<string[]>((res, rej) => {
174 this.client.smembers(this.prefix + key, (err, value) => {
175 if (err) return rej(err)
182 private addToSet (key: string, value: string) {
183 return new Promise<string[]>((res, rej) => {
184 this.client.sadd(this.prefix + key, value, err => err ? rej(err) : res())
188 private deleteFromSet (key: string, value: string) {
189 return new Promise<void>((res, rej) => {
190 this.client.srem(this.prefix + key, value, err => err ? rej(err) : res())
194 private deleteKey (key: string) {
195 return new Promise<void>((res, rej) => {
196 this.client.del(this.prefix + key, err => err ? rej(err) : res())
200 private setValue (key: string, value: string, expirationMilliseconds: number) {
201 return new Promise<void>((res, rej) => {
202 this.client.set(this.prefix + key, value, 'PX', expirationMilliseconds, (err, ok) => {
203 if (err) return rej(err)
205 if (ok !== 'OK') return rej(new Error('Redis set result is not OK.'))
212 private setObject (key: string, obj: { [ id: string ]: string }, expirationMilliseconds: number) {
213 return new Promise<void>((res, rej) => {
214 this.client.hmset(this.prefix + key, obj, (err, ok) => {
215 if (err) return rej(err)
216 if (!ok) return rej(new Error('Redis mset result is not OK.'))
218 this.client.pexpire(this.prefix + key, expirationMilliseconds, (err, ok) => {
219 if (err) return rej(err)
220 if (!ok) return rej(new Error('Redis expiration result is not OK.'))
228 private getObject (key: string) {
229 return new Promise<{ [ id: string ]: string }>((res, rej) => {
230 this.client.hgetall(this.prefix + key, (err, value) => {
231 if (err) return rej(err)
238 private increment (key: string) {
239 return new Promise<number>((res, rej) => {
240 this.client.incr(this.prefix + key, (err, value) => {
241 if (err) return rej(err)
248 private exists (key: string) {
249 return new Promise<boolean>((res, rej) => {
250 this.client.exists(this.prefix + key, (err, existsNumber) => {
251 if (err) return rej(err)
253 return res(existsNumber === 1)
258 static get Instance () {
259 return this.instance || (this.instance = new this())
263 // ---------------------------------------------------------------------------