UNPKG

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