├── HISTORY.md ├── README.md ├── example ├── bakery.js ├── cake.png ├── muffin.png └── simple.js ├── lib ├── gntp.js └── growly.js └── package.json /HISTORY.md: -------------------------------------------------------------------------------- 1 | 1.1.0 / 2012-12-12 2 | ================== 3 | 4 | - Default registration work lazily, and is performed on the first call to `Growly.notify()`. 5 | - Added callback to `Growly.register()`. 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Growly # 2 | 3 | Simple zero-dependency Growl notifications using GNTP. 4 | 5 | ## Installation ## 6 | 7 | Install growly using `npm`: 8 | 9 | ``` 10 | npm install growly 11 | ``` 12 | 13 | And then require it: 14 | 15 | ```javascript 16 | var growly = require('growly'); 17 | ``` 18 | 19 | This module uses the Growl Network Transport Protocol (GNTP) which was implemented in Growl since version 1.3, so you **must have an appropriate version of Growl installed** for Growly to work. 20 | 21 | ## Example ## 22 | 23 | Sending a minimal Growl notification: 24 | 25 | ```javascript 26 | var growly = require('growly'); 27 | 28 | growly.notify('This is as easy as it gets', { title: 'Hello, World!' }); 29 | ``` 30 | 31 | More examples can be found in the *example/* directory. 32 | 33 | ## Usage ## 34 | 35 | The growly module exposes only three methods: `Growly.register()`, `Growly.notify()`, and `Growly.setHost()`. 36 | 37 | ### Growly.register(appname, [appicon], [notifications], [callback]) ### 38 | 39 | Registers a new application with Growl. Registration is completely optional since it will be performed automatically for you with sensible defaults. Useful if you want your application, with its own icon and types of notifications, to show up in Growl's prefence panel. 40 | 41 | - `appname` the name of the application (required.) 42 | - `appicon` url, file path, or Buffer instance for an application icon image. 43 | - `notifications` a list of defined notification types with the following properties: 44 | - `.label` name used to identify the type of notification being used (required.) 45 | - `.dispname` name users will see in Growl's preference panel (defaults to `.label`.) 46 | - `.enabled` whether or not notifications of this type are enabled (defaults to true.) 47 | - `callback` called when the registration completes; if registration fails, the first argument will be an Error object. 48 | 49 | An example: 50 | 51 | ```javascript 52 | growly.register('My Application', 'path/to/icon.png', [ 53 | { label: 'success', dispname: 'Success' }, 54 | { label: 'warning', dispname: 'Warning', enabled: false } 55 | ], function(err) { 56 | console.log(err || 'Registration successful!'); 57 | }); 58 | ``` 59 | 60 | ### Growly.notify(text, [opts], [callback]) ### 61 | 62 | Sends a Growl notification. If an application wasn't registered beforehand with `growly.register()`, a default application will automatically be registered beforesending the notification. 63 | 64 | - `text` the body of the notification. 65 | - `opts` an object with the following properties: 66 | - `.title` title of the notification. 67 | - `.icon` url, file path, or Buffer instance for the notification's icon. 68 | - `.sticky` whether or not to sticky the notification (defaults to false.) 69 | - `.label` type of notification to use (defaults to the first registered notification type.) 70 | - `.priority` the priority of the notification from lowest (-2) to highest (2). 71 | - `.coalescingId` replace/update the matching previous notification. May be ignored. 72 | - `callback` called when the user has closed/clicked the notification. The callback is passed an Error object `err` as the first argument when the notification fails; otherwise, the second argument `action` is a string that'll describe which action has been taken by the user (either 'closed' or 'clicked'.) 73 | 74 | An example: 75 | 76 | ```javascript 77 | /* Assuming an application was registered with a notification type labeled 'warning'. */ 78 | growly.notify('Stuffs broken!', { label: 'warning' }, function(err, action) { 79 | console.log('Action:', action); 80 | }); 81 | ``` 82 | 83 | ### Growly.setHost(host, port) ### 84 | 85 | Set the host and port that Growl (GNTP) requests will be sent to. Using this method is optional since GNTP defaults to using host 'localhost' and port 23053. 86 | 87 | ## License ## 88 | 89 | Copyright (C) 2014 Ibrahim Al-Rajhi 90 | 91 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 92 | 93 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 94 | 95 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 96 | -------------------------------------------------------------------------------- /example/bakery.js: -------------------------------------------------------------------------------- 1 | var growly = require('../lib/growly.js'); 2 | 3 | var notifications = [ 4 | { label: 'muffin', dispname: 'Muffin' }, 5 | { label: 'cake', dispname: 'Cake' } 6 | ], 7 | muffinopts = { label: 'muffin', icon: 'muffin.png' }, 8 | cakeopts = { label: 'cake', title: 'Cake is ready!', icon: 'cake.png', sticky: true }; 9 | 10 | growly.register('Bakery', 'muffin.png', notifications, function(err) { 11 | if (err) { 12 | console.log(err); 13 | return; 14 | } 15 | 16 | growly.notify('Looks like it is half past muffin time!', muffinopts); 17 | 18 | growly.notify('Click to deliver', cakeopts, function(err, action) { 19 | console.log('You', action, 'the notification, so the cake is on its way!'); 20 | }); 21 | }); 22 | 23 | -------------------------------------------------------------------------------- /example/cake.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theabraham/growly/bb5d7cdffa7ca05f1430b978dbc8a5f4e776492b/example/cake.png -------------------------------------------------------------------------------- /example/muffin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theabraham/growly/bb5d7cdffa7ca05f1430b978dbc8a5f4e776492b/example/muffin.png -------------------------------------------------------------------------------- /example/simple.js: -------------------------------------------------------------------------------- 1 | var growly = require('../lib/growly.js'); 2 | 3 | growly.notify('Hello, world!'); 4 | -------------------------------------------------------------------------------- /lib/gntp.js: -------------------------------------------------------------------------------- 1 | var net = require('net'), 2 | crypto = require('crypto'), 3 | format = require('util').format, 4 | fs = require('fs'); 5 | 6 | var nl = '\r\n'; 7 | 8 | /** 9 | * Create a new GNTP request of the given `type`. 10 | * 11 | * @param {String} type either NOTIFY or REGISTER 12 | * @api private 13 | */ 14 | 15 | function GNTP(type, opts) { 16 | opts = opts || {}; 17 | this.type = type; 18 | this.host = opts.host || 'localhost'; 19 | this.port = opts.port || 23053; 20 | this.request = 'GNTP/1.0 ' + type + ' NONE' + nl; 21 | this.resources = []; 22 | this.attempts = 0; 23 | this.maxAttempts = 5; 24 | } 25 | 26 | /** 27 | * Build a response object from the given `resp` response string. 28 | * 29 | * The response object has a key/value pair for every header in the response, and 30 | * a `.state` property equal to either OK, ERROR, or CALLBACK. 31 | * 32 | * An example GNTP response: 33 | * 34 | * GNTP/1.0 -OK NONE\r\n 35 | * Response-Action: REGISTER\r\n 36 | * \r\n 37 | * 38 | * Which would parse to: 39 | * 40 | * { state: 'OK', 'Response-Action': 'REGISTER' } 41 | * 42 | * @param {String} resp 43 | * @return {Object} 44 | * @api private 45 | */ 46 | 47 | GNTP.prototype.parseResp = function(resp) { 48 | var parsed = {}, head, body; 49 | resp = resp.slice(0, resp.indexOf(nl + nl)).split(nl); 50 | head = resp[0]; 51 | body = resp.slice(1); 52 | 53 | parsed.state = head.match(/-(OK|ERROR|CALLBACK)/)[0].slice(1); 54 | body.forEach(function(ln) { 55 | ln = ln.split(': '); 56 | parsed[ln[0]] = ln[1]; 57 | }); 58 | 59 | return parsed; 60 | }; 61 | 62 | /** 63 | * Call `GNTP.send()` with the given arguments after a certain delay. 64 | * 65 | * @api private 66 | */ 67 | 68 | GNTP.prototype.retry = function() { 69 | var self = this, 70 | args = arguments; 71 | setTimeout(function() { 72 | self.send.apply(self, args); 73 | }, 750); 74 | }; 75 | 76 | 77 | /** 78 | * Add a resource to the GNTP request. 79 | * 80 | * @param {Buffer} file 81 | * @return {String} 82 | * @api private 83 | */ 84 | 85 | GNTP.prototype.addResource = function(file) { 86 | var id = crypto.createHash('md5').update(file).digest('hex'), 87 | header = 'Identifier: ' + id + nl + 'Length: ' + file.length + nl + nl; 88 | this.resources.push({ header: header, file: file }); 89 | return 'x-growl-resource://' + id; 90 | }; 91 | 92 | /** 93 | * Append another header `name` with a value of `val` to the request. If `val` is 94 | * undefined, the header will be left out. 95 | * 96 | * @param {String} name 97 | * @param {String} val 98 | * @api public 99 | */ 100 | 101 | GNTP.prototype.add = function(name, val) { 102 | if (val === undefined) 103 | return; 104 | 105 | /* Handle icon files when they're image paths or Buffers. */ 106 | if (/-Icon/.test(name) && !/^https?:\/\//.test(val) ) { 107 | if (/\.(png|gif|jpe?g)$/.test(val)) 108 | val = this.addResource(fs.readFileSync(val)); 109 | else if (val instanceof Buffer) 110 | val = this.addResource(val); 111 | } 112 | 113 | this.request += name + ': ' + val + nl; 114 | }; 115 | 116 | /** 117 | * Append a newline to the request. 118 | * 119 | * @api public 120 | */ 121 | 122 | GNTP.prototype.newline = function() { 123 | this.request += nl; 124 | }; 125 | 126 | /** 127 | * Send the GNTP request, calling `callback` after successfully sending the 128 | * request. 129 | * 130 | * An example GNTP request: 131 | * 132 | * GNTP/1.0 REGISTER NONE\r\n 133 | * Application-Name: Growly.js\r\n 134 | * Notifications-Count: 1\r\n 135 | * \r\n 136 | * Notification-Name: default\r\n 137 | * Notification-Display-Name: Default Notification\r\n 138 | * Notification-Enabled: True\r\n 139 | * \r\n 140 | * 141 | * @param {Function} callback which will be passed the parsed response 142 | * @api public 143 | */ 144 | 145 | GNTP.prototype.send = function(callback) { 146 | var self = this, 147 | socket = net.connect(this.port, this.host), 148 | resp = ''; 149 | 150 | callback = callback || function() {}; 151 | 152 | this.attempts += 1; 153 | 154 | socket.on('connect', function() { 155 | socket.write(self.request); 156 | 157 | self.resources.forEach(function(res) { 158 | socket.write(res.header); 159 | socket.write(res.file); 160 | socket.write(nl + nl); 161 | }); 162 | }); 163 | 164 | socket.on('data', function(data) { 165 | resp += data.toString(); 166 | 167 | /* Wait until we have a complete response which is signaled by two CRLF's. */ 168 | if (resp.slice(resp.length - 4) !== (nl + nl)) return; 169 | 170 | resp = self.parseResp(resp); 171 | 172 | /* We have to manually close the connection for certain responses; otherwise, 173 | reset `resp` to prepare for the next response chunk. */ 174 | if (resp.state === 'ERROR' || resp.state === 'CALLBACK') 175 | socket.end(); 176 | else 177 | resp = ''; 178 | }); 179 | 180 | socket.on('end', function() { 181 | /* Retry on 200 (timed out), 401 (unknown app), or 402 (unknown notification). */ 182 | if (['200', '401', '402'].indexOf(resp['Error-Code']) >= 0) { 183 | if (self.attempts <= self.maxAttempts) { 184 | self.retry(callback); 185 | } else { 186 | var msg = 'GNTP request to "%s:%d" failed with error code %s (%s)'; 187 | callback(new Error(format(msg, self.host, self.port, resp['Error-Code'], resp['Error-Description']))); 188 | } 189 | } else { 190 | callback(undefined, resp); 191 | } 192 | }); 193 | 194 | socket.on('error', function() { 195 | callback(new Error(format('Error while sending GNTP request to "%s:%d"', self.host, self.port))); 196 | socket.destroy(); 197 | }); 198 | }; 199 | 200 | module.exports = GNTP; 201 | -------------------------------------------------------------------------------- /lib/growly.js: -------------------------------------------------------------------------------- 1 | var GNTP = require('./gntp.js'); 2 | 3 | /** 4 | * Interface for registering Growl applications and sending Growl notifications. 5 | * 6 | * @api private 7 | */ 8 | 9 | function Growly() { 10 | this.appname = 'Growly'; 11 | this.notifications = undefined; 12 | this.labels = undefined; 13 | this.count = 0; 14 | this.registered = false; 15 | this.host = undefined; 16 | this.port = undefined; 17 | } 18 | 19 | /** 20 | * Returns an array of label strings extracted from each notification object in 21 | * `Growly.notifications`. 22 | * 23 | * @param {Array} notifications 24 | * @return {Array} notification labels 25 | * @api private 26 | */ 27 | 28 | Growly.prototype.getLabels = function() { 29 | return this.notifications.map(function(notif) { 30 | return notif.label; 31 | }); 32 | }; 33 | 34 | /** 35 | * Set the host to be used by GNTP requests. 36 | * 37 | * @param {String} host 38 | * @param {Number} port 39 | * @api public 40 | */ 41 | 42 | Growly.prototype.setHost = function(host, port) { 43 | this.host = host; 44 | this.port = port; 45 | }; 46 | 47 | /** 48 | * Register an application with the name `appname` (required), icon `appicon`, and 49 | * a list of notification types `notifications`. If provided, `callback` will be 50 | * called when the request completes with the first argument being an `err` error 51 | * object if the request failed. 52 | * 53 | * Each object in the `notifications` array defines a type of notification the 54 | * application will have with the following properties: 55 | * 56 | * - `.label` name used to identify the type of notification being used (required) 57 | * - `.dispname` name users will see in Growl's preference panel (defaults to `.label`) 58 | * - `.enabled` whether or not notifications of this type are enabled (defaults to true) 59 | * - `.icon` default icon notifications of this type should use (url, file path, or Buffer object) 60 | * 61 | * Example registration: 62 | * 63 | * growl.register('My Application', 'path/to/icon.png', [ 64 | * { label: 'success', dispname: 'Success', icon: 'path/to/success.png' }, 65 | * { label: 'warning', dispname: 'Warning', icon: 'path/to/warning.png', enabled: false } 66 | * ], function(err) { console.log(err || 'Registration successful!'); }); 67 | * 68 | * @param {String} appname 69 | * @param {String|Buffer} appicon 70 | * @param {Array} notifications 71 | * @param {Function} callback 72 | * @api public 73 | */ 74 | 75 | Growly.prototype.register = function(appname, appicon, notifications, callback) { 76 | var gntp; 77 | 78 | if (typeof appicon === 'object') { 79 | notifications = appicon; 80 | appicon = undefined; 81 | } 82 | 83 | if (notifications === undefined || !notifications.length) { 84 | notifications = [{ label: 'default', dispname: 'Default Notification', enabled: true }]; 85 | } 86 | 87 | if (typeof arguments[arguments.length - 1] === 'function') { 88 | callback = arguments[arguments.length - 1]; 89 | } else { 90 | callback = function() {}; 91 | } 92 | 93 | this.appname = appname; 94 | this.notifications = notifications; 95 | this.labels = this.getLabels(); 96 | this.registered = true; 97 | 98 | gntp = new GNTP('REGISTER', { host: this.host, port: this.port }); 99 | gntp.add('Application-Name', appname); 100 | gntp.add('Application-Icon', appicon); 101 | gntp.add('Notifications-Count', notifications.length); 102 | gntp.newline(); 103 | 104 | notifications.forEach(function(notif) { 105 | if (notif.enabled === undefined) notif.enabled = true; 106 | gntp.add('Notification-Name', notif.label); 107 | gntp.add('Notification-Display-Name', notif.dispname); 108 | gntp.add('Notification-Enabled', notif.enabled ? 'True' : 'False'); 109 | gntp.add('Notification-Icon', notif.icon); 110 | gntp.newline(); 111 | }); 112 | 113 | gntp.send(callback); 114 | }; 115 | 116 | /** 117 | * Send a notification with `text` content. Growly will lazily register itself 118 | * if the user hasn't already before sending the notification. 119 | * 120 | * A notification can have the following `opts` options: 121 | * 122 | * - `.label` type of notification to use (defaults to the first registered type) 123 | * - `.title` title of the notification 124 | * - `.icon` url, file path, or Buffer instance for the notification's icon. 125 | * - `.sticky` whether or not to sticky the notification (defaults to false) 126 | * - `.priority` the priority of the notification from lowest (-2) to highest (2) 127 | * - `.coalescingId` replace/update the matching previous notification. May be ignored. 128 | * 129 | * If provided, `callback` will be called when the user interacts with the notification. 130 | * The first argument will be an `err` error object, and the second argument an `action` 131 | * string equal to either 'clicked' or 'closed' (whichever action the user took.) 132 | * 133 | * Example notification: 134 | * 135 | * growl.notify('Stuffs broken!', { label: 'warning' }, function(err, action) { 136 | * console.log('Action:', action); 137 | * }); 138 | * 139 | * @param {String} text 140 | * @param {Object} opts 141 | * @param {Function} callback 142 | * @api public 143 | */ 144 | 145 | Growly.prototype.notify = function(text, opts, callback) { 146 | var self = this, 147 | gntp; 148 | 149 | /* Lazy registration. */ 150 | if (!this.registered) { 151 | this.register(this.appname, function(err) { 152 | if (err) console.log(err); 153 | self.notify.call(self, text, opts, callback); 154 | }); 155 | return; 156 | } 157 | 158 | opts = opts || {}; 159 | 160 | if (typeof opts === 'function') { 161 | callback = opts; 162 | opts = {}; 163 | } 164 | 165 | gntp = new GNTP('NOTIFY', { host: this.host, port: this.port }); 166 | gntp.add('Application-Name', this.appname); 167 | gntp.add('Notification-Name', opts.label || this.labels[0]); 168 | gntp.add('Notification-ID', ++this.count); 169 | gntp.add('Notification-Title', opts.title); 170 | gntp.add('Notification-Text', text); 171 | gntp.add('Notification-Sticky', opts.sticky ? 'True' : 'False'); 172 | gntp.add('Notification-Priority', opts.priority); 173 | gntp.add('Notification-Icon', opts.icon); 174 | gntp.add('Notification-Coalescing-ID', opts.coalescingId || undefined); 175 | gntp.add('Notification-Callback-Context', callback ? 'context' : undefined); 176 | gntp.add('Notification-Callback-Context-Type', callback ? 'string' : undefined); 177 | gntp.add('Notification-Callback-Target', undefined); 178 | gntp.newline(); 179 | 180 | gntp.send(function(err, resp) { 181 | if (callback && err) { 182 | callback(err); 183 | } else if (callback && resp.state === 'CALLBACK') { 184 | callback(undefined, resp['Notification-Callback-Result'].toLowerCase()); 185 | } 186 | }); 187 | }; 188 | 189 | /** 190 | * Expose an instance of the Growly object. 191 | */ 192 | 193 | module.exports = new Growly(); 194 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "growly", 3 | "version": "1.3.0", 4 | "description": "Simple zero-dependency Growl notifications using GNTP.", 5 | "keywords": ["growl", "growly", "snarl", "notifications", "gntp", "messages"], 6 | "author": "Ibrahim Al-Rajhi (http://ibrahimalrajhi.com/)", 7 | "repository": "http://github.com/theabraham/growly", 8 | "bugs": "http://github.com/theabraham/growly/issues", 9 | "main": "lib/growly.js", 10 | "directories": { 11 | "example": "example", 12 | "lib": "lib" 13 | }, 14 | "license": "MIT" 15 | } 16 | --------------------------------------------------------------------------------