1 import { createClient, RedisClientOptions, RedisModules } from 'redis'
2 import { exists } from '@server/helpers/custom-validators/misc'
3 import { sha256 } from '@shared/extra-utils'
4 import { logger } from '../helpers/logger'
5 import { generateRandomString } from '../helpers/utils'
6 import { CONFIG } from '../initializers/config'
10 RESUMABLE_UPLOAD_SESSION_LIFETIME,
12 TWO_FACTOR_AUTH_REQUEST_TOKEN_LIFETIME,
13 USER_EMAIL_VERIFY_LIFETIME,
14 USER_PASSWORD_CREATE_LIFETIME,
15 USER_PASSWORD_RESET_LIFETIME,
18 } from '../initializers/constants'
22 private static instance: Redis
23 private initialized = false
24 private connected = false
25 private client: ReturnType<typeof createClient>
26 private prefix: string
28 private constructor () {
32 // Already initialized
33 if (this.initialized === true) return
34 this.initialized = true
36 this.client = createClient(Redis.getRedisClientOptions())
37 this.client.on('error', err => logger.error('Redis Client Error', { err }))
39 logger.info('Connecting to redis...')
43 logger.info('Connected to redis.')
47 logger.error('Cannot connect to redis', { err })
51 this.prefix = 'redis-' + WEBSERVER.HOST + '-'
54 static getRedisClientOptions () {
55 let config: RedisClientOptions<RedisModules, {}> = {
57 connectTimeout: 20000 // Could be slow since node use sync call to compile PeerTube
61 if (CONFIG.REDIS.AUTH) {
62 config = { ...config, password: CONFIG.REDIS.AUTH }
65 if (CONFIG.REDIS.DB) {
66 config = { ...config, database: CONFIG.REDIS.DB }
69 if (CONFIG.REDIS.HOSTNAME && CONFIG.REDIS.PORT) {
70 config.socket = { ...config.socket, host: CONFIG.REDIS.HOSTNAME, port: CONFIG.REDIS.PORT }
72 config.socket = { ...config.socket, path: CONFIG.REDIS.SOCKET }
90 /* ************ Forgot password ************ */
92 async setResetPasswordVerificationString (userId: number) {
93 const generatedString = await generateRandomString(32)
95 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_RESET_LIFETIME)
97 return generatedString
100 async setCreatePasswordVerificationString (userId: number) {
101 const generatedString = await generateRandomString(32)
103 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_CREATE_LIFETIME)
105 return generatedString
108 async removePasswordVerificationString (userId: number) {
109 return this.removeValue(this.generateResetPasswordKey(userId))
112 async getResetPasswordVerificationString (userId: number) {
113 return this.getValue(this.generateResetPasswordKey(userId))
116 /* ************ Two factor auth request ************ */
118 async setTwoFactorRequest (userId: number, otpSecret: string) {
119 const requestToken = await generateRandomString(32)
121 await this.setValue(this.generateTwoFactorRequestKey(userId, requestToken), otpSecret, TWO_FACTOR_AUTH_REQUEST_TOKEN_LIFETIME)
126 async getTwoFactorRequestToken (userId: number, requestToken: string) {
127 return this.getValue(this.generateTwoFactorRequestKey(userId, requestToken))
130 /* ************ Email verification ************ */
132 async setVerifyEmailVerificationString (userId: number) {
133 const generatedString = await generateRandomString(32)
135 await this.setValue(this.generateVerifyEmailKey(userId), generatedString, USER_EMAIL_VERIFY_LIFETIME)
137 return generatedString
140 async getVerifyEmailLink (userId: number) {
141 return this.getValue(this.generateVerifyEmailKey(userId))
144 /* ************ Contact form per IP ************ */
146 async setContactFormIp (ip: string) {
147 return this.setValue(this.generateContactFormKey(ip), '1', CONTACT_FORM_LIFETIME)
150 async doesContactFormIpExist (ip: string) {
151 return this.exists(this.generateContactFormKey(ip))
154 /* ************ Views per IP ************ */
156 setIPVideoView (ip: string, videoUUID: string) {
157 return this.setValue(this.generateIPViewKey(ip, videoUUID), '1', VIEW_LIFETIME.VIEW)
160 async doesVideoIPViewExist (ip: string, videoUUID: string) {
161 return this.exists(this.generateIPViewKey(ip, videoUUID))
164 /* ************ Tracker IP block ************ */
166 setTrackerBlockIP (ip: string) {
167 return this.setValue(this.generateTrackerBlockIPKey(ip), '1', TRACKER_RATE_LIMITS.BLOCK_IP_LIFETIME)
170 async doesTrackerBlockIPExist (ip: string) {
171 return this.exists(this.generateTrackerBlockIPKey(ip))
174 /* ************ Video views stats ************ */
176 addVideoViewStats (videoId: number) {
177 const { videoKey, setKey } = this.generateVideoViewStatsKeys({ videoId })
180 this.addToSet(setKey, videoId.toString()),
181 this.increment(videoKey)
185 async getVideoViewsStats (videoId: number, hour: number) {
186 const { videoKey } = this.generateVideoViewStatsKeys({ videoId, hour })
188 const valueString = await this.getValue(videoKey)
189 const valueInt = parseInt(valueString, 10)
191 if (isNaN(valueInt)) {
192 logger.error('Cannot get videos views stats of video %d in hour %d: views number is NaN (%s).', videoId, hour, valueString)
199 async listVideosViewedForStats (hour: number) {
200 const { setKey } = this.generateVideoViewStatsKeys({ hour })
202 const stringIds = await this.getSet(setKey)
203 return stringIds.map(s => parseInt(s, 10))
206 deleteVideoViewsStats (videoId: number, hour: number) {
207 const { setKey, videoKey } = this.generateVideoViewStatsKeys({ videoId, hour })
210 this.deleteFromSet(setKey, videoId.toString()),
211 this.deleteKey(videoKey)
215 /* ************ Local video views buffer ************ */
217 addLocalVideoView (videoId: number) {
218 const { videoKey, setKey } = this.generateLocalVideoViewsKeys(videoId)
221 this.addToSet(setKey, videoId.toString()),
222 this.increment(videoKey)
226 async getLocalVideoViews (videoId: number) {
227 const { videoKey } = this.generateLocalVideoViewsKeys(videoId)
229 const valueString = await this.getValue(videoKey)
230 const valueInt = parseInt(valueString, 10)
232 if (isNaN(valueInt)) {
233 logger.error('Cannot get videos views of video %d: views number is NaN (%s).', videoId, valueString)
240 async listLocalVideosViewed () {
241 const { setKey } = this.generateLocalVideoViewsKeys()
243 const stringIds = await this.getSet(setKey)
244 return stringIds.map(s => parseInt(s, 10))
247 deleteLocalVideoViews (videoId: number) {
248 const { setKey, videoKey } = this.generateLocalVideoViewsKeys(videoId)
251 this.deleteFromSet(setKey, videoId.toString()),
252 this.deleteKey(videoKey)
256 /* ************ Video viewers stats ************ */
258 getLocalVideoViewer (options: {
264 if (options.key) return this.getObject(options.key)
266 const { viewerKey } = this.generateLocalVideoViewerKeys(options.ip, options.videoId)
268 return this.getObject(viewerKey)
271 setLocalVideoViewer (ip: string, videoId: number, object: any) {
272 const { setKey, viewerKey } = this.generateLocalVideoViewerKeys(ip, videoId)
275 this.addToSet(setKey, viewerKey),
276 this.setObject(viewerKey, object)
280 listLocalVideoViewerKeys () {
281 const { setKey } = this.generateLocalVideoViewerKeys()
283 return this.getSet(setKey)
286 deleteLocalVideoViewersKeys (key: string) {
287 const { setKey } = this.generateLocalVideoViewerKeys()
290 this.deleteFromSet(setKey, key),
295 /* ************ Resumable uploads final responses ************ */
297 setUploadSession (uploadId: string, response?: { video: { id: number, shortUUID: string, uuid: string } }) {
298 return this.setValue(
299 'resumable-upload-' + uploadId,
301 ? JSON.stringify(response)
303 RESUMABLE_UPLOAD_SESSION_LIFETIME
307 doesUploadSessionExist (uploadId: string) {
308 return this.exists('resumable-upload-' + uploadId)
311 async getUploadSession (uploadId: string) {
312 const value = await this.getValue('resumable-upload-' + uploadId)
319 deleteUploadSession (uploadId: string) {
320 return this.deleteKey('resumable-upload-' + uploadId)
323 /* ************ AP resource unavailability ************ */
325 async addAPUnavailability (url: string) {
326 const key = this.generateAPUnavailabilityKey(url)
328 const value = await this.increment(key)
329 await this.setExpiration(key, AP_CLEANER.PERIOD * 2)
334 /* ************ Keys generation ************ */
336 private generateLocalVideoViewsKeys (videoId: number): { setKey: string, videoKey: string }
337 private generateLocalVideoViewsKeys (): { setKey: string }
338 private generateLocalVideoViewsKeys (videoId?: number) {
339 return { setKey: `local-video-views-buffer`, videoKey: `local-video-views-buffer-${videoId}` }
342 private generateLocalVideoViewerKeys (ip: string, videoId: number): { setKey: string, viewerKey: string }
343 private generateLocalVideoViewerKeys (): { setKey: string }
344 private generateLocalVideoViewerKeys (ip?: string, videoId?: number) {
345 return { setKey: `local-video-viewer-stats-keys`, viewerKey: `local-video-viewer-stats-${ip}-${videoId}` }
348 private generateVideoViewStatsKeys (options: { videoId?: number, hour?: number }) {
349 const hour = exists(options.hour)
351 : new Date().getHours()
353 return { setKey: `videos-view-h${hour}`, videoKey: `video-view-${options.videoId}-h${hour}` }
356 private generateResetPasswordKey (userId: number) {
357 return 'reset-password-' + userId
360 private generateTwoFactorRequestKey (userId: number, token: string) {
361 return 'two-factor-request-' + userId + '-' + token
364 private generateVerifyEmailKey (userId: number) {
365 return 'verify-email-' + userId
368 private generateIPViewKey (ip: string, videoUUID: string) {
369 return `views-${videoUUID}-${ip}`
372 private generateTrackerBlockIPKey (ip: string) {
373 return `tracker-block-ip-${ip}`
376 private generateContactFormKey (ip: string) {
377 return 'contact-form-' + ip
380 private generateAPUnavailabilityKey (url: string) {
381 return 'ap-unavailability-' + sha256(url)
384 /* ************ Redis helpers ************ */
386 private getValue (key: string) {
387 return this.client.get(this.prefix + key)
390 private getSet (key: string) {
391 return this.client.sMembers(this.prefix + key)
394 private addToSet (key: string, value: string) {
395 return this.client.sAdd(this.prefix + key, value)
398 private deleteFromSet (key: string, value: string) {
399 return this.client.sRem(this.prefix + key, value)
402 private deleteKey (key: string) {
403 return this.client.del(this.prefix + key)
406 private async getObject (key: string) {
407 const value = await this.getValue(key)
408 if (!value) return null
410 return JSON.parse(value)
413 private setObject (key: string, value: { [ id: string ]: number | string }, expirationMilliseconds?: number) {
414 return this.setValue(key, JSON.stringify(value), expirationMilliseconds)
417 private async setValue (key: string, value: string, expirationMilliseconds?: number) {
418 const options = expirationMilliseconds
419 ? { PX: expirationMilliseconds }
422 const result = await this.client.set(this.prefix + key, value, options)
424 if (result !== 'OK') throw new Error('Redis set result is not OK.')
427 private removeValue (key: string) {
428 return this.client.del(this.prefix + key)
431 private increment (key: string) {
432 return this.client.incr(this.prefix + key)
435 private async exists (key: string) {
436 const result = await this.client.exists(this.prefix + key)
441 private setExpiration (key: string, ms: number) {
442 return this.client.expire(this.prefix + key, ms / 1000)
445 static get Instance () {
446 return this.instance || (this.instance = new this())
450 // ---------------------------------------------------------------------------