notifysend.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /**
  2. * Node.js wrapper for "notify-send".
  3. */
  4. var os = require('os'),
  5. which = require('which'),
  6. utils = require('../lib/utils'),
  7. cloneDeep = require('lodash.clonedeep');
  8. var EventEmitter = require('events').EventEmitter;
  9. var util = require('util');
  10. var notifier = 'notify-send', hasNotifier = void 0;
  11. module.exports = NotifySend;
  12. function NotifySend (options) {
  13. options = cloneDeep(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. NotifySend.prototype.notify = function (options, callback) {
  22. options = cloneDeep(options || {});
  23. callback = callback || function () {};
  24. if (typeof options === 'string') options = {
  25. title: 'node-notifier',
  26. message: options
  27. };
  28. if (!options.message) {
  29. callback(new Error('Message is required.'));
  30. return this;
  31. }
  32. if (os.type() !== 'Linux') {
  33. callback(new Error('Only supported on Linux systems'));
  34. return this;
  35. }
  36. if (hasNotifier === false) {
  37. callback(new Error('notify-send must be installed on the system.'));
  38. return this;
  39. }
  40. if (hasNotifier || !!this.options.suppressOsdCheck) {
  41. doNotification(options, callback);
  42. return this;
  43. }
  44. try {
  45. hasNotifier = !!which.sync(notifier);
  46. doNotification(options, callback);
  47. } catch (err) {
  48. hasNotifier = false;
  49. return callback(err);
  50. };
  51. return this;
  52. };
  53. var allowedArguments = [
  54. "urgency",
  55. "expire-time",
  56. "icon",
  57. "category",
  58. "hint"
  59. ];
  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. }