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())
37 logger.info('Connecting to redis...')
41 logger.info('Connected to redis.')
45 logger.error('Cannot connect to redis', { err })
49 this.prefix = 'redis-' + WEBSERVER.HOST + '-'
52 static getRedisClientOptions () {
53 let config: RedisClientOptions<RedisModules, {}> = {
55 connectTimeout: 20000 // Could be slow since node use sync call to compile PeerTube
59 if (CONFIG.REDIS.AUTH) {
60 config = { ...config, password: CONFIG.REDIS.AUTH }
63 if (CONFIG.REDIS.DB) {
64 config = { ...config, database: CONFIG.REDIS.DB }
67 if (CONFIG.REDIS.HOSTNAME && CONFIG.REDIS.PORT) {
68 config.socket = { ...config.socket, host: CONFIG.REDIS.HOSTNAME, port: CONFIG.REDIS.PORT }
70 config.socket = { ...config.socket, path: CONFIG.REDIS.SOCKET }
88 /* ************ Forgot password ************ */
90 async setResetPasswordVerificationString (userId: number) {
91 const generatedString = await generateRandomString(32)
93 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_RESET_LIFETIME)
95 return generatedString
98 async setCreatePasswordVerificationString (userId: number) {
99 const generatedString = await generateRandomString(32)
101 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_CREATE_LIFETIME)
103 return generatedString
106 async removePasswordVerificationString (userId: number) {
107 return this.removeValue(this.generateResetPasswordKey(userId))
110 async getResetPasswordLink (userId: number) {
111 return this.getValue(this.generateResetPasswordKey(userId))
114 /* ************ Email verification ************ */
116 async setVerifyEmailVerificationString (userId: number) {
117 const generatedString = await generateRandomString(32)
119 await this.setValue(this.generateVerifyEmailKey(userId), generatedString, USER_EMAIL_VERIFY_LIFETIME)
121 return generatedString
124 async getVerifyEmailLink (userId: number) {
125 return this.getValue(this.generateVerifyEmailKey(userId))
128 /* ************ Contact form per IP ************ */
130 async setContactFormIp (ip: string) {
131 return this.setValue(this.generateContactFormKey(ip), '1', CONTACT_FORM_LIFETIME)
134 async doesContactFormIpExist (ip: string) {
135 return this.exists(this.generateContactFormKey(ip))
138 /* ************ Views per IP ************ */
140 setIPVideoView (ip: string, videoUUID: string) {
141 return this.setValue(this.generateIPViewKey(ip, videoUUID), '1', VIEW_LIFETIME.VIEW)
144 async doesVideoIPViewExist (ip: string, videoUUID: string) {
145 return this.exists(this.generateIPViewKey(ip, videoUUID))
148 /* ************ Tracker IP block ************ */
150 setTrackerBlockIP (ip: string) {
151 return this.setValue(this.generateTrackerBlockIPKey(ip), '1', TRACKER_RATE_LIMITS.BLOCK_IP_LIFETIME)
154 async doesTrackerBlockIPExist (ip: string) {
155 return this.exists(this.generateTrackerBlockIPKey(ip))
158 /* ************ Video views stats ************ */
160 addVideoViewStats (videoId: number) {
161 const { videoKey, setKey } = this.generateVideoViewStatsKeys({ videoId })
164 this.addToSet(setKey, videoId.toString()),
165 this.increment(videoKey)
169 async getVideoViewsStats (videoId: number, hour: number) {
170 const { videoKey } = this.generateVideoViewStatsKeys({ videoId, hour })
172 const valueString = await this.getValue(videoKey)
173 const valueInt = parseInt(valueString, 10)
175 if (isNaN(valueInt)) {
176 logger.error('Cannot get videos views stats of video %d in hour %d: views number is NaN (%s).', videoId, hour, valueString)
183 async listVideosViewedForStats (hour: number) {
184 const { setKey } = this.generateVideoViewStatsKeys({ hour })
186 const stringIds = await this.getSet(setKey)
187 return stringIds.map(s => parseInt(s, 10))
190 deleteVideoViewsStats (videoId: number, hour: number) {
191 const { setKey, videoKey } = this.generateVideoViewStatsKeys({ videoId, hour })
194 this.deleteFromSet(setKey, videoId.toString()),
195 this.deleteKey(videoKey)
199 /* ************ Local video views buffer ************ */
201 addLocalVideoView (videoId: number) {
202 const { videoKey, setKey } = this.generateLocalVideoViewsKeys(videoId)
205 this.addToSet(setKey, videoId.toString()),
206 this.increment(videoKey)
210 async getLocalVideoViews (videoId: number) {
211 const { videoKey } = this.generateLocalVideoViewsKeys(videoId)
213 const valueString = await this.getValue(videoKey)
214 const valueInt = parseInt(valueString, 10)
216 if (isNaN(valueInt)) {
217 logger.error('Cannot get videos views of video %d: views number is NaN (%s).', videoId, valueString)
224 async listLocalVideosViewed () {
225 const { setKey } = this.generateLocalVideoViewsKeys()
227 const stringIds = await this.getSet(setKey)
228 return stringIds.map(s => parseInt(s, 10))
231 deleteLocalVideoViews (videoId: number) {
232 const { setKey, videoKey } = this.generateLocalVideoViewsKeys(videoId)
235 this.deleteFromSet(setKey, videoId.toString()),
236 this.deleteKey(videoKey)
240 /* ************ Video viewers stats ************ */
242 getLocalVideoViewer (options: {
248 if (options.key) return this.getObject(options.key)
250 const { viewerKey } = this.generateLocalVideoViewerKeys(options.ip, options.videoId)
252 return this.getObject(viewerKey)
255 setLocalVideoViewer (ip: string, videoId: number, object: any) {
256 const { setKey, viewerKey } = this.generateLocalVideoViewerKeys(ip, videoId)
259 this.addToSet(setKey, viewerKey),
260 this.setObject(viewerKey, object)
264 listLocalVideoViewerKeys () {
265 const { setKey } = this.generateLocalVideoViewerKeys()
267 return this.getSet(setKey)
270 deleteLocalVideoViewersKeys (key: string) {
271 const { setKey } = this.generateLocalVideoViewerKeys()
274 this.deleteFromSet(setKey, key),
279 /* ************ Resumable uploads final responses ************ */
281 setUploadSession (uploadId: string, response?: { video: { id: number, shortUUID: string, uuid: string } }) {
282 return this.setValue(
283 'resumable-upload-' + uploadId,
285 ? JSON.stringify(response)
287 RESUMABLE_UPLOAD_SESSION_LIFETIME
291 doesUploadSessionExist (uploadId: string) {
292 return this.exists('resumable-upload-' + uploadId)
295 async getUploadSession (uploadId: string) {
296 const value = await this.getValue('resumable-upload-' + uploadId)
303 deleteUploadSession (uploadId: string) {
304 return this.deleteKey('resumable-upload-' + uploadId)
307 /* ************ AP resource unavailability ************ */
309 async addAPUnavailability (url: string) {
310 const key = this.generateAPUnavailabilityKey(url)
312 const value = await this.increment(key)
313 await this.setExpiration(key, AP_CLEANER.PERIOD * 2)
318 /* ************ Keys generation ************ */
320 private generateLocalVideoViewsKeys (videoId: number): { setKey: string, videoKey: string }
321 private generateLocalVideoViewsKeys (): { setKey: string }
322 private generateLocalVideoViewsKeys (videoId?: number) {
323 return { setKey: `local-video-views-buffer`, videoKey: `local-video-views-buffer-${videoId}` }
326 private generateLocalVideoViewerKeys (ip: string, videoId: number): { setKey: string, viewerKey: string }
327 private generateLocalVideoViewerKeys (): { setKey: string }
328 private generateLocalVideoViewerKeys (ip?: string, videoId?: number) {
329 return { setKey: `local-video-viewer-stats-keys`, viewerKey: `local-video-viewer-stats-${ip}-${videoId}` }
332 private generateVideoViewStatsKeys (options: { videoId?: number, hour?: number }) {
333 const hour = exists(options.hour)
335 : new Date().getHours()
337 return { setKey: `videos-view-h${hour}`, videoKey: `video-view-${options.videoId}-h${hour}` }
340 private generateResetPasswordKey (userId: number) {
341 return 'reset-password-' + userId
344 private generateVerifyEmailKey (userId: number) {
345 return 'verify-email-' + userId
348 private generateIPViewKey (ip: string, videoUUID: string) {
349 return `views-${videoUUID}-${ip}`
352 private generateTrackerBlockIPKey (ip: string) {
353 return `tracker-block-ip-${ip}`
356 private generateContactFormKey (ip: string) {
357 return 'contact-form-' + ip
360 private generateAPUnavailabilityKey (url: string) {
361 return 'ap-unavailability-' + sha256(url)
364 /* ************ Redis helpers ************ */
366 private getValue (key: string) {
367 return this.client.get(this.prefix + key)
370 private getSet (key: string) {
371 return this.client.sMembers(this.prefix + key)
374 private addToSet (key: string, value: string) {
375 return this.client.sAdd(this.prefix + key, value)
378 private deleteFromSet (key: string, value: string) {
379 return this.client.sRem(this.prefix + key, value)
382 private deleteKey (key: string) {
383 return this.client.del(this.prefix + key)
386 private async getObject (key: string) {
387 const value = await this.getValue(key)
388 if (!value) return null
390 return JSON.parse(value)
393 private setObject (key: string, value: { [ id: string ]: number | string }) {
394 return this.setValue(key, JSON.stringify(value))
397 private async setValue (key: string, value: string, expirationMilliseconds?: number) {
398 const options = expirationMilliseconds
399 ? { PX: expirationMilliseconds }
402 const result = await this.client.set(this.prefix + key, value, options)
404 if (result !== 'OK') throw new Error('Redis set result is not OK.')
407 private removeValue (key: string) {
408 return this.client.del(this.prefix + key)
411 private increment (key: string) {
412 return this.client.incr(this.prefix + key)
415 private async exists (key: string) {
416 const result = await this.client.exists(this.prefix + key)
421 private setExpiration (key: string, ms: number) {
422 return this.client.expire(this.prefix + key, ms / 1000)
425 static get Instance () {
426 return this.instance || (this.instance = new this())
430 // ---------------------------------------------------------------------------