notifications.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. import config from "config";
  2. import crypto from "crypto";
  3. import redis from "redis";
  4. import CoreClass from "../core";
  5. let NotificationsModule;
  6. class _NotificationsModule extends CoreClass {
  7. // eslint-disable-next-line require-jsdoc
  8. constructor() {
  9. super("notifications");
  10. this.subscriptions = [];
  11. NotificationsModule = this;
  12. }
  13. /**
  14. * Initialises the notifications module
  15. * @returns {Promise} - returns promise (reject, resolve)
  16. */
  17. initialize() {
  18. return new Promise((resolve, reject) => {
  19. this.pub = redis.createClient({
  20. ...config.get("redis"),
  21. reconnectStrategy: retries => {
  22. if (this.getStatus() !== "LOCKDOWN") {
  23. if (this.getStatus() !== "RECONNECTING") this.setStatus("RECONNECTING");
  24. this.log("INFO", `Attempting to reconnect.`);
  25. if (retries >= 10) {
  26. this.log("ERROR", `Stopped trying to reconnect.`);
  27. this.setStatus("FAILED");
  28. new Error("Stopped trying to reconnect.");
  29. } else {
  30. Math.min(retries * 50, 500);
  31. }
  32. }
  33. }
  34. });
  35. this.pub.on("error", err => {
  36. if (this.getStatus() === "INITIALIZING") reject(err);
  37. if (this.getStatus() === "LOCKDOWN") return;
  38. this.log("ERROR", `Error ${err.message}.`);
  39. });
  40. this.pub.on("ready", () => {
  41. this.log("INFO", "Pub is ready.");
  42. if (this.getStatus() === "INITIALIZING") resolve();
  43. else if (this.getStatus() === "LOCKDOWN" || this.getStatus() === "RECONNECTING")
  44. this.setStatus("INITIALIZED");
  45. });
  46. this.pub.connect().then(async () => {
  47. this.log("INFO", "Pub connected succesfully.");
  48. this.pub
  49. .sendCommand(["CONFIG", "GET", "notify-keyspace-events"])
  50. .then(response => {
  51. if (response[1] === "xE") {
  52. this.log("INFO", "NOTIFICATIONS_INITIALIZE", `notify-keyspace-events is set correctly`);
  53. this.log("STATION_ISSUE", `notify-keyspace-events is set correctly`);
  54. } else {
  55. this.log(
  56. "ERROR",
  57. "NOTIFICATIONS_INITIALIZE",
  58. `notify-keyspace-events is NOT correctly! It is set to: ${response[1]}`
  59. );
  60. this.log(
  61. "STATION_ISSUE",
  62. `notify-keyspace-events is NOT correctly! It is set to: ${response[1]}`
  63. );
  64. }
  65. })
  66. .catch(err => {
  67. this.log(
  68. "ERROR",
  69. "NOTIFICATIONS_INITIALIZE",
  70. `Getting notify-keyspace-events gave an error. ${err}`
  71. );
  72. this.log("STATION_ISSUE", `Getting notify-keyspace-events gave an error. ${err}.`);
  73. });
  74. });
  75. this.sub = this.pub.duplicate();
  76. this.sub.on("error", err => {
  77. if (this.getStatus() === "INITIALIZING") reject(err);
  78. if (this.getStatus() === "LOCKDOWN") return;
  79. this.log("ERROR", `Error ${err.message}.`);
  80. });
  81. this.sub.connect().then(async () => {
  82. this.log("INFO", "Sub connected succesfully.");
  83. if (this.getStatus() === "INITIALIZING") resolve();
  84. else if (this.getStatus() === "LOCKDOWN" || this.getStatus() === "RECONNECTING")
  85. this.setStatus("READY");
  86. this.sub.PSUBSCRIBE(`__keyevent@${this.sub.options.database}__:expired`, (message, channel) => {
  87. this.log("STATION_ISSUE", `PMESSAGE1 - Channel: ${channel}; ExpiredKey: ${message}`);
  88. this.subscriptions.forEach(sub => {
  89. this.log(
  90. "STATION_ISSUE",
  91. `PMESSAGE2 - Sub name: ${sub.name}; Calls cb: ${!(sub.name !== message)}`
  92. );
  93. if (sub.name !== message) return;
  94. sub.cb();
  95. });
  96. });
  97. });
  98. });
  99. }
  100. /**
  101. * Schedules a notification to be dispatched in a specific amount of milliseconds,
  102. * notifications are unique by name, and the first one is always kept, as in
  103. * attempting to schedule a notification that already exists won't do anything
  104. * @param {object} payload - object containing the payload
  105. * @param {string} payload.name - the name of the notification we want to schedule
  106. * @param {number} payload.time - how long in milliseconds until the notification should be fired
  107. * @param {object} payload.station - the station object related to the notification
  108. * @returns {Promise} - returns a promise (resolve, reject)
  109. */
  110. SCHEDULE(payload) {
  111. return new Promise((resolve, reject) => {
  112. const time = Math.round(payload.time);
  113. if (time <= 0) reject(new Error("Time has to be higher than 0"));
  114. else {
  115. NotificationsModule.log(
  116. "STATION_ISSUE",
  117. `SCHEDULE - Time: ${time}; Name: ${payload.name}; Key: ${crypto
  118. .createHash("md5")
  119. .update(`_notification:${payload.name}_`)
  120. .digest("hex")}; StationId: ${payload.station._id}; StationName: ${payload.station.name}`
  121. );
  122. NotificationsModule.pub
  123. .SET(crypto.createHash("md5").update(`_notification:${payload.name}_`).digest("hex"), "", {
  124. PX: time,
  125. NX: true
  126. })
  127. .then(() => resolve())
  128. .catch(err => reject(new Error(err)));
  129. }
  130. });
  131. }
  132. /**
  133. * Subscribes a callback function to be called when a notification gets called
  134. * @param {object} payload - object containing the payload
  135. * @param {string} payload.name - the name of the notification we want to subscribe to
  136. * @param {boolean} payload.unique - only subscribe if another subscription with the same name doesn't already exist
  137. * @param {object} payload.station - the station object related to the notification
  138. * @returns {Promise} - returns a promise (resolve, reject)
  139. */
  140. SUBSCRIBE(payload) {
  141. return new Promise(resolve => {
  142. NotificationsModule.log(
  143. "STATION_ISSUE",
  144. `SUBSCRIBE - Name: ${payload.name}; Key: ${crypto
  145. .createHash("md5")
  146. .update(`_notification:${payload.name}_`)
  147. .digest("hex")}, StationId: ${payload.station._id}; StationName: ${payload.station.name}; Unique: ${
  148. payload.unique
  149. }; SubscriptionExists: ${!!NotificationsModule.subscriptions.find(
  150. subscription => subscription.originalName === payload.name
  151. )};`
  152. );
  153. if (
  154. payload.unique &&
  155. !!NotificationsModule.subscriptions.find(subscription => subscription.originalName === payload.name)
  156. ) {
  157. resolve({
  158. subscription: NotificationsModule.subscriptions.find(
  159. subscription => subscription.originalName === payload.name
  160. )
  161. });
  162. return;
  163. }
  164. const subscription = {
  165. originalName: payload.name,
  166. name: crypto.createHash("md5").update(`_notification:${payload.name}_`).digest("hex"),
  167. cb: payload.cb
  168. };
  169. NotificationsModule.subscriptions.push(subscription);
  170. resolve({ subscription });
  171. });
  172. }
  173. /**
  174. * Remove a notification subscription
  175. * @param {object} payload - object containing the payload
  176. * @param {object} payload.subscription - the subscription object returned by subscribe
  177. * @returns {Promise} - returns a promise (resolve, reject)
  178. */
  179. REMOVE(payload) {
  180. // subscription
  181. return new Promise(resolve => {
  182. const index = NotificationsModule.subscriptions.indexOf(payload.subscription);
  183. if (index) NotificationsModule.subscriptions.splice(index, 1);
  184. resolve();
  185. });
  186. }
  187. /**
  188. * Unschedules a notification by name (each notification has a unique name)
  189. * @param {object} payload - object containing the payload
  190. * @param {string} payload.name - the name of the notification we want to schedule
  191. * @returns {Promise} - returns a promise (resolve, reject)
  192. */
  193. UNSCHEDULE(payload) {
  194. // name
  195. return new Promise((resolve, reject) => {
  196. NotificationsModule.log(
  197. "STATION_ISSUE",
  198. `UNSCHEDULE - Name: ${payload.name}; Key: ${crypto
  199. .createHash("md5")
  200. .update(`_notification:${payload.name}_`)
  201. .digest("hex")}`
  202. );
  203. NotificationsModule.pub
  204. .DEL(crypto.createHash("md5").update(`_notification:${payload.name}_`).digest("hex"))
  205. .then(() => resolve())
  206. .catch(err => reject(new Error(err)));
  207. });
  208. }
  209. }
  210. export default new _NotificationsModule();