forked from olalonde/Google-Contacts
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
299 lines (246 loc) · 6.85 KB
/
index.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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
/**
* @todo: recursively send requests until all contacts are fetched
*
* @see https://developers.google.com/google-apps/contacts/v3/reference#ContactsFeed
*
* To API test requests:
*
* @see https://developers.google.com/oauthplayground/
*
* To format JSON nicely:
*
* @see http://jsonviewer.stack.hu/
*
* Note: The Contacts API has a hard limit to the number of results it can return at a
* time even if you explicitly request all possible results. If the requested feed has
* more fields than can be returned in a single response, the API truncates the feed and adds
* a "Next" link that allows you to request the rest of the response.
*/
var EventEmitter = require('events').EventEmitter,
qs = require('querystring'),
util = require('util'),
url = require('url'),
https = require('https'),
_ = require('lodash');
var GoogleContacts = function (opts) {
if (typeof opts === 'string') {
opts = { token: opts }
}
if (!opts) {
opts = {};
}
this.contacts = [];
this.consumerKey = opts.consumerKey ? opts.consumerKey : null;
this.consumerSecret = opts.consumerSecret ? opts.consumerSecret : null;
this.token = opts.token ? opts.token : null;
this.refreshToken = opts.refreshToken ? opts.refreshToken : null;
};
GoogleContacts.prototype = {};
util.inherits(GoogleContacts, EventEmitter);
GoogleContacts.prototype._get = function (params, cb) {
var self = this;
if (typeof params === 'function') {
cb = params;
params = {};
}
var req = {
host: 'www.google.com',
port: 443,
path: this._buildPath(params),
method: 'GET',
headers: {
'Authorization': 'Bearer ' + this.token
}
};
https.request(req, function (res) {
var data = '';
res.on('end', function () {
if (res.statusCode < 200 || res.statusCode >= 300) {
var error = new Error('Bad client request status: ' + res.statusCode);
return cb(error);
}
try {
data = JSON.parse(data);
cb(null, data);
}
catch (err) {
cb(err);
}
});
res.on('data', function (chunk) {
data += chunk;
});
res.on('error', function (err) {
cb(err);
});
}).on('error', function (err) {
cb(err);
}).end();
};
GoogleContacts.prototype.getContacts = function (params, cb, contacts) {
var self = this;
if (typeof params == "function") { cb = params; params = {}; }
this._get(params, receivedContacts);
function receivedContacts(err, data) {
if (err) return cb(err);
self._saveContactsFromFeed(data.feed, params);
var next = false;
data.feed.link.forEach(function (link) {
if (link.rel === 'next') {
next = true;
var path = url.parse(link.href).path;
self._get(_.extend(params, { path: path }), receivedContacts);
}
});
if (!next) {
cb(null, self.contacts);
}
};
};
// grab a property off an entry
function val(entry, name, attr, delimiter) {
if (!entry[name]) return;
if (!Array.isArray(entry[name])) {
return entry[name][attr];
} else if (delimiter) {
return entry[name].map(function(item) {
return {
label : item.rel ? item.rel.split(delimiter)[1] : "default",
field : item[attr]
}
});
} else {
return entry[name][0][attr];
}
}
var processors = {
'thin' : function(contacts) { return function(entry) {
contacts.push({
name : val(entry, 'title', '$t'),
email : val(entry, 'gd$email', 'address')
});
} },
'full' : function(contacts) { return function(entry) {
contacts.push({
name : val(entry, 'title', '$t'),
email : val(entry, 'gd$email', 'address'),
phones: val(entry, 'gd$phoneNumber', '$t', '#')
});
} },
'custom': function(contacts, projection) {
// pull apart the properties
var props = projection.split(',').map(function(prop) {
return prop.replace('property-', '');
});
// always include name
props.unshift("name");
// https://developers.google.com/google-apps/contacts/v3/reference#ProjectionsAndExtended
// a map of property names to places on the contact
var prop_names = {
"name" : "title",
"email" : "gd$email",
"phoneNumber": "gd$phoneNumber"
}
var prop_attr = {
"name" : "$t",
"email" : "address",
"phoneNumber" : "$t"
}
// generating a collection of functions
var objector = { };
_.each(props, function(prop) {
objector[prop] = _.partialRight(val, prop_names[prop], prop_attr[prop]);
});
return function(entry) {
var obj = {};
_.each(props, function(prop) {
obj[prop] = objector[prop](entry);
});
contacts.push(obj);
}
}
}
GoogleContacts.prototype._saveContactsFromFeed = function (feed, params) {
var self = this;
// detect which type of projection is being used
var processor;
// dynamic detection of processor type
if (processors[params.projection]) {
processor = processors[params.projection](self.contacts)
} else {
processor = processors.custom(self.contacts, params.projection);
}
// run the processor over each entry
feed.entry.forEach(processor);
}
GoogleContacts.prototype._buildPath = function (params) {
params = _.defaults(params, {
type: 'contacts',
alt : 'json',
projection: 'thin',
email : 'default',
'max-results' : 2000
});
if (params.path) return params.path;
var query = {
alt: params.alt,
'max-results': params['max-results']
};
var path = '/m8/feeds/';
path += params.type + '/';
path += params.email + '/';
path += params.projection;
path += '?' + qs.stringify(query);
return path;
};
GoogleContacts.prototype.refreshAccessToken = function (refreshToken, cb) {
if (typeof params === 'function') {
cb = params;
params = {};
}
var data = {
refresh_token: refreshToken,
client_id: this.consumerKey,
client_secret: this.consumerSecret,
grant_type: 'refresh_token'
}
var body = qs.stringify(data);
var opts = {
host: 'accounts.google.com',
port: 443,
path: '/o/oauth2/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': body.length
}
};
var req = https.request(opts, function (res) {
var data = '';
res.on('end', function () {
if (res.statusCode < 200 || res.statusCode >= 300) {
var error = new Error('Bad client request status: ' + res.statusCode);
return cb(error);
}
try {
data = JSON.parse(data);
cb(null, data.access_token);
}
catch (err) {
cb(err);
}
});
res.on('data', function (chunk) {
data += chunk;
});
res.on('error', function (err) {
cb(err);
});
//res.on('close', onFinish);
}).on('error', function (err) {
cb(err);
});
req.write(body);
req.end();
}
module.exports = GoogleContacts;