UNPKG

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