forked from SpeCT/node-c2dm
/
c2dm.js
158 lines (139 loc) · 5.23 KB
/
c2dm.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
var util = require('util');
var https = require('https');
var querystring = require('querystring');
var emitter = require('events').EventEmitter;
var retry = require('retry');
function C2DM(config) {
if (config) {
if ('user' in config)
this.user = config.user;
if ('password' in config)
this.password = config.password;
this.source = 'source' in config ? config.source : 'node-c2dm-client';
this.token = 'token' in config ? config.token : null;
this.keepAlive = 'keepAlive' in config ? config.keepAlive : false;
} else {
throw Error('No config given.');
}
this.loginOptions = {
host: 'www.google.com',
port: 443,
path: '/accounts/ClientLogin',
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
};
this.c2dmOptions = {
host: 'android.apis.google.com',
port: 443,
path: '/c2dm/send',
method: 'POST',
headers: {}
};
this.on('token', this.captureToken);
}
util.inherits(C2DM, emitter);
exports.C2DM = C2DM;
C2DM.prototype.captureToken = function(err, token) {
this.token = token;
};
C2DM.prototype.login = function(cb) {
var self = this;
if (cb) this.once('token', cb);
var postData = {
Email: this.user,
Passwd: this.password,
accountType: 'HOSTED_OR_GOOGLE',
source: this.source,
service: 'ac2dm'
};
var request = https.request(this.loginOptions, function(res) {
var data = '';
function respond() {
var idx = data.indexOf('Auth=');
if (idx < 0) {
self.emit('token', data, null);
} else {
self.emit('token', null, data.substring(idx).replace('Auth', 'auth').replace(/(\n)+$/, ''));
}
}
res.on('data', function(chunk) {
data += chunk;
});
res.on('end', respond);
res.on('close', respond);
});
request.end(querystring.stringify(postData));
};
C2DM.prototype.send = function(packet, cb) {
var self = this;
if (cb) this.once('sent', cb);
var operation = retry.operation();
operation.attempt(function(currentAttempt) {
var postData = querystring.stringify(packet);
var headers = {
//'Connection': 'keep-alive',
'Host': 'android.apis.google.com',
'Authorization': 'GoogleLogin ' + self.token,
'Content-Type': 'application/x-www-form-urlencoded',
'Content-length': postData.length
};
self.c2dmOptions.headers = headers;
if (self.keepAlive)
headers.Connection = 'keep-alive';
var request = https.request(self.c2dmOptions, function(res) {
var data = '';
if (res.statusCode == 503) {
// 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']) {
var retrySeconds = res.headers['retry-after'] * 1; // force number
if (isNaN(retrySeconds)) {
// The Retry-After header is a HTTP-date, try to parse it
retrySeconds = new Date(res.headers['retry-after']).getTime() - new Date().getTime();
}
if (!isNaN(retrySeconds) && retrySeconds > 0) {
operation._timeouts['minTimeout'] = retrySeconds;
}
}
if (!operation.retry('TemporaryUnavailable')) {
self.emit('sent', operation.mainError(), null);
}
// Ignore all subsequent events for this request
return;
}
// Check if we need to update the headers and try again
var newToken = res.headers['update-client-auth'];
if (newToken) {
// self.emit('token', null, newToken);
self.emit('token', null, 'Auth=' + newToken);
self.send(packet, cb);
return; // ignore any other events from this request
}
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';
}
// Only retry if error is QuotaExceeded or DeviceQuotaExceeded
if (operation.retry(['QuotaExceeded', 'DeviceQuotaExceeded', 'InvalidServerResponse'].indexOf(error) >= 0 ? error : null)) {
return;
}
// Success, return message id (without id=)
self.emit('sent', error, id);
}
res.on('data', function(chunk) {
data += chunk;
});
res.on('end', respond);
res.on('close', respond);
});
request.end(postData);
});
};