1 import { createClient, RedisClientOptions, RedisModules, RedisScripts } 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'
19 // Only used for typings
20 // TODO: remove when https://github.com/microsoft/TypeScript/issues/37181 is fixed
21 const redisClientWrapperForType = () => createClient<{}, RedisScripts>()
25 private static instance: Redis
26 private initialized = false
27 private connected = false
28 private client: ReturnType<typeof redisClientWrapperForType>
29 private prefix: string
31 private constructor () {
35 // Already initialized
36 if (this.initialized === true) return
37 this.initialized = true
39 this.client = createClient(Redis.getRedisClientOptions())
41 logger.info('Connecting to redis...')
45 logger.info('Connected to redis.')
49 logger.error('Cannot connect to redis', { err })
53 this.prefix = 'redis-' + WEBSERVER.HOST + '-'
56 static getRedisClientOptions () {
57 let config: RedisClientOptions<RedisModules, {}> = {
59 connectTimeout: 20000 // Could be slow since node use sync call to compile PeerTube
63 if (CONFIG.REDIS.AUTH) {
64 config = { ...config, password: CONFIG.REDIS.AUTH }
67 if (CONFIG.REDIS.DB) {
68 config = { ...config, database: CONFIG.REDIS.DB }
71 if (CONFIG.REDIS.HOSTNAME && CONFIG.REDIS.PORT) {
72 config.socket = { ...config.socket, host: CONFIG.REDIS.HOSTNAME, port: CONFIG.REDIS.PORT }
74 config.socket = { ...config.socket, path: CONFIG.REDIS.SOCKET }
92 /* ************ Forgot password ************ */
94 async setResetPasswordVerificationString (userId: number) {
95 const generatedString = await generateRandomString(32)
97 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_RESET_LIFETIME)
99 return generatedString
102 async setCreatePasswordVerificationString (userId: number) {
103 const generatedString = await generateRandomString(32)
105 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_CREATE_LIFETIME)
107 return generatedString
110 async removePasswordVerificationString (userId: number) {
111 return this.removeValue(this.generateResetPasswordKey(userId))
114 async getResetPasswordLink (userId: number) {
115 return this.getValue(this.generateResetPasswordKey(userId))
118 /* ************ Email verification ************ */
120 async setVerifyEmailVerificationString (userId: number) {
121 const generatedString = await generateRandomString(32)
123 await this.setValue(this.generateVerifyEmailKey(userId), generatedString, USER_EMAIL_VERIFY_LIFETIME)
125 return generatedString
128 async getVerifyEmailLink (userId: number) {
129 return this.getValue(this.generateVerifyEmailKey(userId))
132 /* ************ Contact form per IP ************ */
134 async setContactFormIp (ip: string) {
135 return this.setValue(this.generateContactFormKey(ip), '1', CONTACT_FORM_LIFETIME)
138 async doesContactFormIpExist (ip: string) {
139 return this.exists(this.generateContactFormKey(ip))
142 /* ************ Views per IP ************ */
144 setIPVideoView (ip: string, videoUUID: string) {
145 return this.setValue(this.generateIPViewKey(ip, videoUUID), '1', VIEW_LIFETIME.VIEW)
148 async doesVideoIPViewExist (ip: string, videoUUID: string) {
149 return this.exists(this.generateIPViewKey(ip, videoUUID))
152 /* ************ Tracker IP block ************ */
154 setTrackerBlockIP (ip: string) {
155 return this.setValue(this.generateTrackerBlockIPKey(ip), '1', TRACKER_RATE_LIMITS.BLOCK_IP_LIFETIME)
158 async doesTrackerBlockIPExist (ip: string) {
159 return this.exists(this.generateTrackerBlockIPKey(ip))
162 /* ************ Video views stats ************ */
164 addVideoViewStats (videoId: number) {
165 const { videoKey, setKey } = this.generateVideoViewStatsKeys({ videoId })
168 this.addToSet(setKey, videoId.toString()),
169 this.increment(videoKey)
173 async getVideoViewsStats (videoId: number, hour: number) {
174 const { videoKey } = this.generateVideoViewStatsKeys({ videoId, hour })
176 const valueString = await this.getValue(videoKey)
177 const valueInt = parseInt(valueString, 10)
179 if (isNaN(valueInt)) {
180 logger.error('Cannot get videos views stats of video %d in hour %d: views number is NaN (%s).', videoId, hour, valueString)
187 async listVideosViewedForStats (hour: number) {
188 const { setKey } = this.generateVideoViewStatsKeys({ hour })
190 const stringIds = await this.getSet(setKey)
191 return stringIds.map(s => parseInt(s, 10))
194 deleteVideoViewsStats (videoId: number, hour: number) {
195 const { setKey, videoKey } = this.generateVideoViewStatsKeys({ videoId, hour })
198 this.deleteFromSet(setKey, videoId.toString()),
199 this.deleteKey(videoKey)
203 /* ************ Local video views buffer ************ */
205 addLocalVideoView (videoId: number) {
206 const { videoKey, setKey } = this.generateLocalVideoViewsKeys(videoId)
209 this.addToSet(setKey, videoId.toString()),
210 this.increment(videoKey)
214 async getLocalVideoViews (videoId: number) {
215 const { videoKey } = this.generateLocalVideoViewsKeys(videoId)
217 const valueString = await this.getValue(videoKey)
218 const valueInt = parseInt(valueString, 10)
220 if (isNaN(valueInt)) {
221 logger.error('Cannot get videos views of video %d: views number is NaN (%s).', videoId, valueString)
228 async listLocalVideosViewed () {
229 const { setKey } = this.generateLocalVideoViewsKeys()
231 const stringIds = await this.getSet(setKey)
232 return stringIds.map(s => parseInt(s, 10))
235 deleteLocalVideoViews (videoId: number) {
236 const { setKey, videoKey } = this.generateLocalVideoViewsKeys(videoId)
239 this.deleteFromSet(setKey, videoId.toString()),
240 this.deleteKey(videoKey)
244 /* ************ Video viewers stats ************ */
246 getLocalVideoViewer (options: {
252 if (options.key) return this.getObject(options.key)
254 const { viewerKey } = this.generateLocalVideoViewerKeys(options.ip, options.videoId)
256 return this.getObject(viewerKey)
259 setLocalVideoViewer (ip: string, videoId: number, object: any) {
260 const { setKey, viewerKey } = this.generateLocalVideoViewerKeys(ip, videoId)
263 this.addToSet(setKey, viewerKey),
264 this.setObject(viewerKey, object)
268 listLocalVideoViewerKeys () {
269 const { setKey } = this.generateLocalVideoViewerKeys()
271 return this.getSet(setKey)
274 deleteLocalVideoViewersKeys (key: string) {
275 const { setKey } = this.generateLocalVideoViewerKeys()
278 this.deleteFromSet(setKey, key),
283 /* ************ Resumable uploads final responses ************ */
285 setUploadSession (uploadId: string, response?: { video: { id: number, shortUUID: string, uuid: string } }) {
286 return this.setValue(
287 'resumable-upload-' + uploadId,
289 ? JSON.stringify(response)
291 RESUMABLE_UPLOAD_SESSION_LIFETIME
295 doesUploadSessionExist (uploadId: string) {
296 return this.exists('resumable-upload-' + uploadId)
299 async getUploadSession (uploadId: string) {
300 const value = await this.getValue('resumable-upload-' + uploadId)
307 deleteUploadSession (uploadId: string) {
308 return this.deleteKey('resumable-upload-' + uploadId)
311 /* ************ AP ressource unavailability ************ */
313 async addAPUnavailability (url: string) {
314 const key = this.generateAPUnavailabilityKey(url)
316 const value = await this.increment(key)
317 await this.setExpiration(key, AP_CLEANER.PERIOD * 2)
322 /* ************ Keys generation ************ */
324 private generateLocalVideoViewsKeys (videoId: number): { setKey: string, videoKey: string }
325 private generateLocalVideoViewsKeys (): { setKey: string }
326 private generateLocalVideoViewsKeys (videoId?: number) {
327 return { setKey: `local-video-views-buffer`, videoKey: `local-video-views-buffer-${videoId}` }
330 private generateLocalVideoViewerKeys (ip: string, videoId: number): { setKey: string, viewerKey: string }
331 private generateLocalVideoViewerKeys (): { setKey: string }
332 private generateLocalVideoViewerKeys (ip?: string, videoId?: number) {
333 return { setKey: `local-video-viewer-stats-keys`, viewerKey: `local-video-viewer-stats-${ip}-${videoId}` }
336 private generateVideoViewStatsKeys (options: { videoId?: number, hour?: number }) {
337 const hour = exists(options.hour)
339 : new Date().getHours()
341 return { setKey: `videos-view-h${hour}`, videoKey: `video-view-${options.videoId}-h${hour}` }
344 private generateResetPasswordKey (userId: number) {
345 return 'reset-password-' + userId
348 private generateVerifyEmailKey (userId: number) {
349 return 'verify-email-' + userId
352 private generateIPViewKey (ip: string, videoUUID: string) {
353 return `views-${videoUUID}-${ip}`
356 private generateTrackerBlockIPKey (ip: string) {
357 return `tracker-block-ip-${ip}`
360 private generateContactFormKey (ip: string) {
361 return 'contact-form-' + ip
364 private generateAPUnavailabilityKey (url: string) {
365 return 'ap-unavailability-' + sha256(url)
368 /* ************ Redis helpers ************ */
370 private getValue (key: string) {
371 return this.client.get(this.prefix + key)
374 private getSet (key: string) {
375 return this.client.sMembers(this.prefix + key)
378 private addToSet (key: string, value: string) {
379 return this.client.sAdd(this.prefix + key, value)
382 private deleteFromSet (key: string, value: string) {
383 return this.client.sRem(this.prefix + key, value)
386 private deleteKey (key: string) {
387 return this.client.del(this.prefix + key)
390 private async getObject (key: string) {
391 const value = await this.getValue(key)
392 if (!value) return null
394 return JSON.parse(value)
397 private setObject (key: string, value: { [ id: string ]: number | string }) {
398 return this.setValue(key, JSON.stringify(value))
401 private async setValue (key: string, value: string, expirationMilliseconds?: number) {
402 const options = expirationMilliseconds
403 ? { PX: expirationMilliseconds }
406 const result = await this.client.set(this.prefix + key, value, options)
408 if (result !== 'OK') throw new Error('Redis set result is not OK.')
411 private removeValue (key: string) {
412 return this.client.del(this.prefix + key)
415 private increment (key: string) {
416 return this.client.incr(this.prefix + key)
419 private async exists (key: string) {
420 const result = await this.client.exists(this.prefix + key)
425 private setExpiration (key: string, ms: number) {
426 return this.client.expire(this.prefix + key, ms / 1000)
429 static get Instance () {
430 return this.instance || (this.instance = new this())
434 // ---------------------------------------------------------------------------