1 import * as express from 'express'
2 import { createClient, RedisClient } from 'redis'
3 import { logger } from '../helpers/logger'
4 import { generateRandomString } from '../helpers/utils'
7 USER_EMAIL_VERIFY_LIFETIME,
8 USER_PASSWORD_RESET_LIFETIME,
9 USER_PASSWORD_CREATE_LIFETIME,
13 } from '../initializers/constants'
14 import { CONFIG } from '../initializers/config'
24 private static instance: Redis
25 private initialized = false
26 private client: RedisClient
27 private prefix: string
29 private constructor () {
33 // Already initialized
34 if (this.initialized === true) return
35 this.initialized = true
37 this.client = createClient(Redis.getRedisClientOptions())
39 this.client.on('error', err => {
40 logger.error('Error in Redis client.', { err })
44 if (CONFIG.REDIS.AUTH) {
45 this.client.auth(CONFIG.REDIS.AUTH)
48 this.prefix = 'redis-' + WEBSERVER.HOST + '-'
51 static getRedisClientOptions () {
52 return Object.assign({},
53 (CONFIG.REDIS.AUTH && CONFIG.REDIS.AUTH != null) ? { password: CONFIG.REDIS.AUTH } : {},
54 (CONFIG.REDIS.DB) ? { db: CONFIG.REDIS.DB } : {},
55 (CONFIG.REDIS.HOSTNAME && CONFIG.REDIS.PORT)
56 ? { host: CONFIG.REDIS.HOSTNAME, port: CONFIG.REDIS.PORT }
57 : { path: CONFIG.REDIS.SOCKET }
69 /* ************ Forgot password ************ */
71 async setResetPasswordVerificationString (userId: number) {
72 const generatedString = await generateRandomString(32)
74 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_RESET_LIFETIME)
76 return generatedString
79 async setCreatePasswordVerificationString (userId: number) {
80 const generatedString = await generateRandomString(32)
82 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_CREATE_LIFETIME)
84 return generatedString
87 async removePasswordVerificationString (userId: number) {
88 return this.removeValue(this.generateResetPasswordKey(userId))
91 async getResetPasswordLink (userId: number) {
92 return this.getValue(this.generateResetPasswordKey(userId))
95 /* ************ Email verification ************ */
97 async setVerifyEmailVerificationString (userId: number) {
98 const generatedString = await generateRandomString(32)
100 await this.setValue(this.generateVerifyEmailKey(userId), generatedString, USER_EMAIL_VERIFY_LIFETIME)
102 return generatedString
105 async getVerifyEmailLink (userId: number) {
106 return this.getValue(this.generateVerifyEmailKey(userId))
109 /* ************ Contact form per IP ************ */
111 async setContactFormIp (ip: string) {
112 return this.setValue(this.generateContactFormKey(ip), '1', CONTACT_FORM_LIFETIME)
115 async doesContactFormIpExist (ip: string) {
116 return this.exists(this.generateContactFormKey(ip))
119 /* ************ Views per IP ************ */
121 setIPVideoView (ip: string, videoUUID: string) {
122 return this.setValue(this.generateViewKey(ip, videoUUID), '1', VIDEO_VIEW_LIFETIME)
125 async doesVideoIPViewExist (ip: string, videoUUID: string) {
126 return this.exists(this.generateViewKey(ip, videoUUID))
129 /* ************ Tracker IP block ************ */
131 setTrackerBlockIP (ip: string) {
132 return this.setValue(this.generateTrackerBlockIPKey(ip), '1', TRACKER_RATE_LIMITS.BLOCK_IP_LIFETIME)
135 async doesTrackerBlockIPExist (ip: string) {
136 return this.exists(this.generateTrackerBlockIPKey(ip))
139 /* ************ API cache ************ */
141 async getCachedRoute (req: express.Request) {
142 const cached = await this.getObject(this.generateCachedRouteKey(req))
144 return cached as CachedRoute
147 setCachedRoute (req: express.Request, body: any, lifetime: number, contentType?: string, statusCode?: number) {
148 const cached: CachedRoute = Object.assign(
150 { body: body.toString() },
151 (contentType) ? { contentType } : null,
152 (statusCode) ? { statusCode: statusCode.toString() } : null
155 return this.setObject(this.generateCachedRouteKey(req), cached, lifetime)
158 /* ************ Video views ************ */
160 addVideoView (videoId: number) {
161 const keyIncr = this.generateVideoViewKey(videoId)
162 const keySet = this.generateVideosViewKey()
165 this.addToSet(keySet, videoId.toString()),
166 this.increment(keyIncr)
170 async getVideoViews (videoId: number, hour: number) {
171 const key = this.generateVideoViewKey(videoId, hour)
173 const valueString = await this.getValue(key)
174 const valueInt = parseInt(valueString, 10)
176 if (isNaN(valueInt)) {
177 logger.error('Cannot get videos views of video %d in hour %d: views number is NaN (%s).', videoId, hour, valueString)
184 async getVideosIdViewed (hour: number) {
185 const key = this.generateVideosViewKey(hour)
187 const stringIds = await this.getSet(key)
188 return stringIds.map(s => parseInt(s, 10))
191 deleteVideoViews (videoId: number, hour: number) {
192 const keySet = this.generateVideosViewKey(hour)
193 const keyIncr = this.generateVideoViewKey(videoId, hour)
196 this.deleteFromSet(keySet, videoId.toString()),
197 this.deleteKey(keyIncr)
201 /* ************ Keys generation ************ */
203 generateCachedRouteKey (req: express.Request) {
204 return req.method + '-' + req.originalUrl
207 private generateVideosViewKey (hour?: number) {
208 if (!hour) hour = new Date().getHours()
210 return `videos-view-h${hour}`
213 private generateVideoViewKey (videoId: number, hour?: number) {
214 if (!hour) hour = new Date().getHours()
216 return `video-view-${videoId}-h${hour}`
219 private generateResetPasswordKey (userId: number) {
220 return 'reset-password-' + userId
223 private generateVerifyEmailKey (userId: number) {
224 return 'verify-email-' + userId
227 private generateViewKey (ip: string, videoUUID: string) {
228 return `views-${videoUUID}-${ip}`
231 private generateTrackerBlockIPKey (ip: string) {
232 return `tracker-block-ip-${ip}`
235 private generateContactFormKey (ip: string) {
236 return 'contact-form-' + ip
239 /* ************ Redis helpers ************ */
241 private getValue (key: string) {
242 return new Promise<string>((res, rej) => {
243 this.client.get(this.prefix + key, (err, value) => {
244 if (err) return rej(err)
251 private getSet (key: string) {
252 return new Promise<string[]>((res, rej) => {
253 this.client.smembers(this.prefix + key, (err, value) => {
254 if (err) return rej(err)
261 private addToSet (key: string, value: string) {
262 return new Promise<string[]>((res, rej) => {
263 this.client.sadd(this.prefix + key, value, err => err ? rej(err) : res())
267 private deleteFromSet (key: string, value: string) {
268 return new Promise<void>((res, rej) => {
269 this.client.srem(this.prefix + key, value, err => err ? rej(err) : res())
273 private deleteKey (key: string) {
274 return new Promise<void>((res, rej) => {
275 this.client.del(this.prefix + key, err => err ? rej(err) : res())
279 private deleteFieldInHash (key: string, field: string) {
280 return new Promise<void>((res, rej) => {
281 this.client.hdel(this.prefix + key, field, err => err ? rej(err) : res())
285 private setValue (key: string, value: string, expirationMilliseconds: number) {
286 return new Promise<void>((res, rej) => {
287 this.client.set(this.prefix + key, value, 'PX', expirationMilliseconds, (err, ok) => {
288 if (err) return rej(err)
290 if (ok !== 'OK') return rej(new Error('Redis set result is not OK.'))
297 private removeValue (key: string) {
298 return new Promise<void>((res, rej) => {
299 this.client.del(this.prefix + key, err => {
300 if (err) return rej(err)
307 private setObject (key: string, obj: { [id: string]: string }, expirationMilliseconds: number) {
308 return new Promise<void>((res, rej) => {
309 this.client.hmset(this.prefix + key, obj, (err, ok) => {
310 if (err) return rej(err)
311 if (!ok) return rej(new Error('Redis mset result is not OK.'))
313 this.client.pexpire(this.prefix + key, expirationMilliseconds, (err, ok) => {
314 if (err) return rej(err)
315 if (!ok) return rej(new Error('Redis expiration result is not OK.'))
323 private getObject (key: string) {
324 return new Promise<{ [id: string]: string }>((res, rej) => {
325 this.client.hgetall(this.prefix + key, (err, value) => {
326 if (err) return rej(err)
333 private setValueInHash (key: string, field: string, value: string) {
334 return new Promise<void>((res, rej) => {
335 this.client.hset(this.prefix + key, field, value, (err) => {
336 if (err) return rej(err)
343 private increment (key: string) {
344 return new Promise<number>((res, rej) => {
345 this.client.incr(this.prefix + key, (err, value) => {
346 if (err) return rej(err)
353 private exists (key: string) {
354 return new Promise<boolean>((res, rej) => {
355 this.client.exists(this.prefix + key, (err, existsNumber) => {
356 if (err) return rej(err)
358 return res(existsNumber === 1)
363 static get Instance () {
364 return this.instance || (this.instance = new this())
368 // ---------------------------------------------------------------------------