]>
Commit | Line | Data |
---|---|---|
a91e9beb | 1 | import { createClient, RedisClientOptions, RedisModules } from 'redis' |
e5d91a9b | 2 | import { exists } from '@server/helpers/custom-validators/misc' |
f1569117 | 3 | import { sha256 } from '@shared/extra-utils' |
ecb4e35f C |
4 | import { logger } from '../helpers/logger' |
5 | import { generateRandomString } from '../helpers/utils' | |
e5d91a9b | 6 | import { CONFIG } from '../initializers/config' |
a4101923 | 7 | import { |
f1569117 | 8 | AP_CLEANER, |
a4101923 | 9 | CONTACT_FORM_LIFETIME, |
e5d91a9b C |
10 | RESUMABLE_UPLOAD_SESSION_LIFETIME, |
11 | TRACKER_RATE_LIMITS, | |
a4101923 | 12 | USER_EMAIL_VERIFY_LIFETIME, |
45f1bd72 | 13 | USER_PASSWORD_CREATE_LIFETIME, |
e5d91a9b | 14 | USER_PASSWORD_RESET_LIFETIME, |
e4bf7856 | 15 | VIEW_LIFETIME, |
e5d91a9b | 16 | WEBSERVER |
74dc3bca | 17 | } from '../initializers/constants' |
4195cd2b | 18 | |
ecb4e35f C |
19 | class Redis { |
20 | ||
21 | private static instance: Redis | |
22 | private initialized = false | |
e5d91a9b | 23 | private connected = false |
a91e9beb | 24 | private client: ReturnType<typeof createClient> |
ecb4e35f C |
25 | private prefix: string |
26 | ||
a1587156 C |
27 | private constructor () { |
28 | } | |
ecb4e35f C |
29 | |
30 | init () { | |
31 | // Already initialized | |
32 | if (this.initialized === true) return | |
33 | this.initialized = true | |
34 | ||
47f6409b | 35 | this.client = createClient(Redis.getRedisClientOptions()) |
ecb4e35f | 36 | |
8f5a1f36 C |
37 | logger.info('Connecting to redis...') |
38 | ||
e5d91a9b | 39 | this.client.connect() |
8f5a1f36 C |
40 | .then(() => { |
41 | logger.info('Connected to redis.') | |
42 | ||
43 | this.connected = true | |
44 | }).catch(err => { | |
e5d91a9b C |
45 | logger.error('Cannot connect to redis', { err }) |
46 | process.exit(-1) | |
47 | }) | |
48 | ||
6dd9de95 | 49 | this.prefix = 'redis-' + WEBSERVER.HOST + '-' |
ecb4e35f C |
50 | } |
51 | ||
47f6409b | 52 | static getRedisClientOptions () { |
8f5a1f36 C |
53 | let config: RedisClientOptions<RedisModules, {}> = { |
54 | socket: { | |
55 | connectTimeout: 20000 // Could be slow since node use sync call to compile PeerTube | |
56 | } | |
57 | } | |
58 | ||
59 | if (CONFIG.REDIS.AUTH) { | |
60 | config = { ...config, password: CONFIG.REDIS.AUTH } | |
61 | } | |
62 | ||
63 | if (CONFIG.REDIS.DB) { | |
64 | config = { ...config, database: CONFIG.REDIS.DB } | |
65 | } | |
66 | ||
67 | if (CONFIG.REDIS.HOSTNAME && CONFIG.REDIS.PORT) { | |
68 | config.socket = { ...config.socket, host: CONFIG.REDIS.HOSTNAME, port: CONFIG.REDIS.PORT } | |
69 | } else { | |
70 | config.socket = { ...config.socket, path: CONFIG.REDIS.SOCKET } | |
71 | } | |
72 | ||
73 | return config | |
19f7b248 RK |
74 | } |
75 | ||
47f6409b C |
76 | getClient () { |
77 | return this.client | |
78 | } | |
79 | ||
80 | getPrefix () { | |
81 | return this.prefix | |
82 | } | |
83 | ||
e5d91a9b C |
84 | isConnected () { |
85 | return this.connected | |
86 | } | |
87 | ||
a1587156 | 88 | /* ************ Forgot password ************ */ |
6e46de09 | 89 | |
ecb4e35f C |
90 | async setResetPasswordVerificationString (userId: number) { |
91 | const generatedString = await generateRandomString(32) | |
92 | ||
93 | await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_RESET_LIFETIME) | |
94 | ||
45f1bd72 JL |
95 | return generatedString |
96 | } | |
97 | ||
98 | async setCreatePasswordVerificationString (userId: number) { | |
99 | const generatedString = await generateRandomString(32) | |
100 | ||
101 | await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_CREATE_LIFETIME) | |
102 | ||
ecb4e35f C |
103 | return generatedString |
104 | } | |
105 | ||
e9c5f123 C |
106 | async removePasswordVerificationString (userId: number) { |
107 | return this.removeValue(this.generateResetPasswordKey(userId)) | |
108 | } | |
109 | ||
ecb4e35f C |
110 | async getResetPasswordLink (userId: number) { |
111 | return this.getValue(this.generateResetPasswordKey(userId)) | |
112 | } | |
113 | ||
a1587156 | 114 | /* ************ Email verification ************ */ |
6e46de09 | 115 | |
d9eaee39 JM |
116 | async setVerifyEmailVerificationString (userId: number) { |
117 | const generatedString = await generateRandomString(32) | |
118 | ||
119 | await this.setValue(this.generateVerifyEmailKey(userId), generatedString, USER_EMAIL_VERIFY_LIFETIME) | |
120 | ||
121 | return generatedString | |
122 | } | |
123 | ||
124 | async getVerifyEmailLink (userId: number) { | |
125 | return this.getValue(this.generateVerifyEmailKey(userId)) | |
126 | } | |
127 | ||
a1587156 | 128 | /* ************ Contact form per IP ************ */ |
a4101923 C |
129 | |
130 | async setContactFormIp (ip: string) { | |
131 | return this.setValue(this.generateContactFormKey(ip), '1', CONTACT_FORM_LIFETIME) | |
132 | } | |
133 | ||
0f6acda1 | 134 | async doesContactFormIpExist (ip: string) { |
a4101923 C |
135 | return this.exists(this.generateContactFormKey(ip)) |
136 | } | |
137 | ||
a1587156 | 138 | /* ************ Views per IP ************ */ |
6e46de09 | 139 | |
51353d9a C |
140 | setIPVideoView (ip: string, videoUUID: string) { |
141 | return this.setValue(this.generateIPViewKey(ip, videoUUID), '1', VIEW_LIFETIME.VIEW) | |
142 | } | |
e4bf7856 | 143 | |
0f6acda1 | 144 | async doesVideoIPViewExist (ip: string, videoUUID: string) { |
51353d9a C |
145 | return this.exists(this.generateIPViewKey(ip, videoUUID)) |
146 | } | |
147 | ||
db48de85 C |
148 | /* ************ Tracker IP block ************ */ |
149 | ||
150 | setTrackerBlockIP (ip: string) { | |
151 | return this.setValue(this.generateTrackerBlockIPKey(ip), '1', TRACKER_RATE_LIMITS.BLOCK_IP_LIFETIME) | |
152 | } | |
153 | ||
154 | async doesTrackerBlockIPExist (ip: string) { | |
155 | return this.exists(this.generateTrackerBlockIPKey(ip)) | |
156 | } | |
157 | ||
51353d9a | 158 | /* ************ Video views stats ************ */ |
6e46de09 | 159 | |
51353d9a C |
160 | addVideoViewStats (videoId: number) { |
161 | const { videoKey, setKey } = this.generateVideoViewStatsKeys({ videoId }) | |
6b616860 C |
162 | |
163 | return Promise.all([ | |
51353d9a C |
164 | this.addToSet(setKey, videoId.toString()), |
165 | this.increment(videoKey) | |
6b616860 C |
166 | ]) |
167 | } | |
168 | ||
51353d9a C |
169 | async getVideoViewsStats (videoId: number, hour: number) { |
170 | const { videoKey } = this.generateVideoViewStatsKeys({ videoId, hour }) | |
6b616860 | 171 | |
51353d9a | 172 | const valueString = await this.getValue(videoKey) |
6040f87d C |
173 | const valueInt = parseInt(valueString, 10) |
174 | ||
175 | if (isNaN(valueInt)) { | |
51353d9a | 176 | logger.error('Cannot get videos views stats of video %d in hour %d: views number is NaN (%s).', videoId, hour, valueString) |
6040f87d C |
177 | return undefined |
178 | } | |
179 | ||
180 | return valueInt | |
6b616860 C |
181 | } |
182 | ||
51353d9a C |
183 | async listVideosViewedForStats (hour: number) { |
184 | const { setKey } = this.generateVideoViewStatsKeys({ hour }) | |
6b616860 | 185 | |
51353d9a | 186 | const stringIds = await this.getSet(setKey) |
6b616860 C |
187 | return stringIds.map(s => parseInt(s, 10)) |
188 | } | |
189 | ||
51353d9a C |
190 | deleteVideoViewsStats (videoId: number, hour: number) { |
191 | const { setKey, videoKey } = this.generateVideoViewStatsKeys({ videoId, hour }) | |
192 | ||
193 | return Promise.all([ | |
194 | this.deleteFromSet(setKey, videoId.toString()), | |
195 | this.deleteKey(videoKey) | |
196 | ]) | |
197 | } | |
198 | ||
199 | /* ************ Local video views buffer ************ */ | |
200 | ||
201 | addLocalVideoView (videoId: number) { | |
202 | const { videoKey, setKey } = this.generateLocalVideoViewsKeys(videoId) | |
6b616860 C |
203 | |
204 | return Promise.all([ | |
51353d9a C |
205 | this.addToSet(setKey, videoId.toString()), |
206 | this.increment(videoKey) | |
207 | ]) | |
208 | } | |
209 | ||
210 | async getLocalVideoViews (videoId: number) { | |
211 | const { videoKey } = this.generateLocalVideoViewsKeys(videoId) | |
212 | ||
213 | const valueString = await this.getValue(videoKey) | |
214 | const valueInt = parseInt(valueString, 10) | |
215 | ||
216 | if (isNaN(valueInt)) { | |
217 | logger.error('Cannot get videos views of video %d: views number is NaN (%s).', videoId, valueString) | |
218 | return undefined | |
219 | } | |
220 | ||
221 | return valueInt | |
222 | } | |
223 | ||
224 | async listLocalVideosViewed () { | |
225 | const { setKey } = this.generateLocalVideoViewsKeys() | |
226 | ||
227 | const stringIds = await this.getSet(setKey) | |
228 | return stringIds.map(s => parseInt(s, 10)) | |
229 | } | |
230 | ||
231 | deleteLocalVideoViews (videoId: number) { | |
232 | const { setKey, videoKey } = this.generateLocalVideoViewsKeys(videoId) | |
233 | ||
234 | return Promise.all([ | |
235 | this.deleteFromSet(setKey, videoId.toString()), | |
236 | this.deleteKey(videoKey) | |
6b616860 C |
237 | ]) |
238 | } | |
239 | ||
b2111066 C |
240 | /* ************ Video viewers stats ************ */ |
241 | ||
242 | getLocalVideoViewer (options: { | |
243 | key?: string | |
244 | // Or | |
245 | ip?: string | |
246 | videoId?: number | |
247 | }) { | |
248 | if (options.key) return this.getObject(options.key) | |
249 | ||
250 | const { viewerKey } = this.generateLocalVideoViewerKeys(options.ip, options.videoId) | |
251 | ||
252 | return this.getObject(viewerKey) | |
253 | } | |
254 | ||
255 | setLocalVideoViewer (ip: string, videoId: number, object: any) { | |
256 | const { setKey, viewerKey } = this.generateLocalVideoViewerKeys(ip, videoId) | |
257 | ||
258 | return Promise.all([ | |
259 | this.addToSet(setKey, viewerKey), | |
260 | this.setObject(viewerKey, object) | |
261 | ]) | |
262 | } | |
263 | ||
264 | listLocalVideoViewerKeys () { | |
265 | const { setKey } = this.generateLocalVideoViewerKeys() | |
266 | ||
267 | return this.getSet(setKey) | |
268 | } | |
269 | ||
270 | deleteLocalVideoViewersKeys (key: string) { | |
271 | const { setKey } = this.generateLocalVideoViewerKeys() | |
272 | ||
273 | return Promise.all([ | |
274 | this.deleteFromSet(setKey, key), | |
275 | this.deleteKey(key) | |
276 | ]) | |
277 | } | |
278 | ||
276250f0 RK |
279 | /* ************ Resumable uploads final responses ************ */ |
280 | ||
281 | setUploadSession (uploadId: string, response?: { video: { id: number, shortUUID: string, uuid: string } }) { | |
282 | return this.setValue( | |
283 | 'resumable-upload-' + uploadId, | |
284 | response | |
285 | ? JSON.stringify(response) | |
286 | : '', | |
287 | RESUMABLE_UPLOAD_SESSION_LIFETIME | |
288 | ) | |
289 | } | |
290 | ||
291 | doesUploadSessionExist (uploadId: string) { | |
292 | return this.exists('resumable-upload-' + uploadId) | |
293 | } | |
294 | ||
295 | async getUploadSession (uploadId: string) { | |
296 | const value = await this.getValue('resumable-upload-' + uploadId) | |
297 | ||
298 | return value | |
299 | ? JSON.parse(value) | |
300 | : '' | |
301 | } | |
302 | ||
020d3d3d C |
303 | deleteUploadSession (uploadId: string) { |
304 | return this.deleteKey('resumable-upload-' + uploadId) | |
305 | } | |
306 | ||
7a4fd56c | 307 | /* ************ AP resource unavailability ************ */ |
f1569117 C |
308 | |
309 | async addAPUnavailability (url: string) { | |
310 | const key = this.generateAPUnavailabilityKey(url) | |
311 | ||
312 | const value = await this.increment(key) | |
313 | await this.setExpiration(key, AP_CLEANER.PERIOD * 2) | |
314 | ||
315 | return value | |
316 | } | |
317 | ||
a1587156 | 318 | /* ************ Keys generation ************ */ |
6e46de09 | 319 | |
b2111066 C |
320 | private generateLocalVideoViewsKeys (videoId: number): { setKey: string, videoKey: string } |
321 | private generateLocalVideoViewsKeys (): { setKey: string } | |
322 | private generateLocalVideoViewsKeys (videoId?: number) { | |
51353d9a | 323 | return { setKey: `local-video-views-buffer`, videoKey: `local-video-views-buffer-${videoId}` } |
6b616860 C |
324 | } |
325 | ||
b2111066 C |
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}` } | |
330 | } | |
331 | ||
51353d9a C |
332 | private generateVideoViewStatsKeys (options: { videoId?: number, hour?: number }) { |
333 | const hour = exists(options.hour) | |
334 | ? options.hour | |
335 | : new Date().getHours() | |
6b616860 | 336 | |
51353d9a | 337 | return { setKey: `videos-view-h${hour}`, videoKey: `video-view-${options.videoId}-h${hour}` } |
6b616860 C |
338 | } |
339 | ||
6e46de09 | 340 | private generateResetPasswordKey (userId: number) { |
b40f0575 C |
341 | return 'reset-password-' + userId |
342 | } | |
343 | ||
6e46de09 | 344 | private generateVerifyEmailKey (userId: number) { |
d9eaee39 JM |
345 | return 'verify-email-' + userId |
346 | } | |
347 | ||
51353d9a | 348 | private generateIPViewKey (ip: string, videoUUID: string) { |
a4101923 C |
349 | return `views-${videoUUID}-${ip}` |
350 | } | |
351 | ||
db48de85 C |
352 | private generateTrackerBlockIPKey (ip: string) { |
353 | return `tracker-block-ip-${ip}` | |
354 | } | |
355 | ||
a4101923 C |
356 | private generateContactFormKey (ip: string) { |
357 | return 'contact-form-' + ip | |
b40f0575 C |
358 | } |
359 | ||
f1569117 C |
360 | private generateAPUnavailabilityKey (url: string) { |
361 | return 'ap-unavailability-' + sha256(url) | |
362 | } | |
363 | ||
a1587156 | 364 | /* ************ Redis helpers ************ */ |
b40f0575 | 365 | |
ecb4e35f | 366 | private getValue (key: string) { |
e5d91a9b | 367 | return this.client.get(this.prefix + key) |
ecb4e35f C |
368 | } |
369 | ||
6b616860 | 370 | private getSet (key: string) { |
e5d91a9b | 371 | return this.client.sMembers(this.prefix + key) |
6b616860 C |
372 | } |
373 | ||
374 | private addToSet (key: string, value: string) { | |
e5d91a9b | 375 | return this.client.sAdd(this.prefix + key, value) |
6b616860 C |
376 | } |
377 | ||
378 | private deleteFromSet (key: string, value: string) { | |
e5d91a9b | 379 | return this.client.sRem(this.prefix + key, value) |
6b616860 C |
380 | } |
381 | ||
382 | private deleteKey (key: string) { | |
e5d91a9b | 383 | return this.client.del(this.prefix + key) |
6e46de09 C |
384 | } |
385 | ||
b2111066 C |
386 | private async getObject (key: string) { |
387 | const value = await this.getValue(key) | |
388 | if (!value) return null | |
389 | ||
390 | return JSON.parse(value) | |
391 | } | |
392 | ||
393 | private setObject (key: string, value: { [ id: string ]: number | string }) { | |
394 | return this.setValue(key, JSON.stringify(value)) | |
395 | } | |
396 | ||
397 | private async setValue (key: string, value: string, expirationMilliseconds?: number) { | |
398 | const options = expirationMilliseconds | |
399 | ? { PX: expirationMilliseconds } | |
400 | : {} | |
401 | ||
402 | const result = await this.client.set(this.prefix + key, value, options) | |
ecb4e35f | 403 | |
e5d91a9b | 404 | if (result !== 'OK') throw new Error('Redis set result is not OK.') |
ecb4e35f C |
405 | } |
406 | ||
e9c5f123 | 407 | private removeValue (key: string) { |
e5d91a9b | 408 | return this.client.del(this.prefix + key) |
4195cd2b C |
409 | } |
410 | ||
6b616860 | 411 | private increment (key: string) { |
e5d91a9b | 412 | return this.client.incr(this.prefix + key) |
6b616860 C |
413 | } |
414 | ||
c0d2eac3 C |
415 | private async exists (key: string) { |
416 | const result = await this.client.exists(this.prefix + key) | |
417 | ||
418 | return result !== 0 | |
b5c0e955 C |
419 | } |
420 | ||
f1569117 C |
421 | private setExpiration (key: string, ms: number) { |
422 | return this.client.expire(this.prefix + key, ms / 1000) | |
423 | } | |
424 | ||
ecb4e35f C |
425 | static get Instance () { |
426 | return this.instance || (this.instance = new this()) | |
427 | } | |
428 | } | |
429 | ||
430 | // --------------------------------------------------------------------------- | |
431 | ||
432 | export { | |
433 | Redis | |
434 | } |