]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/redis.ts
Fix play on iOS (grumph)
[github/Chocobozzz/PeerTube.git] / server / lib / redis.ts
CommitLineData
4195cd2b 1import * as express from 'express'
ecb4e35f
C
2import { createClient, RedisClient } from 'redis'
3import { logger } from '../helpers/logger'
4import { generateRandomString } from '../helpers/utils'
fd4484f1 5import { CONFIG, USER_PASSWORD_RESET_LIFETIME, VIDEO_VIEW_LIFETIME } from '../initializers'
4195cd2b
C
6
7type CachedRoute = {
8 body: string,
9 contentType?: string
10 statusCode?: string
11}
ecb4e35f
C
12
13class Redis {
14
15 private static instance: Redis
16 private initialized = false
17 private client: RedisClient
18 private prefix: string
19
20 private constructor () {}
21
22 init () {
23 // Already initialized
24 if (this.initialized === true) return
25 this.initialized = true
26
27 this.client = createClient({
28 host: CONFIG.REDIS.HOSTNAME,
30c82f0d
RK
29 port: CONFIG.REDIS.PORT,
30 db: CONFIG.REDIS.DB
ecb4e35f
C
31 })
32
33 this.client.on('error', err => {
d5b7d911 34 logger.error('Error in Redis client.', { err })
ecb4e35f
C
35 process.exit(-1)
36 })
37
38 if (CONFIG.REDIS.AUTH) {
39 this.client.auth(CONFIG.REDIS.AUTH)
40 }
41
42 this.prefix = 'redis-' + CONFIG.WEBSERVER.HOST + '-'
43 }
44
45 async setResetPasswordVerificationString (userId: number) {
46 const generatedString = await generateRandomString(32)
47
48 await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_RESET_LIFETIME)
49
50 return generatedString
51 }
52
53 async getResetPasswordLink (userId: number) {
54 return this.getValue(this.generateResetPasswordKey(userId))
55 }
56
b5c0e955
C
57 setView (ip: string, videoUUID: string) {
58 return this.setValue(this.buildViewKey(ip, videoUUID), '1', VIDEO_VIEW_LIFETIME)
59 }
60
61 async isViewExists (ip: string, videoUUID: string) {
62 return this.exists(this.buildViewKey(ip, videoUUID))
63 }
64
4195cd2b
C
65 async getCachedRoute (req: express.Request) {
66 const cached = await this.getObject(this.buildCachedRouteKey(req))
67
68 return cached as CachedRoute
69 }
70
fd4484f1 71 setCachedRoute (req: express.Request, body: any, lifetime: number, contentType?: string, statusCode?: number) {
4195cd2b
C
72 const cached: CachedRoute = {
73 body: body.toString(),
74 contentType,
75 statusCode: statusCode.toString()
76 }
77
fd4484f1 78 return this.setObject(this.buildCachedRouteKey(req), cached, lifetime)
4195cd2b
C
79 }
80
2c29ad4f
C
81 listJobs (jobsPrefix: string, state: string, mode: 'alpha', order: 'ASC' | 'DESC', offset: number, count: number) {
82 return new Promise<string[]>((res, rej) => {
83 this.client.sort(jobsPrefix + ':jobs:' + state, 'by', mode, order, 'LIMIT', offset.toString(), count.toString(), (err, values) => {
84 if (err) return rej(err)
85
2c29ad4f
C
86 return res(values)
87 })
88 })
89 }
90
ecb4e35f
C
91 private getValue (key: string) {
92 return new Promise<string>((res, rej) => {
93 this.client.get(this.prefix + key, (err, value) => {
94 if (err) return rej(err)
95
96 return res(value)
97 })
98 })
99 }
100
101 private setValue (key: string, value: string, expirationMilliseconds: number) {
102 return new Promise<void>((res, rej) => {
103 this.client.set(this.prefix + key, value, 'PX', expirationMilliseconds, (err, ok) => {
104 if (err) return rej(err)
105
4195cd2b 106 if (ok !== 'OK') return rej(new Error('Redis set result is not OK.'))
ecb4e35f
C
107
108 return res()
109 })
110 })
111 }
112
4195cd2b
C
113 private setObject (key: string, obj: { [ id: string ]: string }, expirationMilliseconds: number) {
114 return new Promise<void>((res, rej) => {
115 this.client.hmset(this.prefix + key, obj, (err, ok) => {
116 if (err) return rej(err)
117 if (!ok) return rej(new Error('Redis mset result is not OK.'))
118
119 this.client.pexpire(this.prefix + key, expirationMilliseconds, (err, ok) => {
120 if (err) return rej(err)
121 if (!ok) return rej(new Error('Redis expiration result is not OK.'))
122
123 return res()
124 })
125 })
126 })
127 }
128
129 private getObject (key: string) {
130 return new Promise<{ [ id: string ]: string }>((res, rej) => {
131 this.client.hgetall(this.prefix + key, (err, value) => {
132 if (err) return rej(err)
133
134 return res(value)
135 })
136 })
137 }
138
b5c0e955
C
139 private exists (key: string) {
140 return new Promise<boolean>((res, rej) => {
141 this.client.exists(this.prefix + key, (err, existsNumber) => {
142 if (err) return rej(err)
143
144 return res(existsNumber === 1)
145 })
146 })
147 }
148
ecb4e35f
C
149 private generateResetPasswordKey (userId: number) {
150 return 'reset-password-' + userId
151 }
152
b5c0e955
C
153 private buildViewKey (ip: string, videoUUID: string) {
154 return videoUUID + '-' + ip
155 }
156
4195cd2b
C
157 private buildCachedRouteKey (req: express.Request) {
158 return req.method + '-' + req.originalUrl
159 }
160
ecb4e35f
C
161 static get Instance () {
162 return this.instance || (this.instance = new this())
163 }
164}
165
166// ---------------------------------------------------------------------------
167
168export {
169 Redis
170}