redis.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. import * as express from 'express'
  2. import { createClient, RedisClient } from 'redis'
  3. import { logger } from '../helpers/logger'
  4. import { generateRandomString } from '../helpers/utils'
  5. import {
  6. CONTACT_FORM_LIFETIME,
  7. USER_EMAIL_VERIFY_LIFETIME,
  8. USER_PASSWORD_RESET_LIFETIME,
  9. VIDEO_VIEW_LIFETIME,
  10. WEBSERVER
  11. } from '../initializers/constants'
  12. import { CONFIG } from '../initializers/config'
  13. type CachedRoute = {
  14. body: string,
  15. contentType?: string
  16. statusCode?: string
  17. }
  18. class Redis {
  19. private static instance: Redis
  20. private initialized = false
  21. private client: RedisClient
  22. private prefix: string
  23. private constructor () {}
  24. init () {
  25. // Already initialized
  26. if (this.initialized === true) return
  27. this.initialized = true
  28. this.client = createClient(Redis.getRedisClientOptions())
  29. this.client.on('error', err => {
  30. logger.error('Error in Redis client.', { err })
  31. process.exit(-1)
  32. })
  33. if (CONFIG.REDIS.AUTH) {
  34. this.client.auth(CONFIG.REDIS.AUTH)
  35. }
  36. this.prefix = 'redis-' + WEBSERVER.HOST + '-'
  37. }
  38. static getRedisClientOptions () {
  39. return Object.assign({},
  40. (CONFIG.REDIS.AUTH && CONFIG.REDIS.AUTH != null) ? { password: CONFIG.REDIS.AUTH } : {},
  41. (CONFIG.REDIS.DB) ? { db: CONFIG.REDIS.DB } : {},
  42. (CONFIG.REDIS.HOSTNAME && CONFIG.REDIS.PORT) ?
  43. { host: CONFIG.REDIS.HOSTNAME, port: CONFIG.REDIS.PORT } :
  44. { path: CONFIG.REDIS.SOCKET }
  45. )
  46. }
  47. getClient () {
  48. return this.client
  49. }
  50. getPrefix () {
  51. return this.prefix
  52. }
  53. /************* Forgot password *************/
  54. async setResetPasswordVerificationString (userId: number) {
  55. const generatedString = await generateRandomString(32)
  56. await this.setValue(this.generateResetPasswordKey(userId), generatedString, USER_PASSWORD_RESET_LIFETIME)
  57. return generatedString
  58. }
  59. async getResetPasswordLink (userId: number) {
  60. return this.getValue(this.generateResetPasswordKey(userId))
  61. }
  62. /************* Email verification *************/
  63. async setVerifyEmailVerificationString (userId: number) {
  64. const generatedString = await generateRandomString(32)
  65. await this.setValue(this.generateVerifyEmailKey(userId), generatedString, USER_EMAIL_VERIFY_LIFETIME)
  66. return generatedString
  67. }
  68. async getVerifyEmailLink (userId: number) {
  69. return this.getValue(this.generateVerifyEmailKey(userId))
  70. }
  71. /************* Contact form per IP *************/
  72. async setContactFormIp (ip: string) {
  73. return this.setValue(this.generateContactFormKey(ip), '1', CONTACT_FORM_LIFETIME)
  74. }
  75. async doesContactFormIpExist (ip: string) {
  76. return this.exists(this.generateContactFormKey(ip))
  77. }
  78. /************* Views per IP *************/
  79. setIPVideoView (ip: string, videoUUID: string) {
  80. return this.setValue(this.generateViewKey(ip, videoUUID), '1', VIDEO_VIEW_LIFETIME)
  81. }
  82. async doesVideoIPViewExist (ip: string, videoUUID: string) {
  83. return this.exists(this.generateViewKey(ip, videoUUID))
  84. }
  85. /************* API cache *************/
  86. async getCachedRoute (req: express.Request) {
  87. const cached = await this.getObject(this.generateCachedRouteKey(req))
  88. return cached as CachedRoute
  89. }
  90. setCachedRoute (req: express.Request, body: any, lifetime: number, contentType?: string, statusCode?: number) {
  91. const cached: CachedRoute = Object.assign({}, {
  92. body: body.toString()
  93. },
  94. (contentType) ? { contentType } : null,
  95. (statusCode) ? { statusCode: statusCode.toString() } : null
  96. )
  97. return this.setObject(this.generateCachedRouteKey(req), cached, lifetime)
  98. }
  99. /************* Video views *************/
  100. addVideoView (videoId: number) {
  101. const keyIncr = this.generateVideoViewKey(videoId)
  102. const keySet = this.generateVideosViewKey()
  103. return Promise.all([
  104. this.addToSet(keySet, videoId.toString()),
  105. this.increment(keyIncr)
  106. ])
  107. }
  108. async getVideoViews (videoId: number, hour: number) {
  109. const key = this.generateVideoViewKey(videoId, hour)
  110. const valueString = await this.getValue(key)
  111. const valueInt = parseInt(valueString, 10)
  112. if (isNaN(valueInt)) {
  113. logger.error('Cannot get videos views of video %d in hour %d: views number is NaN (%s).', videoId, hour, valueString)
  114. return undefined
  115. }
  116. return valueInt
  117. }
  118. async getVideosIdViewed (hour: number) {
  119. const key = this.generateVideosViewKey(hour)
  120. const stringIds = await this.getSet(key)
  121. return stringIds.map(s => parseInt(s, 10))
  122. }
  123. deleteVideoViews (videoId: number, hour: number) {
  124. const keySet = this.generateVideosViewKey(hour)
  125. const keyIncr = this.generateVideoViewKey(videoId, hour)
  126. return Promise.all([
  127. this.deleteFromSet(keySet, videoId.toString()),
  128. this.deleteKey(keyIncr)
  129. ])
  130. }
  131. /************* Keys generation *************/
  132. generateCachedRouteKey (req: express.Request) {
  133. return req.method + '-' + req.originalUrl
  134. }
  135. private generateVideosViewKey (hour?: number) {
  136. if (!hour) hour = new Date().getHours()
  137. return `videos-view-h${hour}`
  138. }
  139. private generateVideoViewKey (videoId: number, hour?: number) {
  140. if (!hour) hour = new Date().getHours()
  141. return `video-view-${videoId}-h${hour}`
  142. }
  143. private generateResetPasswordKey (userId: number) {
  144. return 'reset-password-' + userId
  145. }
  146. private generateVerifyEmailKey (userId: number) {
  147. return 'verify-email-' + userId
  148. }
  149. private generateViewKey (ip: string, videoUUID: string) {
  150. return `views-${videoUUID}-${ip}`
  151. }
  152. private generateContactFormKey (ip: string) {
  153. return 'contact-form-' + ip
  154. }
  155. /************* Redis helpers *************/
  156. private getValue (key: string) {
  157. return new Promise<string>((res, rej) => {
  158. this.client.get(this.prefix + key, (err, value) => {
  159. if (err) return rej(err)
  160. return res(value)
  161. })
  162. })
  163. }
  164. private getSet (key: string) {
  165. return new Promise<string[]>((res, rej) => {
  166. this.client.smembers(this.prefix + key, (err, value) => {
  167. if (err) return rej(err)
  168. return res(value)
  169. })
  170. })
  171. }
  172. private addToSet (key: string, value: string) {
  173. return new Promise<string[]>((res, rej) => {
  174. this.client.sadd(this.prefix + key, value, err => err ? rej(err) : res())
  175. })
  176. }
  177. private deleteFromSet (key: string, value: string) {
  178. return new Promise<void>((res, rej) => {
  179. this.client.srem(this.prefix + key, value, err => err ? rej(err) : res())
  180. })
  181. }
  182. private deleteKey (key: string) {
  183. return new Promise<void>((res, rej) => {
  184. this.client.del(this.prefix + key, err => err ? rej(err) : res())
  185. })
  186. }
  187. private deleteFieldInHash (key: string, field: string) {
  188. return new Promise<void>((res, rej) => {
  189. this.client.hdel(this.prefix + key, field, err => err ? rej(err) : res())
  190. })
  191. }
  192. private setValue (key: string, value: string, expirationMilliseconds: number) {
  193. return new Promise<void>((res, rej) => {
  194. this.client.set(this.prefix + key, value, 'PX', expirationMilliseconds, (err, ok) => {
  195. if (err) return rej(err)
  196. if (ok !== 'OK') return rej(new Error('Redis set result is not OK.'))
  197. return res()
  198. })
  199. })
  200. }
  201. private setObject (key: string, obj: { [ id: string ]: string }, expirationMilliseconds: number) {
  202. return new Promise<void>((res, rej) => {
  203. this.client.hmset(this.prefix + key, obj, (err, ok) => {
  204. if (err) return rej(err)
  205. if (!ok) return rej(new Error('Redis mset result is not OK.'))
  206. this.client.pexpire(this.prefix + key, expirationMilliseconds, (err, ok) => {
  207. if (err) return rej(err)
  208. if (!ok) return rej(new Error('Redis expiration result is not OK.'))
  209. return res()
  210. })
  211. })
  212. })
  213. }
  214. private getObject (key: string) {
  215. return new Promise<{ [ id: string ]: string }>((res, rej) => {
  216. this.client.hgetall(this.prefix + key, (err, value) => {
  217. if (err) return rej(err)
  218. return res(value)
  219. })
  220. })
  221. }
  222. private setValueInHash (key: string, field: string, value: string) {
  223. return new Promise<void>((res, rej) => {
  224. this.client.hset(this.prefix + key, field, value, (err) => {
  225. if (err) return rej(err)
  226. return res()
  227. })
  228. })
  229. }
  230. private increment (key: string) {
  231. return new Promise<number>((res, rej) => {
  232. this.client.incr(this.prefix + key, (err, value) => {
  233. if (err) return rej(err)
  234. return res(value)
  235. })
  236. })
  237. }
  238. private exists (key: string) {
  239. return new Promise<boolean>((res, rej) => {
  240. this.client.exists(this.prefix + key, (err, existsNumber) => {
  241. if (err) return rej(err)
  242. return res(existsNumber === 1)
  243. })
  244. })
  245. }
  246. static get Instance () {
  247. return this.instance || (this.instance = new this())
  248. }
  249. }
  250. // ---------------------------------------------------------------------------
  251. export {
  252. Redis
  253. }