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'
19 // Only used for typings
20 const redisClientWrapperForType = () => createClient<{}>()
24 private static instance: Redis
25 private initialized = false
26 private connected = false
27 private client: ReturnType<typeof redisClientWrapperForType>
28 private prefix: string
30 private constructor () {
34 // Already initialized
35 if (this.initialized === true) return
36 this.initialized = true
38 this.client = createClient(Redis.getRedisClientOptions())
40 logger.info('Connecting to redis...')
44 logger.info('Connected to redis.')
48 logger.error('Cannot connect to redis', { err })
52 this.prefix = 'redis-' + WEBSERVER.HOST + '-'
55 static getRedisClientOptions () {
56 let config: RedisClientOptions<RedisModules, {}> = {
58 connectTimeout: 20000 // Could be slow since node use sync call to compile PeerTube
62 if (CONFIG.REDIS.AUTH) {
63 config = { ...config, password: CONFIG.REDIS.AUTH }
66 if (CONFIG.REDIS.DB) {
67 config = { ...config, database: CONFIG.REDIS.DB }
70 if (CONFIG.REDIS.HOSTNAME && CONFIG.REDIS.PORT) {
71 config.socket = { ...config.socket, host: CONFIG.REDIS.HOSTNAME, port: CONFIG.REDIS.PORT }
73 config.socket = { ...config.socket, path: CONFIG.REDIS.SOCKET }
91 /* ************ Forgot password ************ */
93 async setResetPasswordVerificationString (userId: number) {
94 const generatedString = await generateRandomString(32)
96 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_RESET_LIFETIME)
98 return generatedString
101 async setCreatePasswordVerificationString (userId: number) {
102 const generatedString = await generateRandomString(32)
104 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_CREATE_LIFETIME)
106 return generatedString
109 async removePasswordVerificationString (userId: number) {
110 return this.removeValue(this.generateResetPasswordKey(userId))
113 async getResetPasswordLink (userId: number) {
114 return this.getValue(this.generateResetPasswordKey(userId))
117 /* ************ Email verification ************ */
119 async setVerifyEmailVerificationString (userId: number) {
120 const generatedString = await generateRandomString(32)
122 await this.setValue(this.generateVerifyEmailKey(userId), generatedString, USER_EMAIL_VERIFY_LIFETIME)
124 return generatedString
127 async getVerifyEmailLink (userId: number) {
128 return this.getValue(this.generateVerifyEmailKey(userId))
131 /* ************ Contact form per IP ************ */
133 async setContactFormIp (ip: string) {
134 return this.setValue(this.generateContactFormKey(ip), '1', CONTACT_FORM_LIFETIME)
137 async doesContactFormIpExist (ip: string) {
138 return this.exists(this.generateContactFormKey(ip))
141 /* ************ Views per IP ************ */
143 setIPVideoView (ip: string, videoUUID: string) {
144 return this.setValue(this.generateIPViewKey(ip, videoUUID), '1', VIEW_LIFETIME.VIEW)
147 setIPVideoViewer (ip: string, videoUUID: string) {
148 return this.setValue(this.generateIPViewerKey(ip, videoUUID), '1', VIEW_LIFETIME.VIEWER)
151 async doesVideoIPViewExist (ip: string, videoUUID: string) {
152 return this.exists(this.generateIPViewKey(ip, videoUUID))
155 async doesVideoIPViewerExist (ip: string, videoUUID: string) {
156 return this.exists(this.generateIPViewerKey(ip, videoUUID))
159 /* ************ Tracker IP block ************ */
161 setTrackerBlockIP (ip: string) {
162 return this.setValue(this.generateTrackerBlockIPKey(ip), '1', TRACKER_RATE_LIMITS.BLOCK_IP_LIFETIME)
165 async doesTrackerBlockIPExist (ip: string) {
166 return this.exists(this.generateTrackerBlockIPKey(ip))
169 /* ************ Video views stats ************ */
171 addVideoViewStats (videoId: number) {
172 const { videoKey, setKey } = this.generateVideoViewStatsKeys({ videoId })
175 this.addToSet(setKey, videoId.toString()),
176 this.increment(videoKey)
180 async getVideoViewsStats (videoId: number, hour: number) {
181 const { videoKey } = this.generateVideoViewStatsKeys({ videoId, hour })
183 const valueString = await this.getValue(videoKey)
184 const valueInt = parseInt(valueString, 10)
186 if (isNaN(valueInt)) {
187 logger.error('Cannot get videos views stats of video %d in hour %d: views number is NaN (%s).', videoId, hour, valueString)
194 async listVideosViewedForStats (hour: number) {
195 const { setKey } = this.generateVideoViewStatsKeys({ hour })
197 const stringIds = await this.getSet(setKey)
198 return stringIds.map(s => parseInt(s, 10))
201 deleteVideoViewsStats (videoId: number, hour: number) {
202 const { setKey, videoKey } = this.generateVideoViewStatsKeys({ videoId, hour })
205 this.deleteFromSet(setKey, videoId.toString()),
206 this.deleteKey(videoKey)
210 /* ************ Local video views buffer ************ */
212 addLocalVideoView (videoId: number) {
213 const { videoKey, setKey } = this.generateLocalVideoViewsKeys(videoId)
216 this.addToSet(setKey, videoId.toString()),
217 this.increment(videoKey)
221 async getLocalVideoViews (videoId: number) {
222 const { videoKey } = this.generateLocalVideoViewsKeys(videoId)
224 const valueString = await this.getValue(videoKey)
225 const valueInt = parseInt(valueString, 10)
227 if (isNaN(valueInt)) {
228 logger.error('Cannot get videos views of video %d: views number is NaN (%s).', videoId, valueString)
235 async listLocalVideosViewed () {
236 const { setKey } = this.generateLocalVideoViewsKeys()
238 const stringIds = await this.getSet(setKey)
239 return stringIds.map(s => parseInt(s, 10))
242 deleteLocalVideoViews (videoId: number) {
243 const { setKey, videoKey } = this.generateLocalVideoViewsKeys(videoId)
246 this.deleteFromSet(setKey, videoId.toString()),
247 this.deleteKey(videoKey)
251 /* ************ Resumable uploads final responses ************ */
253 setUploadSession (uploadId: string, response?: { video: { id: number, shortUUID: string, uuid: string } }) {
254 return this.setValue(
255 'resumable-upload-' + uploadId,
257 ? JSON.stringify(response)
259 RESUMABLE_UPLOAD_SESSION_LIFETIME
263 doesUploadSessionExist (uploadId: string) {
264 return this.exists('resumable-upload-' + uploadId)
267 async getUploadSession (uploadId: string) {
268 const value = await this.getValue('resumable-upload-' + uploadId)
275 deleteUploadSession (uploadId: string) {
276 return this.deleteKey('resumable-upload-' + uploadId)
279 /* ************ AP ressource unavailability ************ */
281 async addAPUnavailability (url: string) {
282 const key = this.generateAPUnavailabilityKey(url)
284 const value = await this.increment(key)
285 await this.setExpiration(key, AP_CLEANER.PERIOD * 2)
290 /* ************ Keys generation ************ */
292 private generateLocalVideoViewsKeys (videoId?: Number) {
293 return { setKey: `local-video-views-buffer`, videoKey: `local-video-views-buffer-${videoId}` }
296 private generateVideoViewStatsKeys (options: { videoId?: number, hour?: number }) {
297 const hour = exists(options.hour)
299 : new Date().getHours()
301 return { setKey: `videos-view-h${hour}`, videoKey: `video-view-${options.videoId}-h${hour}` }
304 private generateResetPasswordKey (userId: number) {
305 return 'reset-password-' + userId
308 private generateVerifyEmailKey (userId: number) {
309 return 'verify-email-' + userId
312 private generateIPViewKey (ip: string, videoUUID: string) {
313 return `views-${videoUUID}-${ip}`
316 private generateIPViewerKey (ip: string, videoUUID: string) {
317 return `viewer-${videoUUID}-${ip}`
320 private generateTrackerBlockIPKey (ip: string) {
321 return `tracker-block-ip-${ip}`
324 private generateContactFormKey (ip: string) {
325 return 'contact-form-' + ip
328 private generateAPUnavailabilityKey (url: string) {
329 return 'ap-unavailability-' + sha256(url)
332 /* ************ Redis helpers ************ */
334 private getValue (key: string) {
335 return this.client.get(this.prefix + key)
338 private getSet (key: string) {
339 return this.client.sMembers(this.prefix + key)
342 private addToSet (key: string, value: string) {
343 return this.client.sAdd(this.prefix + key, value)
346 private deleteFromSet (key: string, value: string) {
347 return this.client.sRem(this.prefix + key, value)
350 private deleteKey (key: string) {
351 return this.client.del(this.prefix + key)
354 private async setValue (key: string, value: string, expirationMilliseconds: number) {
355 const result = await this.client.set(this.prefix + key, value, { PX: expirationMilliseconds })
357 if (result !== 'OK') throw new Error('Redis set result is not OK.')
360 private removeValue (key: string) {
361 return this.client.del(this.prefix + key)
364 private increment (key: string) {
365 return this.client.incr(this.prefix + key)
368 private async exists (key: string) {
369 const result = await this.client.exists(this.prefix + key)
374 private setExpiration (key: string, ms: number) {
375 return this.client.expire(this.prefix + key, ms / 1000)
378 static get Instance () {
379 return this.instance || (this.instance = new this())
383 // ---------------------------------------------------------------------------