forked from Ajnasz/Google-Contacts
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathindex.js
249 lines (206 loc) · 6.74 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
/**
* @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,
_ = require('lodash'),
qs = require('querystring'),
util = require('util'),
url = require('url'),
https = require('https'),
debug = require('debug')('google-contacts');
var GoogleContacts = function (params) {
if (typeof params === 'string') {
params = {token: params}
}
if (!params) {
params = {};
}
this.contacts = [];
this.consumerKey = params.consumerKey ? params.consumerKey : null;
this.consumerSecret = params.consumerSecret ? params.consumerSecret : null;
this.token = params.token ? params.token : null;
this.refreshToken = params.refreshToken ? params.refreshToken : null;
this.params = _.defaults(params, {thin: true});
};
GoogleContacts.prototype = {};
util.inherits(GoogleContacts, EventEmitter);
GoogleContacts.prototype._get = function (params, cb) {
if (typeof params === 'function') {
cb = params;
params = {};
}
var req = {
host: 'www.google.com',
port: 443,
path: this._buildPath(params),
method: 'GET',
headers: {
'Authorization': 'OAuth ' + this.token,
'GData-Version': 3
}
};
debug(req);
https.request(req, function (res) {
var data = '';
res.on('data', function (chunk) {
debug('got ' + chunk.length + ' bytes');
data += chunk.toString('utf-8');
});
res.on('error', function (err) {
cb(err);
});
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 {
debug(data);
cb(null, JSON.parse(data));
}
catch (err) {
cb(err);
}
});
})
.on('error', cb)
.end();
};
GoogleContacts.prototype.getContacts = function (cb, params) {
var self = this;
this._get(_.extend({type: 'contacts'}, params, this.params), receivedContacts);
function receivedContacts(err, data) {
if (err) return cb(err);
var feed = _.get(data, 'feed', []);
var entry = _.get(data, 'feed.entry', []);
if (!entry.length) {
return cb(null, entry);
}
self._saveContactsFromFeed(feed);
var next = false;
_.each(feed.link, function (link) {
if (link.rel === 'next') {
next = true;
var path = url.parse(link.href).path;
self._get({path: path}, receivedContacts);
}
});
if (!next) {
cb(null, self.contacts);
}
}
};
GoogleContacts.prototype.getContact = function (cb, params) {
var self = this;
if(!_.has(params, 'id')){
return cb("No id found in params");
}
this._get(_.extend({type: 'contacts'}, this.params, params), receivedContact);
function receivedContact(err, contact) {
if (err) return cb(err);
cb(null, contact);
}
};
GoogleContacts.prototype._saveContactsFromFeed = function (feed) {
var self = this;
_.each(feed.entry, function (entry) {
var el, url;
if (self.params.thin) {
url = _.get(entry, 'id.$t', '');
el = {
name: _.get(entry, 'title.$t'),
email: _.get(entry, 'gd$email.0.address'), // only save first email
phoneNumber: _.get(entry, 'gd$phoneNumber.0.uri', '').replace('tel:', ''),
id: url.substring(_.lastIndexOf(url, '/') + 1)
};
} else {
el = entry;
}
self.contacts.push(el);
});
};
GoogleContacts.prototype._buildPath = function (params) {
if (params.path) return params.path;
params = _.extend({}, params, this.params);
params.type = params.type || 'contacts';
params.alt = params.alt || 'json';
params.projection = params.projection || (params.thin ? 'thin' : 'full');
params.email = params.email || 'default';
params['max-results'] = params['max-results'] || 10000;
var query = {
alt: params.alt
};
if(!params.id) query['max-results'] = params['max-results'];
if (params['updated-min'])
query['updated-min'] = params['updated-min'];
if (params.q || params.query)
query.q = params.q || params.query;
var path = '/m8/feeds/';
path += params.type + '/';
path += params.email + '/';
path += params.projection;
if(params.id) path += '/'+ params.id;
path += '?' + qs.stringify(query);
return path;
};
GoogleContacts.prototype.refreshAccessToken = function (refreshToken, params, 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', cb);
}).on('error', cb);
req.write(body);
req.end();
};
exports.GoogleContacts = GoogleContacts;