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 USER_EMAIL_VERIFY_LIFETIME,
13 USER_PASSWORD_CREATE_LIFETIME,
14 USER_PASSWORD_RESET_LIFETIME,
17 } from '../initializers/constants'
21 private static instance: Redis
22 private initialized = false
23 private connected = false
24 private client: ReturnType<typeof createClient>
25 private prefix: string
27 private constructor () {
31 // Already initialized
32 if (this.initialized === true) return
33 this.initialized = true
35 this.client = createClient(Redis.getRedisClientOptions())
36 this.client.on('error', err => logger.error('Redis Client Error', { err }))
38 logger.info('Connecting to redis...')
42 logger.info('Connected to redis.')
46 logger.error('Cannot connect to redis', { err })
50 this.prefix = 'redis-' + WEBSERVER.HOST + '-'
53 static getRedisClientOptions () {
54 let config: RedisClientOptions<RedisModules, {}> = {
56 connectTimeout: 20000 // Could be slow since node use sync call to compile PeerTube
60 if (CONFIG.REDIS.AUTH) {
61 config = { ...config, password: CONFIG.REDIS.AUTH }
64 if (CONFIG.REDIS.DB) {
65 config = { ...config, database: CONFIG.REDIS.DB }
68 if (CONFIG.REDIS.HOSTNAME && CONFIG.REDIS.PORT) {
69 config.socket = { ...config.socket, host: CONFIG.REDIS.HOSTNAME, port: CONFIG.REDIS.PORT }
71 config.socket = { ...config.socket, path: CONFIG.REDIS.SOCKET }
89 /* ************ Forgot password ************ */
91 async setResetPasswordVerificationString (userId: number) {
92 const generatedString = await generateRandomString(32)
94 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_RESET_LIFETIME)
96 return generatedString
99 async setCreatePasswordVerificationString (userId: number) {
100 const generatedString = await generateRandomString(32)
102 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_CREATE_LIFETIME)
104 return generatedString
107 async removePasswordVerificationString (userId: number) {
108 return this.removeValue(this.generateResetPasswordKey(userId))
111 async getResetPasswordLink (userId: number) {
112 return this.getValue(this.generateResetPasswordKey(userId))
115 /* ************ Email verification ************ */
117 async setVerifyEmailVerificationString (userId: number) {
118 const generatedString = await generateRandomString(32)
120 await this.setValue(this.generateVerifyEmailKey(userId), generatedString, USER_EMAIL_VERIFY_LIFETIME)
122 return generatedString
125 async getVerifyEmailLink (userId: number) {
126 return this.getValue(this.generateVerifyEmailKey(userId))
129 /* ************ Contact form per IP ************ */
131 async setContactFormIp (ip: string) {
132 return this.setValue(this.generateContactFormKey(ip), '1', CONTACT_FORM_LIFETIME)
135 async doesContactFormIpExist (ip: string) {
136 return this.exists(this.generateContactFormKey(ip))
139 /* ************ Views per IP ************ */
141 setIPVideoView (ip: string, videoUUID: string) {
142 return this.setValue(this.generateIPViewKey(ip, videoUUID), '1', VIEW_LIFETIME.VIEW)
145 async doesVideoIPViewExist (ip: string, videoUUID: string) {
146 return this.exists(this.generateIPViewKey(ip, videoUUID))
149 /* ************ Tracker IP block ************ */
151 setTrackerBlockIP (ip: string) {
152 return this.setValue(this.generateTrackerBlockIPKey(ip), '1', TRACKER_RATE_LIMITS.BLOCK_IP_LIFETIME)
155 async doesTrackerBlockIPExist (ip: string) {
156 return this.exists(this.generateTrackerBlockIPKey(ip))
159 /* ************ Video views stats ************ */
161 addVideoViewStats (videoId: number) {
162 const { videoKey, setKey } = this.generateVideoViewStatsKeys({ videoId })
165 this.addToSet(setKey, videoId.toString()),
166 this.increment(videoKey)
170 async getVideoViewsStats (videoId: number, hour: number) {
171 const { videoKey } = this.generateVideoViewStatsKeys({ videoId, hour })
173 const valueString = await this.getValue(videoKey)
174 const valueInt = parseInt(valueString, 10)
176 if (isNaN(valueInt)) {
177 logger.error('Cannot get videos views stats of video %d in hour %d: views number is NaN (%s).', videoId, hour, valueString)
184 async listVideosViewedForStats (hour: number) {
185 const { setKey } = this.generateVideoViewStatsKeys({ hour })
187 const stringIds = await this.getSet(setKey)
188 return stringIds.map(s => parseInt(s, 10))
191 deleteVideoViewsStats (videoId: number, hour: number) {
192 const { setKey, videoKey } = this.generateVideoViewStatsKeys({ videoId, hour })
195 this.deleteFromSet(setKey, videoId.toString()),
196 this.deleteKey(videoKey)
200 /* ************ Local video views buffer ************ */
202 addLocalVideoView (videoId: number) {
203 const { videoKey, setKey } = this.generateLocalVideoViewsKeys(videoId)
206 this.addToSet(setKey, videoId.toString()),
207 this.increment(videoKey)
211 async getLocalVideoViews (videoId: number) {
212 const { videoKey } = this.generateLocalVideoViewsKeys(videoId)
214 const valueString = await this.getValue(videoKey)
215 const valueInt = parseInt(valueString, 10)
217 if (isNaN(valueInt)) {
218 logger.error('Cannot get videos views of video %d: views number is NaN (%s).', videoId, valueString)
225 async listLocalVideosViewed () {
226 const { setKey } = this.generateLocalVideoViewsKeys()
228 const stringIds = await this.getSet(setKey)
229 return stringIds.map(s => parseInt(s, 10))
232 deleteLocalVideoViews (videoId: number) {
233 const { setKey, videoKey } = this.generateLocalVideoViewsKeys(videoId)
236 this.deleteFromSet(setKey, videoId.toString()),
237 this.deleteKey(videoKey)
241 /* ************ Video viewers stats ************ */
243 getLocalVideoViewer (options: {
249 if (options.key) return this.getObject(options.key)
251 const { viewerKey } = this.generateLocalVideoViewerKeys(options.ip, options.videoId)
253 return this.getObject(viewerKey)
256 setLocalVideoViewer (ip: string, videoId: number, object: any) {
257 const { setKey, viewerKey } = this.generateLocalVideoViewerKeys(ip, videoId)
260 this.addToSet(setKey, viewerKey),
261 this.setObject(viewerKey, object)
265 listLocalVideoViewerKeys () {
266 const { setKey } = this.generateLocalVideoViewerKeys()
268 return this.getSet(setKey)
271 deleteLocalVideoViewersKeys (key: string) {
272 const { setKey } = this.generateLocalVideoViewerKeys()
275 this.deleteFromSet(setKey, key),
280 /* ************ Resumable uploads final responses ************ */
282 setUploadSession (uploadId: string, response?: { video: { id: number, shortUUID: string, uuid: string } }) {
283 return this.setValue(
284 'resumable-upload-' + uploadId,
286 ? JSON.stringify(response)
288 RESUMABLE_UPLOAD_SESSION_LIFETIME
292 doesUploadSessionExist (uploadId: string) {
293 return this.exists('resumable-upload-' + uploadId)
296 async getUploadSession (uploadId: string) {
297 const value = await this.getValue('resumable-upload-' + uploadId)
304 deleteUploadSession (uploadId: string) {
305 return this.deleteKey('resumable-upload-' + uploadId)
308 /* ************ AP resource unavailability ************ */
310 async addAPUnavailability (url: string) {
311 const key = this.generateAPUnavailabilityKey(url)
313 const value = await this.increment(key)
314 await this.setExpiration(key, AP_CLEANER.PERIOD * 2)
319 /* ************ Keys generation ************ */
321 private generateLocalVideoViewsKeys (videoId: number): { setKey: string, videoKey: string }
322 private generateLocalVideoViewsKeys (): { setKey: string }
323 private generateLocalVideoViewsKeys (videoId?: number) {
324 return { setKey: `local-video-views-buffer`, videoKey: `local-video-views-buffer-${videoId}` }
327 private generateLocalVideoViewerKeys (ip: string, videoId: number): { setKey: string, viewerKey: string }
328 private generateLocalVideoViewerKeys (): { setKey: string }
329 private generateLocalVideoViewerKeys (ip?: string, videoId?: number) {
330 return { setKey: `local-video-viewer-stats-keys`, viewerKey: `local-video-viewer-stats-${ip}-${videoId}` }
333 private generateVideoViewStatsKeys (options: { videoId?: number, hour?: number }) {
334 const hour = exists(options.hour)
336 : new Date().getHours()
338 return { setKey: `videos-view-h${hour}`, videoKey: `video-view-${options.videoId}-h${hour}` }
341 private generateResetPasswordKey (userId: number) {
342 return 'reset-password-' + userId
345 private generateVerifyEmailKey (userId: number) {
346 return 'verify-email-' + userId
349 private generateIPViewKey (ip: string, videoUUID: string) {
350 return `views-${videoUUID}-${ip}`
353 private generateTrackerBlockIPKey (ip: string) {
354 return `tracker-block-ip-${ip}`
357 private generateContactFormKey (ip: string) {
358 return 'contact-form-' + ip
361 private generateAPUnavailabilityKey (url: string) {
362 return 'ap-unavailability-' + sha256(url)
365 /* ************ Redis helpers ************ */
367 private getValue (key: string) {
368 return this.client.get(this.prefix + key)
371 private getSet (key: string) {
372 return this.client.sMembers(this.prefix + key)
375 private addToSet (key: string, value: string) {
376 return this.client.sAdd(this.prefix + key, value)
379 private deleteFromSet (key: string, value: string) {
380 return this.client.sRem(this.prefix + key, value)
383 private deleteKey (key: string) {
384 return this.client.del(this.prefix + key)
387 private async getObject (key: string) {
388 const value = await this.getValue(key)
389 if (!value) return null
391 return JSON.parse(value)
394 private setObject (key: string, value: { [ id: string ]: number | string }) {
395 return this.setValue(key, JSON.stringify(value))
398 private async setValue (key: string, value: string, expirationMilliseconds?: number) {
399 const options = expirationMilliseconds
400 ? { PX: expirationMilliseconds }
403 const result = await this.client.set(this.prefix + key, value, options)
405 if (result !== 'OK') throw new Error('Redis set result is not OK.')
408 private removeValue (key: string) {
409 return this.client.del(this.prefix + key)
412 private increment (key: string) {
413 return this.client.incr(this.prefix + key)
416 private async exists (key: string) {
417 const result = await this.client.exists(this.prefix + key)
422 private setExpiration (key: string, ms: number) {
423 return this.client.expire(this.prefix + key, ms / 1000)
426 static get Instance () {
427 return this.instance || (this.instance = new this())
431 // ---------------------------------------------------------------------------