notifysend.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /**
  2. * Node.js wrapper for "notify-send".
  3. */
  4. var os = require('os');
  5. var which = require('which');
  6. var utils = require('../lib/utils');
  7. var EventEmitter = require('events').EventEmitter;
  8. var util = require('util');
  9. var notifier = 'notify-send';
  10. var hasNotifier;
  11. module.exports = NotifySend;
  12. function NotifySend(options) {
  13. options = utils.clone(options || {});
  14. if (!(this instanceof NotifySend)) {
  15. return new NotifySend(options);
  16. }
  17. this.options = options;
  18. EventEmitter.call(this);
  19. }
  20. util.inherits(NotifySend, EventEmitter);
  21. function noop() {}
  22. function notifyRaw(options, callback) {
  23. options = utils.clone(options || {});
  24. callback = callback || noop;
  25. if (typeof callback !== 'function') {
  26. throw new TypeError(
  27. 'The second argument must be a function callback. You have passed ' +
  28. typeof callback
  29. );
  30. }
  31. if (typeof options === 'string') {
  32. options = { title: 'node-notifier', message: options };
  33. }
  34. if (!options.message) {
  35. callback(new Error('Message is required.'));
  36. return this;
  37. }
  38. if (os.type() !== 'Linux' && !os.type().match(/BSD$/)) {
  39. callback(new Error('Only supported on Linux and *BSD systems'));
  40. return this;
  41. }
  42. if (hasNotifier === false) {
  43. callback(new Error('notify-send must be installed on the system.'));
  44. return this;
  45. }
  46. if (hasNotifier || !!this.options.suppressOsdCheck) {
  47. doNotification(options, callback);
  48. return this;
  49. }
  50. try {
  51. hasNotifier = !!which.sync(notifier);
  52. doNotification(options, callback);
  53. } catch (err) {
  54. hasNotifier = false;
  55. return callback(err);
  56. }
  57. return this;
  58. }
  59. Object.defineProperty(NotifySend.prototype, 'notify', {
  60. get: function() {
  61. if (!this._notify) this._notify = notifyRaw.bind(this);
  62. return this._notify;
  63. }
  64. });
  65. var allowedArguments = ['urgency', 'expire-time', 'icon', 'category', 'hint', 'app-name'];
  66. function doNotification(options, callback) {
  67. var initial, argsList;
  68. options = utils.mapToNotifySend(options);
  69. options.title = options.title || 'Node Notification:';
  70. initial = [options.title, options.message];
  71. delete options.title;
  72. delete options.message;
  73. argsList = utils.constructArgumentList(options, {
  74. initial: initial,
  75. keyExtra: '-',
  76. allowedArguments: allowedArguments
  77. });
  78. utils.command(notifier, argsList, callback);
  79. }