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, isLive: boolean) {
122 const lifetime = isLive
124 : VIEW_LIFETIME.VIDEO
126 return this.setValue(this.generateViewKey(ip, videoUUID), '1', lifetime)
129 async doesVideoIPViewExist (ip: string, videoUUID: string) {
130 return this.exists(this.generateViewKey(ip, videoUUID))
133 /* ************ Tracker IP block ************ */
135 setTrackerBlockIP (ip: string) {
136 return this.setValue(this.generateTrackerBlockIPKey(ip), '1', TRACKER_RATE_LIMITS.BLOCK_IP_LIFETIME)
139 async doesTrackerBlockIPExist (ip: string) {
140 return this.exists(this.generateTrackerBlockIPKey(ip))
143 /* ************ API cache ************ */
145 async getCachedRoute (req: express.Request) {
146 const cached = await this.getObject(this.generateCachedRouteKey(req))
148 return cached as CachedRoute
151 setCachedRoute (req: express.Request, body: any, lifetime: number, contentType?: string, statusCode?: number) {
152 const cached: CachedRoute = Object.assign(
154 { body: body.toString() },
155 (contentType) ? { contentType } : null,
156 (statusCode) ? { statusCode: statusCode.toString() } : null
159 return this.setObject(this.generateCachedRouteKey(req), cached, lifetime)
162 /* ************ Video views ************ */
164 addVideoView (videoId: number) {
165 const keyIncr = this.generateVideoViewKey(videoId)
166 const keySet = this.generateVideosViewKey()
169 this.addToSet(keySet, videoId.toString()),
170 this.increment(keyIncr)
174 async getVideoViews (videoId: number, hour: number) {
175 const key = this.generateVideoViewKey(videoId, hour)
177 const valueString = await this.getValue(key)
178 const valueInt = parseInt(valueString, 10)
180 if (isNaN(valueInt)) {
181 logger.error('Cannot get videos views of video %d in hour %d: views number is NaN (%s).', videoId, hour, valueString)
188 async getVideosIdViewed (hour: number) {
189 const key = this.generateVideosViewKey(hour)
191 const stringIds = await this.getSet(key)
192 return stringIds.map(s => parseInt(s, 10))
195 deleteVideoViews (videoId: number, hour: number) {
196 const keySet = this.generateVideosViewKey(hour)
197 const keyIncr = this.generateVideoViewKey(videoId, hour)
200 this.deleteFromSet(keySet, videoId.toString()),
201 this.deleteKey(keyIncr)
205 /* ************ Keys generation ************ */
207 generateCachedRouteKey (req: express.Request) {
208 return req.method + '-' + req.originalUrl
211 private generateVideosViewKey (hour?: number) {
212 if (!hour) hour = new Date().getHours()
214 return `videos-view-h${hour}`
217 private generateVideoViewKey (videoId: number, hour?: number) {
218 if (hour === undefined || hour === null) hour = new Date().getHours()
220 return `video-view-${videoId}-h${hour}`
223 private generateResetPasswordKey (userId: number) {
224 return 'reset-password-' + userId
227 private generateVerifyEmailKey (userId: number) {
228 return 'verify-email-' + userId
231 private generateViewKey (ip: string, videoUUID: string) {
232 return `views-${videoUUID}-${ip}`
235 private generateTrackerBlockIPKey (ip: string) {
236 return `tracker-block-ip-${ip}`
239 private generateContactFormKey (ip: string) {
240 return 'contact-form-' + ip
243 /* ************ Redis helpers ************ */
245 private getValue (key: string) {
246 return new Promise<string>((res, rej) => {
247 this.client.get(this.prefix + key, (err, value) => {
248 if (err) return rej(err)
255 private getSet (key: string) {
256 return new Promise<string[]>((res, rej) => {
257 this.client.smembers(this.prefix + key, (err, value) => {
258 if (err) return rej(err)
265 private addToSet (key: string, value: string) {
266 return new Promise<void>((res, rej) => {
267 this.client.sadd(this.prefix + key, value, err => err ? rej(err) : res())
271 private deleteFromSet (key: string, value: string) {
272 return new Promise<void>((res, rej) => {
273 this.client.srem(this.prefix + key, value, err => err ? rej(err) : res())
277 private deleteKey (key: string) {
278 return new Promise<void>((res, rej) => {
279 this.client.del(this.prefix + key, err => err ? rej(err) : res())
283 private deleteFieldInHash (key: string, field: string) {
284 return new Promise<void>((res, rej) => {
285 this.client.hdel(this.prefix + key, field, err => err ? rej(err) : res())
289 private setValue (key: string, value: string, expirationMilliseconds: number) {
290 return new Promise<void>((res, rej) => {
291 this.client.set(this.prefix + key, value, 'PX', expirationMilliseconds, (err, ok) => {
292 if (err) return rej(err)
294 if (ok !== 'OK') return rej(new Error('Redis set result is not OK.'))
301 private removeValue (key: string) {
302 return new Promise<void>((res, rej) => {
303 this.client.del(this.prefix + key, err => {
304 if (err) return rej(err)
311 private setObject (key: string, obj: { [id: string]: string }, expirationMilliseconds: number) {
312 return new Promise<void>((res, rej) => {
313 this.client.hmset(this.prefix + key, obj, (err, ok) => {
314 if (err) return rej(err)
315 if (!ok) return rej(new Error('Redis mset result is not OK.'))
317 this.client.pexpire(this.prefix + key, expirationMilliseconds, (err, ok) => {
318 if (err) return rej(err)
319 if (!ok) return rej(new Error('Redis expiration result is not OK.'))
327 private getObject (key: string) {
328 return new Promise<{ [id: string]: string }>((res, rej) => {
329 this.client.hgetall(this.prefix + key, (err, value) => {
330 if (err) return rej(err)
337 private setValueInHash (key: string, field: string, value: string) {
338 return new Promise<void>((res, rej) => {
339 this.client.hset(this.prefix + key, field, value, (err) => {
340 if (err) return rej(err)
347 private increment (key: string) {
348 return new Promise<number>((res, rej) => {
349 this.client.incr(this.prefix + key, (err, value) => {
350 if (err) return rej(err)
357 private exists (key: string) {
358 return new Promise<boolean>((res, rej) => {
359 this.client.exists(this.prefix + key, (err, existsNumber) => {
360 if (err) return rej(err)
362 return res(existsNumber === 1)
367 static get Instance () {
368 return this.instance || (this.instance = new this())
372 // ---------------------------------------------------------------------------