1 import IoRedis, { RedisOptions } from 'ioredis'
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,
11 TWO_FACTOR_AUTH_REQUEST_TOKEN_LIFETIME,
12 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: IoRedis
25 private prefix: string
27 private constructor () {
31 // Already initialized
32 if (this.initialized === true) return
33 this.initialized = true
35 logger.info('Connecting to redis...')
37 this.client = new IoRedis(Redis.getRedisClientOptions('', { enableAutoPipelining: true }))
38 this.client.on('error', err => logger.error('Redis failed to connect', { err }))
39 this.client.on('connect', () => {
40 logger.info('Connected to redis.')
44 this.client.on('reconnecting', (ms) => {
45 logger.error(`Reconnecting to redis in ${ms}.`)
47 this.client.on('close', () => {
48 logger.error('Connection to redis has closed.')
49 this.connected = false
52 this.client.on('end', () => {
53 logger.error('Connection to redis has closed and no more reconnects will be done.')
56 this.prefix = 'redis-' + WEBSERVER.HOST + '-'
59 static getRedisClientOptions (connectionName?: string, options: RedisOptions = {}): RedisOptions {
61 connectionName: [ 'PeerTube', connectionName ].join(''),
62 connectTimeout: 20000, // Could be slow since node use sync call to compile PeerTube
63 password: CONFIG.REDIS.AUTH,
65 host: CONFIG.REDIS.HOSTNAME,
66 port: CONFIG.REDIS.PORT,
67 path: CONFIG.REDIS.SOCKET,
68 showFriendlyErrorStack: true,
85 /* ************ Forgot password ************ */
87 async setResetPasswordVerificationString (userId: number) {
88 const generatedString = await generateRandomString(32)
90 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_RESET_LIFETIME)
92 return generatedString
95 async setCreatePasswordVerificationString (userId: number) {
96 const generatedString = await generateRandomString(32)
98 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_CREATE_LIFETIME)
100 return generatedString
103 async removePasswordVerificationString (userId: number) {
104 return this.removeValue(this.generateResetPasswordKey(userId))
107 async getResetPasswordVerificationString (userId: number) {
108 return this.getValue(this.generateResetPasswordKey(userId))
111 /* ************ Two factor auth request ************ */
113 async setTwoFactorRequest (userId: number, otpSecret: string) {
114 const requestToken = await generateRandomString(32)
116 await this.setValue(this.generateTwoFactorRequestKey(userId, requestToken), otpSecret, TWO_FACTOR_AUTH_REQUEST_TOKEN_LIFETIME)
121 async getTwoFactorRequestToken (userId: number, requestToken: string) {
122 return this.getValue(this.generateTwoFactorRequestKey(userId, requestToken))
125 /* ************ Email verification ************ */
127 async setUserVerifyEmailVerificationString (userId: number) {
128 const generatedString = await generateRandomString(32)
130 await this.setValue(this.generateUserVerifyEmailKey(userId), generatedString, EMAIL_VERIFY_LIFETIME)
132 return generatedString
135 async getUserVerifyEmailLink (userId: number) {
136 return this.getValue(this.generateUserVerifyEmailKey(userId))
139 async setRegistrationVerifyEmailVerificationString (registrationId: number) {
140 const generatedString = await generateRandomString(32)
142 await this.setValue(this.generateRegistrationVerifyEmailKey(registrationId), generatedString, EMAIL_VERIFY_LIFETIME)
144 return generatedString
147 async getRegistrationVerifyEmailLink (registrationId: number) {
148 return this.getValue(this.generateRegistrationVerifyEmailKey(registrationId))
151 /* ************ Contact form per IP ************ */
153 async setContactFormIp (ip: string) {
154 return this.setValue(this.generateContactFormKey(ip), '1', CONTACT_FORM_LIFETIME)
157 async doesContactFormIpExist (ip: string) {
158 return this.exists(this.generateContactFormKey(ip))
161 /* ************ Views per IP ************ */
163 setIPVideoView (ip: string, videoUUID: string) {
164 return this.setValue(this.generateIPViewKey(ip, videoUUID), '1', VIEW_LIFETIME.VIEW)
167 async doesVideoIPViewExist (ip: string, videoUUID: string) {
168 return this.exists(this.generateIPViewKey(ip, videoUUID))
171 /* ************ Video views stats ************ */
173 addVideoViewStats (videoId: number) {
174 const { videoKey, setKey } = this.generateVideoViewStatsKeys({ videoId })
177 this.addToSet(setKey, videoId.toString()),
178 this.increment(videoKey)
182 async getVideoViewsStats (videoId: number, hour: number) {
183 const { videoKey } = this.generateVideoViewStatsKeys({ videoId, hour })
185 const valueString = await this.getValue(videoKey)
186 const valueInt = parseInt(valueString, 10)
188 if (isNaN(valueInt)) {
189 logger.error('Cannot get videos views stats of video %d in hour %d: views number is NaN (%s).', videoId, hour, valueString)
196 async listVideosViewedForStats (hour: number) {
197 const { setKey } = this.generateVideoViewStatsKeys({ hour })
199 const stringIds = await this.getSet(setKey)
200 return stringIds.map(s => parseInt(s, 10))
203 deleteVideoViewsStats (videoId: number, hour: number) {
204 const { setKey, videoKey } = this.generateVideoViewStatsKeys({ videoId, hour })
207 this.deleteFromSet(setKey, videoId.toString()),
208 this.deleteKey(videoKey)
212 /* ************ Local video views buffer ************ */
214 addLocalVideoView (videoId: number) {
215 const { videoKey, setKey } = this.generateLocalVideoViewsKeys(videoId)
218 this.addToSet(setKey, videoId.toString()),
219 this.increment(videoKey)
223 async getLocalVideoViews (videoId: number) {
224 const { videoKey } = this.generateLocalVideoViewsKeys(videoId)
226 const valueString = await this.getValue(videoKey)
227 const valueInt = parseInt(valueString, 10)
229 if (isNaN(valueInt)) {
230 logger.error('Cannot get videos views of video %d: views number is NaN (%s).', videoId, valueString)
237 async listLocalVideosViewed () {
238 const { setKey } = this.generateLocalVideoViewsKeys()
240 const stringIds = await this.getSet(setKey)
241 return stringIds.map(s => parseInt(s, 10))
244 deleteLocalVideoViews (videoId: number) {
245 const { setKey, videoKey } = this.generateLocalVideoViewsKeys(videoId)
248 this.deleteFromSet(setKey, videoId.toString()),
249 this.deleteKey(videoKey)
253 /* ************ Video viewers stats ************ */
255 getLocalVideoViewer (options: {
261 if (options.key) return this.getObject(options.key)
263 const { viewerKey } = this.generateLocalVideoViewerKeys(options.ip, options.videoId)
265 return this.getObject(viewerKey)
268 setLocalVideoViewer (ip: string, videoId: number, object: any) {
269 const { setKey, viewerKey } = this.generateLocalVideoViewerKeys(ip, videoId)
272 this.addToSet(setKey, viewerKey),
273 this.setObject(viewerKey, object)
277 listLocalVideoViewerKeys () {
278 const { setKey } = this.generateLocalVideoViewerKeys()
280 return this.getSet(setKey)
283 deleteLocalVideoViewersKeys (key: string) {
284 const { setKey } = this.generateLocalVideoViewerKeys()
287 this.deleteFromSet(setKey, key),
292 /* ************ Resumable uploads final responses ************ */
294 setUploadSession (uploadId: string, response?: { video: { id: number, shortUUID: string, uuid: string } }) {
295 return this.setValue(
296 'resumable-upload-' + uploadId,
298 ? JSON.stringify(response)
300 RESUMABLE_UPLOAD_SESSION_LIFETIME
304 doesUploadSessionExist (uploadId: string) {
305 return this.exists('resumable-upload-' + uploadId)
308 async getUploadSession (uploadId: string) {
309 const value = await this.getValue('resumable-upload-' + uploadId)
316 deleteUploadSession (uploadId: string) {
317 return this.deleteKey('resumable-upload-' + uploadId)
320 /* ************ AP resource unavailability ************ */
322 async addAPUnavailability (url: string) {
323 const key = this.generateAPUnavailabilityKey(url)
325 const value = await this.increment(key)
326 await this.setExpiration(key, AP_CLEANER.PERIOD * 2)
331 /* ************ Keys generation ************ */
333 private generateLocalVideoViewsKeys (videoId: number): { setKey: string, videoKey: string }
334 private generateLocalVideoViewsKeys (): { setKey: string }
335 private generateLocalVideoViewsKeys (videoId?: number) {
336 return { setKey: `local-video-views-buffer`, videoKey: `local-video-views-buffer-${videoId}` }
339 private generateLocalVideoViewerKeys (ip: string, videoId: number): { setKey: string, viewerKey: string }
340 private generateLocalVideoViewerKeys (): { setKey: string }
341 private generateLocalVideoViewerKeys (ip?: string, videoId?: number) {
342 return { setKey: `local-video-viewer-stats-keys`, viewerKey: `local-video-viewer-stats-${ip}-${videoId}` }
345 private generateVideoViewStatsKeys (options: { videoId?: number, hour?: number }) {
346 const hour = exists(options.hour)
348 : new Date().getHours()
350 return { setKey: `videos-view-h${hour}`, videoKey: `video-view-${options.videoId}-h${hour}` }
353 private generateResetPasswordKey (userId: number) {
354 return 'reset-password-' + userId
357 private generateTwoFactorRequestKey (userId: number, token: string) {
358 return 'two-factor-request-' + userId + '-' + token
361 private generateUserVerifyEmailKey (userId: number) {
362 return 'verify-email-user-' + userId
365 private generateRegistrationVerifyEmailKey (registrationId: number) {
366 return 'verify-email-registration-' + registrationId
369 private generateIPViewKey (ip: string, videoUUID: string) {
370 return `views-${videoUUID}-${ip}`
373 private generateContactFormKey (ip: string) {
374 return 'contact-form-' + ip
377 private generateAPUnavailabilityKey (url: string) {
378 return 'ap-unavailability-' + sha256(url)
381 /* ************ Redis helpers ************ */
383 private getValue (key: string) {
384 return this.client.get(this.prefix + key)
387 private getSet (key: string) {
388 return this.client.smembers(this.prefix + key)
391 private addToSet (key: string, value: string) {
392 return this.client.sadd(this.prefix + key, value)
395 private deleteFromSet (key: string, value: string) {
396 return this.client.srem(this.prefix + key, value)
399 private deleteKey (key: string) {
400 return this.client.del(this.prefix + key)
403 private async getObject (key: string) {
404 const value = await this.getValue(key)
405 if (!value) return null
407 return JSON.parse(value)
410 private setObject (key: string, value: { [ id: string ]: number | string }, expirationMilliseconds?: number) {
411 return this.setValue(key, JSON.stringify(value), expirationMilliseconds)
414 private async setValue (key: string, value: string, expirationMilliseconds?: number) {
415 const result = expirationMilliseconds !== undefined
416 ? await this.client.set(this.prefix + key, value, 'PX', expirationMilliseconds)
417 : await this.client.set(this.prefix + key, value)
419 if (result !== 'OK') throw new Error('Redis set result is not OK.')
422 private removeValue (key: string) {
423 return this.client.del(this.prefix + key)
426 private increment (key: string) {
427 return this.client.incr(this.prefix + key)
430 private async exists (key: string) {
431 const result = await this.client.exists(this.prefix + key)
436 private setExpiration (key: string, ms: number) {
437 return this.client.expire(this.prefix + key, ms / 1000)
440 static get Instance () {
441 return this.instance || (this.instance = new this())
445 // ---------------------------------------------------------------------------