1 import { createClient } 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())
41 .then(() => { this.connected = true })
43 logger.error('Cannot connect to redis', { err })
47 this.client.on('error', err => {
48 logger.error('Error in Redis client.', { err })
52 this.prefix = 'redis-' + WEBSERVER.HOST + '-'
55 static getRedisClientOptions () {
56 return Object.assign({},
57 CONFIG.REDIS.AUTH ? { password: CONFIG.REDIS.AUTH } : {},
58 (CONFIG.REDIS.DB) ? { db: CONFIG.REDIS.DB } : {},
59 (CONFIG.REDIS.HOSTNAME && CONFIG.REDIS.PORT)
60 ? { host: CONFIG.REDIS.HOSTNAME, port: CONFIG.REDIS.PORT }
61 : { path: CONFIG.REDIS.SOCKET }
77 /* ************ Forgot password ************ */
79 async setResetPasswordVerificationString (userId: number) {
80 const generatedString = await generateRandomString(32)
82 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_RESET_LIFETIME)
84 return generatedString
87 async setCreatePasswordVerificationString (userId: number) {
88 const generatedString = await generateRandomString(32)
90 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_CREATE_LIFETIME)
92 return generatedString
95 async removePasswordVerificationString (userId: number) {
96 return this.removeValue(this.generateResetPasswordKey(userId))
99 async getResetPasswordLink (userId: number) {
100 return this.getValue(this.generateResetPasswordKey(userId))
103 /* ************ Email verification ************ */
105 async setVerifyEmailVerificationString (userId: number) {
106 const generatedString = await generateRandomString(32)
108 await this.setValue(this.generateVerifyEmailKey(userId), generatedString, USER_EMAIL_VERIFY_LIFETIME)
110 return generatedString
113 async getVerifyEmailLink (userId: number) {
114 return this.getValue(this.generateVerifyEmailKey(userId))
117 /* ************ Contact form per IP ************ */
119 async setContactFormIp (ip: string) {
120 return this.setValue(this.generateContactFormKey(ip), '1', CONTACT_FORM_LIFETIME)
123 async doesContactFormIpExist (ip: string) {
124 return this.exists(this.generateContactFormKey(ip))
127 /* ************ Views per IP ************ */
129 setIPVideoView (ip: string, videoUUID: string) {
130 return this.setValue(this.generateIPViewKey(ip, videoUUID), '1', VIEW_LIFETIME.VIEW)
133 setIPVideoViewer (ip: string, videoUUID: string) {
134 return this.setValue(this.generateIPViewerKey(ip, videoUUID), '1', VIEW_LIFETIME.VIEWER)
137 async doesVideoIPViewExist (ip: string, videoUUID: string) {
138 return this.exists(this.generateIPViewKey(ip, videoUUID))
141 async doesVideoIPViewerExist (ip: string, videoUUID: string) {
142 return this.exists(this.generateIPViewerKey(ip, videoUUID))
145 /* ************ Tracker IP block ************ */
147 setTrackerBlockIP (ip: string) {
148 return this.setValue(this.generateTrackerBlockIPKey(ip), '1', TRACKER_RATE_LIMITS.BLOCK_IP_LIFETIME)
151 async doesTrackerBlockIPExist (ip: string) {
152 return this.exists(this.generateTrackerBlockIPKey(ip))
155 /* ************ Video views stats ************ */
157 addVideoViewStats (videoId: number) {
158 const { videoKey, setKey } = this.generateVideoViewStatsKeys({ videoId })
161 this.addToSet(setKey, videoId.toString()),
162 this.increment(videoKey)
166 async getVideoViewsStats (videoId: number, hour: number) {
167 const { videoKey } = this.generateVideoViewStatsKeys({ videoId, hour })
169 const valueString = await this.getValue(videoKey)
170 const valueInt = parseInt(valueString, 10)
172 if (isNaN(valueInt)) {
173 logger.error('Cannot get videos views stats of video %d in hour %d: views number is NaN (%s).', videoId, hour, valueString)
180 async listVideosViewedForStats (hour: number) {
181 const { setKey } = this.generateVideoViewStatsKeys({ hour })
183 const stringIds = await this.getSet(setKey)
184 return stringIds.map(s => parseInt(s, 10))
187 deleteVideoViewsStats (videoId: number, hour: number) {
188 const { setKey, videoKey } = this.generateVideoViewStatsKeys({ videoId, hour })
191 this.deleteFromSet(setKey, videoId.toString()),
192 this.deleteKey(videoKey)
196 /* ************ Local video views buffer ************ */
198 addLocalVideoView (videoId: number) {
199 const { videoKey, setKey } = this.generateLocalVideoViewsKeys(videoId)
202 this.addToSet(setKey, videoId.toString()),
203 this.increment(videoKey)
207 async getLocalVideoViews (videoId: number) {
208 const { videoKey } = this.generateLocalVideoViewsKeys(videoId)
210 const valueString = await this.getValue(videoKey)
211 const valueInt = parseInt(valueString, 10)
213 if (isNaN(valueInt)) {
214 logger.error('Cannot get videos views of video %d: views number is NaN (%s).', videoId, valueString)
221 async listLocalVideosViewed () {
222 const { setKey } = this.generateLocalVideoViewsKeys()
224 const stringIds = await this.getSet(setKey)
225 return stringIds.map(s => parseInt(s, 10))
228 deleteLocalVideoViews (videoId: number) {
229 const { setKey, videoKey } = this.generateLocalVideoViewsKeys(videoId)
232 this.deleteFromSet(setKey, videoId.toString()),
233 this.deleteKey(videoKey)
237 /* ************ Resumable uploads final responses ************ */
239 setUploadSession (uploadId: string, response?: { video: { id: number, shortUUID: string, uuid: string } }) {
240 return this.setValue(
241 'resumable-upload-' + uploadId,
243 ? JSON.stringify(response)
245 RESUMABLE_UPLOAD_SESSION_LIFETIME
249 doesUploadSessionExist (uploadId: string) {
250 return this.exists('resumable-upload-' + uploadId)
253 async getUploadSession (uploadId: string) {
254 const value = await this.getValue('resumable-upload-' + uploadId)
261 deleteUploadSession (uploadId: string) {
262 return this.deleteKey('resumable-upload-' + uploadId)
265 /* ************ AP ressource unavailability ************ */
267 async addAPUnavailability (url: string) {
268 const key = this.generateAPUnavailabilityKey(url)
270 const value = await this.increment(key)
271 await this.setExpiration(key, AP_CLEANER.PERIOD * 2)
276 /* ************ Keys generation ************ */
278 private generateLocalVideoViewsKeys (videoId?: Number) {
279 return { setKey: `local-video-views-buffer`, videoKey: `local-video-views-buffer-${videoId}` }
282 private generateVideoViewStatsKeys (options: { videoId?: number, hour?: number }) {
283 const hour = exists(options.hour)
285 : new Date().getHours()
287 return { setKey: `videos-view-h${hour}`, videoKey: `video-view-${options.videoId}-h${hour}` }
290 private generateResetPasswordKey (userId: number) {
291 return 'reset-password-' + userId
294 private generateVerifyEmailKey (userId: number) {
295 return 'verify-email-' + userId
298 private generateIPViewKey (ip: string, videoUUID: string) {
299 return `views-${videoUUID}-${ip}`
302 private generateIPViewerKey (ip: string, videoUUID: string) {
303 return `viewer-${videoUUID}-${ip}`
306 private generateTrackerBlockIPKey (ip: string) {
307 return `tracker-block-ip-${ip}`
310 private generateContactFormKey (ip: string) {
311 return 'contact-form-' + ip
314 private generateAPUnavailabilityKey (url: string) {
315 return 'ap-unavailability-' + sha256(url)
318 /* ************ Redis helpers ************ */
320 private getValue (key: string) {
321 return this.client.get(this.prefix + key)
324 private getSet (key: string) {
325 return this.client.sMembers(this.prefix + key)
328 private addToSet (key: string, value: string) {
329 return this.client.sAdd(this.prefix + key, value)
332 private deleteFromSet (key: string, value: string) {
333 return this.client.sRem(this.prefix + key, value)
336 private deleteKey (key: string) {
337 return this.client.del(this.prefix + key)
340 private async setValue (key: string, value: string, expirationMilliseconds: number) {
341 const result = await this.client.set(this.prefix + key, value, { PX: expirationMilliseconds })
343 if (result !== 'OK') throw new Error('Redis set result is not OK.')
346 private removeValue (key: string) {
347 return this.client.del(this.prefix + key)
350 private increment (key: string) {
351 return this.client.incr(this.prefix + key)
354 private exists (key: string) {
355 return this.client.exists(this.prefix + key)
358 private setExpiration (key: string, ms: number) {
359 return this.client.expire(this.prefix + key, ms / 1000)
362 static get Instance () {
363 return this.instance || (this.instance = new this())
367 // ---------------------------------------------------------------------------