notifications.js 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. 'use strict';
  2. const coreClass = require("../core");
  3. const crypto = require('crypto');
  4. const redis = require('redis');
  5. const config = require('config');
  6. const subscriptions = [];
  7. module.exports = class extends coreClass {
  8. initialize() {
  9. return new Promise((resolve, reject) => {
  10. const url = this.url = config.get("redis").url;
  11. const password = this.password = config.get("redis").password;
  12. this.pub = redis.createClient({ url, password });
  13. this.sub = redis.createClient({ url, password });
  14. this.sub.on('error', (err) => {
  15. errorCb('Cache connection error.', err, 'Notifications');
  16. reject(err);
  17. });
  18. this.sub.on("connect", () => {
  19. resolve();
  20. });
  21. this.sub.on('pmessage', (pattern, channel, expiredKey) => {
  22. this.logger.stationIssue(`PMESSAGE - Pattern: ${pattern}; Channel: ${channel}; ExpiredKey: ${expiredKey}`);
  23. subscriptions.forEach((sub) => {
  24. if (sub.name !== expiredKey) return;
  25. sub.cb();
  26. });
  27. });
  28. this.sub.psubscribe('__keyevent@0__:expired');
  29. });
  30. }
  31. /**
  32. * Schedules a notification to be dispatched in a specific amount of milliseconds,
  33. * notifications are unique by name, and the first one is always kept, as in
  34. * attempting to schedule a notification that already exists won't do anything
  35. *
  36. * @param {String} name - the name of the notification we want to schedule
  37. * @param {Integer} time - how long in milliseconds until the notification should be fired
  38. * @param {Function} cb - gets called when the notification has been scheduled
  39. */
  40. async schedule(name, time, cb, station) {
  41. try { await this._validateHook(); } catch { return; }
  42. if (!cb) cb = ()=>{};
  43. time = Math.round(time);
  44. this.logger.stationIssue(`SCHEDULE - Time: ${time}; Name: ${name}; Key: ${crypto.createHash('md5').update(`_notification:${name}_`).digest('hex')}; StationId: ${station._id}; StationName: ${station.name}`);
  45. this.pub.set(crypto.createHash('md5').update(`_notification:${name}_`).digest('hex'), '', 'PX', time, 'NX', cb);
  46. }
  47. /**
  48. * Subscribes a callback function to be called when a notification gets called
  49. *
  50. * @param {String} name - the name of the notification we want to subscribe to
  51. * @param {Function} cb - gets called when the subscribed notification gets called
  52. * @param {Boolean} unique - only subscribe if another subscription with the same name doesn't already exist
  53. * @return {Object} - the subscription object
  54. */
  55. async subscribe(name, cb, unique = false, station) {
  56. try { await this._validateHook(); } catch { return; }
  57. this.logger.stationIssue(`SUBSCRIBE - Name: ${name}; Key: ${crypto.createHash('md5').update(`_notification:${name}_`).digest('hex')}, StationId: ${station._id}; StationName: ${station.name}; Unique: ${unique}; SubscriptionExists: ${!!subscriptions.find((subscription) => subscription.originalName == name)};`);
  58. if (unique && !!subscriptions.find((subscription) => subscription.originalName == name)) return;
  59. let subscription = { originalName: name, name: crypto.createHash('md5').update(`_notification:${name}_`).digest('hex'), cb };
  60. subscriptions.push(subscription);
  61. return subscription;
  62. }
  63. /**
  64. * Remove a notification subscription
  65. *
  66. * @param {Object} subscription - the subscription object returned by {@link subscribe}
  67. */
  68. async remove(subscription) {
  69. try { await this._validateHook(); } catch { return; }
  70. let index = subscriptions.indexOf(subscription);
  71. if (index) subscriptions.splice(index, 1);
  72. }
  73. async unschedule(name) {
  74. try { await this._validateHook(); } catch { return; }
  75. this.logger.stationIssue(`UNSCHEDULE - Name: ${name}; Key: ${crypto.createHash('md5').update(`_notification:${name}_`).digest('hex')}`);
  76. this.pub.del(crypto.createHash('md5').update(`_notification:${name}_`).digest('hex'));
  77. }
  78. }