notifications.js 7.7 KB

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