notifications.js 3.7 KB

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