notifysend.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 = void 0;
  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. NotifySend.prototype.notify = function(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. var allowedArguments = ['urgency', 'expire-time', 'icon', 'category', 'hint'];
  60. function doNotification(options, callback) {
  61. var initial, argsList;
  62. options = utils.mapToNotifySend(options);
  63. options.title = options.title || 'Node Notification:';
  64. initial = [options.title, options.message];
  65. delete options.title;
  66. delete options.message;
  67. argsList = utils.constructArgumentList(options, {
  68. initial: initial,
  69. keyExtra: '-',
  70. allowedArguments: allowedArguments
  71. });
  72. utils.command(notifier, argsList, callback);
  73. }