notificationcenter.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /**
  2. * A Node.js wrapper for terminal-notify (with fallback).
  3. */
  4. var utils = require('../lib/utils');
  5. var Growl = require('./growl');
  6. var path = require('path');
  7. var notifier = path.join(
  8. __dirname,
  9. '../vendor/mac.noindex/terminal-notifier.app/Contents/MacOS/terminal-notifier'
  10. );
  11. var EventEmitter = require('events').EventEmitter;
  12. var util = require('util');
  13. var errorMessageOsX =
  14. 'You need Mac OS X 10.8 or above to use NotificationCenter,' +
  15. ' or use Growl fallback with constructor option {withFallback: true}.';
  16. module.exports = NotificationCenter;
  17. function NotificationCenter(options) {
  18. options = utils.clone(options || {});
  19. if (!(this instanceof NotificationCenter)) {
  20. return new NotificationCenter(options);
  21. }
  22. this.options = options;
  23. EventEmitter.call(this);
  24. }
  25. util.inherits(NotificationCenter, EventEmitter);
  26. var activeId = null;
  27. function noop() {}
  28. NotificationCenter.prototype.notify = function(options, callback) {
  29. var fallbackNotifier;
  30. var id = identificator();
  31. options = utils.clone(options || {});
  32. activeId = id;
  33. if (typeof options === 'string') {
  34. options = { title: 'node-notifier', message: options };
  35. }
  36. callback = callback || noop;
  37. if (typeof callback !== 'function') {
  38. throw new TypeError(
  39. 'The second argument must be a function callback. You have passed ' +
  40. typeof fn
  41. );
  42. }
  43. var actionJackedCallback = utils.actionJackerDecorator(
  44. this,
  45. options,
  46. callback,
  47. function(data) {
  48. if (activeId !== id) return false;
  49. if (data === 'activate') {
  50. return 'click';
  51. }
  52. if (data === 'timeout') {
  53. return 'timeout';
  54. }
  55. if (data === 'replied') {
  56. return 'replied';
  57. }
  58. return false;
  59. }
  60. );
  61. options = utils.mapToMac(options);
  62. if (!options.message && !options.group && !options.list && !options.remove) {
  63. callback(new Error('Message, group, remove or list property is required.'));
  64. return this;
  65. }
  66. var argsList = utils.constructArgumentList(options);
  67. if (utils.isMountainLion()) {
  68. utils.fileCommandJson(
  69. this.options.customPath || notifier,
  70. argsList,
  71. actionJackedCallback
  72. );
  73. return this;
  74. }
  75. if (fallbackNotifier || !!this.options.withFallback) {
  76. fallbackNotifier = fallbackNotifier || new Growl(this.options);
  77. return fallbackNotifier.notify(options, callback);
  78. }
  79. callback(new Error(errorMessageOsX));
  80. return this;
  81. };
  82. function identificator() {
  83. return { _ref: 'val' };
  84. }