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