Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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){
Expand Down
36 changes: 15 additions & 21 deletions lib/gcm.js
Original file line number Diff line number Diff line change
@@ -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');

Expand Down Expand Up @@ -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;
Expand All @@ -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']) {
Expand All @@ -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) {
Expand Down