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'
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 setIPVideoView (ip: string, videoUUID: string) {
64 return this.setValue(this.buildViewKey(ip, videoUUID), '1', VIDEO_VIEW_LIFETIME)
67 async isVideoIPViewExists (ip: string, videoUUID: string) {
68 return this.exists(this.buildViewKey(ip, videoUUID))
71 async getCachedRoute (req: express.Request) {
72 const cached = await this.getObject(this.buildCachedRouteKey(req))
74 return cached as CachedRoute
77 setCachedRoute (req: express.Request, body: any, lifetime: number, contentType?: string, statusCode?: number) {
78 const cached: CachedRoute = Object.assign({}, {
81 (contentType) ? { contentType } : null,
82 (statusCode) ? { statusCode: statusCode.toString() } : null
85 return this.setObject(this.buildCachedRouteKey(req), cached, lifetime)
88 addVideoView (videoId: number) {
89 const keyIncr = this.generateVideoViewKey(videoId)
90 const keySet = this.generateVideosViewKey()
93 this.addToSet(keySet, videoId.toString()),
94 this.increment(keyIncr)
98 async getVideoViews (videoId: number, hour: number) {
99 const key = this.generateVideoViewKey(videoId, hour)
101 const valueString = await this.getValue(key)
102 return parseInt(valueString, 10)
105 async getVideosIdViewed (hour: number) {
106 const key = this.generateVideosViewKey(hour)
108 const stringIds = await this.getSet(key)
109 return stringIds.map(s => parseInt(s, 10))
112 deleteVideoViews (videoId: number, hour: number) {
113 const keySet = this.generateVideosViewKey(hour)
114 const keyIncr = this.generateVideoViewKey(videoId, hour)
117 this.deleteFromSet(keySet, videoId.toString()),
118 this.deleteKey(keyIncr)
122 generateVideosViewKey (hour?: number) {
123 if (!hour) hour = new Date().getHours()
125 return `videos-view-h${hour}`
128 generateVideoViewKey (videoId: number, hour?: number) {
129 if (!hour) hour = new Date().getHours()
131 return `video-view-${videoId}-h${hour}`
134 generateResetPasswordKey (userId: number) {
135 return 'reset-password-' + userId
138 buildViewKey (ip: string, videoUUID: string) {
139 return videoUUID + '-' + ip
142 buildCachedRouteKey (req: express.Request) {
143 return req.method + '-' + req.originalUrl
146 private getValue (key: string) {
147 return new Promise<string>((res, rej) => {
148 this.client.get(this.prefix + key, (err, value) => {
149 if (err) return rej(err)
156 private getSet (key: string) {
157 return new Promise<string[]>((res, rej) => {
158 this.client.smembers(this.prefix + key, (err, value) => {
159 if (err) return rej(err)
166 private addToSet (key: string, value: string) {
167 return new Promise<string[]>((res, rej) => {
168 this.client.sadd(this.prefix + key, value, err => err ? rej(err) : res())
172 private deleteFromSet (key: string, value: string) {
173 return new Promise<void>((res, rej) => {
174 this.client.srem(this.prefix + key, value, err => err ? rej(err) : res())
178 private deleteKey (key: string) {
179 return new Promise<void>((res, rej) => {
180 this.client.del(this.prefix + key, err => err ? rej(err) : res())
184 private setValue (key: string, value: string, expirationMilliseconds: number) {
185 return new Promise<void>((res, rej) => {
186 this.client.set(this.prefix + key, value, 'PX', expirationMilliseconds, (err, ok) => {
187 if (err) return rej(err)
189 if (ok !== 'OK') return rej(new Error('Redis set result is not OK.'))
196 private setObject (key: string, obj: { [ id: string ]: string }, expirationMilliseconds: number) {
197 return new Promise<void>((res, rej) => {
198 this.client.hmset(this.prefix + key, obj, (err, ok) => {
199 if (err) return rej(err)
200 if (!ok) return rej(new Error('Redis mset result is not OK.'))
202 this.client.pexpire(this.prefix + key, expirationMilliseconds, (err, ok) => {
203 if (err) return rej(err)
204 if (!ok) return rej(new Error('Redis expiration result is not OK.'))
212 private getObject (key: string) {
213 return new Promise<{ [ id: string ]: string }>((res, rej) => {
214 this.client.hgetall(this.prefix + key, (err, value) => {
215 if (err) return rej(err)
222 private increment (key: string) {
223 return new Promise<number>((res, rej) => {
224 this.client.incr(this.prefix + key, (err, value) => {
225 if (err) return rej(err)
232 private exists (key: string) {
233 return new Promise<boolean>((res, rej) => {
234 this.client.exists(this.prefix + key, (err, existsNumber) => {
235 if (err) return rej(err)
237 return res(existsNumber === 1)
242 static get Instance () {
243 return this.instance || (this.instance = new this())
247 // ---------------------------------------------------------------------------