growl.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /**
  2. * Wrapper for the growly module
  3. */
  4. var checkGrowl = require('../lib/checkGrowl');
  5. var utils = require('../lib/utils');
  6. var growly = require('growly');
  7. var EventEmitter = require('events').EventEmitter;
  8. var util = require('util');
  9. var errorMessageNotFound =
  10. "Couldn't connect to growl (might be used as a fallback). Make sure it is running";
  11. module.exports = Growl;
  12. var hasGrowl;
  13. function Growl(options) {
  14. options = utils.clone(options || {});
  15. if (!(this instanceof Growl)) {
  16. return new Growl(options);
  17. }
  18. growly.appname = options.name || 'Node';
  19. this.options = options;
  20. EventEmitter.call(this);
  21. }
  22. util.inherits(Growl, EventEmitter);
  23. function notifyRaw(options, callback) {
  24. growly.setHost(this.options.host, this.options.port);
  25. options = utils.clone(options || {});
  26. if (typeof options === 'string') {
  27. options = { title: 'node-notifier', message: options };
  28. }
  29. callback = utils.actionJackerDecorator(this, options, callback, function(
  30. data
  31. ) {
  32. if (data === 'click') {
  33. return 'click';
  34. }
  35. if (data === 'timedout') {
  36. return 'timeout';
  37. }
  38. return false;
  39. });
  40. options = utils.mapToGrowl(options);
  41. if (!options.message) {
  42. callback(new Error('Message is required.'));
  43. return this;
  44. }
  45. options.title = options.title || 'Node Notification:';
  46. if (hasGrowl || !!options.wait) {
  47. var localCallback = options.wait ? callback : noop;
  48. growly.notify(options.message, options, localCallback);
  49. if (!options.wait) callback();
  50. return this;
  51. }
  52. checkGrowl(growly, function(_, didHaveGrowl) {
  53. hasGrowl = didHaveGrowl;
  54. if (!didHaveGrowl) return callback(new Error(errorMessageNotFound));
  55. growly.notify(options.message, options);
  56. callback();
  57. });
  58. return this;
  59. }
  60. Object.defineProperty(Growl.prototype, 'notify', {
  61. get: function() {
  62. if (!this._notify) this._notify = notifyRaw.bind(this);
  63. return this._notify;
  64. }
  65. });
  66. function noop() {}