diff --git a/README.md b/README.md index 00bdb30..159c0b8 100644 --- a/README.md +++ b/README.md @@ -23,8 +23,10 @@ As a submodule of your project var message = { registration_id: 'Device registration id', // required collapse_key: 'Collapse key', - 'data.key1': 'value1', - 'data.key2': 'value2' + data: { + key1: 'value1', + key2: 'value2' + } }; gcm.send(message, function(err, messageId){ diff --git a/lib/gcm.js b/lib/gcm.js index b8cccea..07c1570 100644 --- a/lib/gcm.js +++ b/lib/gcm.js @@ -1,6 +1,5 @@ var util = require('util'); var https = require('https'); -var querystring = require('querystring'); var emitter = require('events').EventEmitter; var retry = require('retry'); @@ -30,11 +29,11 @@ GCM.prototype.send = function(packet, cb) { var operation = retry.operation(); operation.attempt(function(currentAttempt) { - var postData = querystring.stringify(packet); + var postData = JSON.stringify(packet); var headers = { 'Host': self.gcmOptions.host, 'Authorization': 'key=' + self.apiKey, - 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', + 'Content-Type': 'application/json', 'Content-length': postData.length }; self.gcmOptions.headers = headers; @@ -44,7 +43,7 @@ GCM.prototype.send = function(packet, cb) { var request = https.request(self.gcmOptions, function(res) { var data = ''; - if (res.statusCode == 503) { + if (res.statusCode >= 501 && res.statusCode < 600) { // If the server is temporary unavailable, the C2DM spec requires that we implement exponential backoff // and respect any Retry-After header if (res.headers['retry-after']) { @@ -65,26 +64,21 @@ GCM.prototype.send = function(packet, cb) { } function respond() { - var error = null, id = null; - if (data.indexOf('Error=') === 0) { - error = data.substring(6).trim(); - } - else if (data.indexOf('id=') === 0) { - id = data.substring(3).trim(); - } - else { - // No id nor error? - error = 'InvalidServerResponse'; - } + if(res.statusCode >= 200 && res.statusCode < 300) { + //Success + self.emit('sent', null, JSON.parse(data)) + } else { + //Error - // Only retry if error is QuotaExceeded or DeviceQuotaExceeded - if (operation.retry(['QuotaExceeded', 'DeviceQuotaExceeded', 'InvalidServerResponse'].indexOf(error) >= 0 ? error : null)) { - return; - } + if (data == "DeviceMessageRateExceeded" || data == "DEVICE_MESSAGE_RATE_EXCEEDED") { + if (operation.retry(data)) { + return; + } + } - // Success, return message id (without id=) - self.emit('sent', error, id); + self.emit('sent', data, null) + } } res.on('data', function(chunk) {