1 | #!/usr/bin/env node
|
2 |
|
3 | var Notification = require('./').Notification;
|
4 | var minimist = require('minimist');
|
5 | var usage = require('cli-usage');
|
6 |
|
7 | var aliases = {
|
8 | 'help': 'h',
|
9 | 'title': 't',
|
10 | 'subtitle': 'st',
|
11 | 'message': 'm',
|
12 | 'icon': 'i',
|
13 | 'sound': 's',
|
14 | 'open': 'o',
|
15 | 'port': 'p',
|
16 | };
|
17 |
|
18 | var argv = minimist(process.argv.slice(2), {
|
19 | alias: aliases,
|
20 | string: ['icon', 'message', 'open', 'subtitle', 'title', 'host', 'port']
|
21 | });
|
22 |
|
23 | readme(aliases, ['host']);
|
24 |
|
25 | var validOpts = Object.keys(aliases).concat('host');
|
26 | var passedOptions = getOptionsIfExists(validOpts, argv);
|
27 | var stdinMessage = '';
|
28 |
|
29 | if (process.stdin.isTTY) {
|
30 | doNotification(passedOptions);
|
31 | } else {
|
32 | process.stdin.resume();
|
33 | process.stdin.setEncoding('utf8');
|
34 | process.stdin.on('data', function(data) {
|
35 | if (data) {
|
36 | stdinMessage += data;
|
37 | } else {
|
38 | doNotification(passedOptions);
|
39 | this.end();
|
40 | return;
|
41 | }
|
42 | });
|
43 | process.stdin.on('end', function(){
|
44 | if (stdinMessage) {
|
45 | passedOptions.message = stdinMessage;
|
46 | }
|
47 | doNotification(passedOptions);
|
48 | });
|
49 | }
|
50 |
|
51 | function doNotification (options) {
|
52 | var notifier = new Notification(options);
|
53 | if (!options.message) {
|
54 |
|
55 | process.exit(0);
|
56 | }
|
57 | notifier.notify(options, function (err, msg) {
|
58 | if (err) {
|
59 | console.error(err.message);
|
60 | process.exit(1);
|
61 | }
|
62 |
|
63 | if (!msg) return;
|
64 | console.log(msg);
|
65 | process.exit(0);
|
66 | });
|
67 | }
|
68 |
|
69 | function getOptionsIfExists(optionTypes, argv) {
|
70 | var options = {};
|
71 | optionTypes.forEach(function (key) {
|
72 | if (key && argv[key]) {
|
73 | options[key] = argv[key];
|
74 | }
|
75 | });
|
76 | return options;
|
77 | }
|
78 |
|
79 | function readme(input, extra) {
|
80 | var str = '# notify\n \n## Options\n' + params(input, extra) + '\n\n';
|
81 | str += '## Example\n```shell\n';
|
82 | str += '$ notify -t "Hello" -m "My Message" -s --open http://github.com\n';
|
83 | str += '$ notify -t "Agent Coulson" --icon https://raw.githubusercontent.com/mikaelbr/node-notifier/master/example/coulson.jpg \n';
|
84 | str += '$ notify -m "My Message" -s Glass\n';
|
85 | str += '$ echo "My Message" | notify -t "Hello"```\n\n';
|
86 | usage(str);
|
87 | }
|
88 |
|
89 | function params(input, extra) {
|
90 | var withAlias = Object.keys(input).reduce(function (acc, key) {
|
91 | return acc + ' * --' + key + ' (alias -' + input[key] + ')\n';
|
92 | }, '');
|
93 |
|
94 | if (!extra) return withAlias;
|
95 |
|
96 | return withAlias + extra.reduce(function (acc, key) {
|
97 | return acc + ' * --' + key + '\n';
|
98 | }, '')
|
99 | }
|