-
Notifications
You must be signed in to change notification settings - Fork 0
/
contactV2.js
521 lines (451 loc) · 15.8 KB
/
contactV2.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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
'use strict';
var raven = require('raven');
var elasticsearch = require('elasticsearch');
var Q = require('q');
var rp = require('request-promise');
var gcloud = require('google-cloud')({
projectId: 'newsai-1166'
});
// Instantiate a datastore client
var datastore = require('@google-cloud/datastore')({
projectId: 'newsai-1166'
});
// Initialize Google Cloud
var enhanceTopicName = 'process-enhance';
var newTwitterTopicName = 'process-twitter-feed'
var newInstagramTopicName = 'process-instagram-feed';
var topicName = 'process-new-contact-upload';
var subscriptionName = 'node-new-contact-upload';
var pubsub = gcloud.pubsub();
// Instantiate a elasticsearch client
var client = new elasticsearch.Client({
host: 'https://newsai:[email protected]',
// log: 'trace',
rejectUnauthorized: false
});
// Instantiate a sentry client
var sentryClient = new raven.Client('https://f4ab035568994293b9a2a90727ccb5fc:[email protected]/103134');
sentryClient.patchGlobal();
// Get a Google Cloud topic
function getTopic(currentTopicName, cb) {
pubsub.createTopic(currentTopicName, function(err, topic) {
// topic already exists.
if (err && err.code === 409) {
return cb(null, pubsub.topic(currentTopicName));
}
return cb(err, topic);
});
}
function addContactEmailsToPubSubTopicPublish(contactEmails) {
var deferred = Q.defer();
getTopic(enhanceTopicName, function(err, topic) {
if (err) {
deferred.reject(new Error(err));
console.error('Error occurred while getting pubsub topic', err);
sentryClient.captureMessage(err);
} else {
topic.publish({
data: {
email: contactEmails
}
}, function(err) {
if (err) {
deferred.reject(new Error(err));
console.error('Error occurred while queuing background task', err);
sentryClient.captureMessage(err);
} else {
deferred.resolve(true);
}
});
}
});
return deferred.promise;
}
function addContactEmailToPubSub(contactEmails) {
var allPromises = [];
var i, j, tempArray, chunk = 75;
for (i = 0, j = contactEmails.length; i < j; i += chunk) {
// Break array into a chunk
tempArray = contactEmails.slice(i, i + chunk);
var tempString = tempArray.join(',');
// Execute contact sync
var toExecute = addContactEmailsToPubSubTopicPublish(tempString);
allPromises.push(toExecute);
}
return Q.all(allPromises);
}
function addContactInstagramUsernameToPubSubTopicPublish(contactInstagramUsernames) {
var deferred = Q.defer();
getTopic(newInstagramTopicName, function(err, topic) {
if (err) {
deferred.reject(new Error(err));
console.error('Error occurred while getting pubsub topic', err);
sentryClient.captureMessage(err);
} else {
topic.publish({
data: {
username: contactInstagramUsernames
}
}, function(err) {
if (err) {
deferred.reject(new Error(err));
console.error('Error occurred while queuing background task', err);
sentryClient.captureMessage(err);
} else {
deferred.resolve(true);
}
});
}
});
return deferred.promise;
}
function addInstagramUsernameToPubSub(contactInstagramUsernames) {
var allPromises = [];
var i, j, tempArray, chunk = 75;
for (i = 0, j = contactInstagramUsernames.length; i < j; i += chunk) {
// Break array into a chunk
tempArray = contactInstagramUsernames.slice(i, i + chunk);
var tempString = tempArray.join(',');
// Execute contact sync
var toExecute = addContactInstagramUsernameToPubSubTopicPublish(tempString);
allPromises.push(toExecute);
}
return Q.all(allPromises);
}
function addContactTwitterUsernameToPubSubTopicPublish(contactTwitterUsernames) {
var deferred = Q.defer();
getTopic(newTwitterTopicName, function(err, topic) {
if (err) {
deferred.reject(new Error(err));
console.error('Error occurred while getting pubsub topic', err);
sentryClient.captureMessage(err);
} else {
topic.publish({
data: {
username: contactTwitterUsernames
}
}, function(err) {
if (err) {
deferred.reject(new Error(err));
console.error('Error occurred while queuing background task', err);
sentryClient.captureMessage(err);
} else {
deferred.resolve(true);
}
});
}
});
return deferred.promise;
}
function addTwitterUsernameToPubSub(contactTwitterUsernames) {
var allPromises = [];
var i, j, tempArray, chunk = 75;
for (i = 0, j = contactTwitterUsernames.length; i < j; i += chunk) {
// Break array into a chunk
tempArray = contactTwitterUsernames.slice(i, i + chunk);
var tempString = tempArray.join(',');
// Execute contact sync
var toExecute = addContactTwitterUsernameToPubSubTopicPublish(tempString);
allPromises.push(toExecute);
}
return Q.all(allPromises);
}
/**
* Gets a Datastore key from the kind/key pair in the request.
*
* @param {Object} requestData Cloud Function request data.
* @param {string} requestData.Id Datastore ID string.
* @returns {Object} Datastore key object.
*/
function getKeysFromRequestData(requestData, resouceType) {
if (!requestData.Id) {
throw new Error("Id not provided. Make sure you have a 'Id' property " +
"in your request");
}
var ids = requestData.Id.split(',');
var keys = [];
for (var i = ids.length - 1; i >= 0; i--) {
var contactId = parseInt(ids[i], 10);
var datastoreId = datastore.key([resouceType, contactId]);
keys.push(datastoreId);
}
return keys;
}
/**
* Retrieves a record.
*
* @example
* gcloud alpha functions call ds-get --data '{'kind':'gcf-test','key':'foobar'}'
*
* @param {Object} context Cloud Function context.
* @param {Function} context.success Success callback.
* @param {Function} context.failure Failure callback.
* @param {Object} data Request data, in this case an object provided by the user.
* @param {string} data.kind The Datastore kind of the data to retrieve, e.g. 'user'.
* @param {string} data.key Key at which to retrieve the data, e.g. 5075192766267392.
*/
function getDatastore(data, resouceType) {
var deferred = Q.defer();
try {
var keys = getKeysFromRequestData(data, resouceType);
datastore.get(keys, function(err, entities) {
if (err) {
console.error(err);
sentryClient.captureMessage(err);
deferred.reject(new Error(err));
}
// The get operation will not fail for a non-existent entities, it just
// returns null.
if (!entities) {
var error = 'Entity does not exist';
console.error(error);
sentryClient.captureMessage(error);
deferred.reject(new Error(error));
}
deferred.resolve(entities);
});
} catch (err) {
console.error(err);
sentryClient.captureMessage(err);
deferred.reject(new Error(err));
}
return deferred.promise;
}
/**
* Format a contact for ES sync
*
* @param {Object} contactData Contact details from datastore.
*/
function formatESContact(contactId, contactData) {
contactData['Id'] = contactId;
if ('CustomFields.Name' in contactData && 'CustomFields.Value' in contactData) {
// Populate a column for contactData
contactData['CustomFields'] = [];
for (var i = contactData['CustomFields.Name'].length - 1; i >= 0; i--) {
var singleData = {};
singleData.Name = contactData['CustomFields.Name'][i];
singleData.Value = contactData['CustomFields.Value'][i];
contactData['CustomFields'].push(singleData);
}
// Remove the name and value fields
delete contactData['CustomFields.Name'];
delete contactData['CustomFields.Value'];
}
return contactData;
}
/**
* Add a contact to ES
*
* @param {Object} contactData Contact details from datastore.
* Returns true if adding data works and false if not.
*/
function addToElastic(contacts) {
var deferred = Q.defer();
var esActions = [];
for (var i = contacts.length - 1; i >= 0; i--) {
var contactId = contacts[i].key.id;
var contactData = contacts[i].data;
var postContactData = formatESContact(contactId, contactData);
var indexRecord = {
index: {
_index: 'contacts',
_type: 'contact_v2',
_id: contactId
}
};
var dataRecord = postContactData;
esActions.push(indexRecord);
esActions.push({
data: dataRecord
});
}
client.bulk({
body: esActions
}, function(error, response) {
if (error) {
sentryClient.captureMessage(error);
deferred.reject(false);
}
deferred.resolve(true);
});
return deferred.promise;
}
/**
* Syncs a contact information to elasticsearch.
*
* @param {Object} contact Contact details from datastore.
*/
function getAndSyncElastic(contacts) {
var deferred = Q.defer();
addToElastic(contacts).then(function(status) {
if (status) {
var contactEmails = [];
var contactTwitterUsernames = [];
var contactInstagramUsernames = [];
for (var i = 0; i < contacts.length; i++) {
contactEmails.push(contacts[i].data.Email);
if (contacts[i].data.Twitter !== '') {
contactTwitterUsernames.push(contacts[i].data.Twitter);
}
if (contacts[i].data.Instagram !== '') {
contactInstagramUsernames.push(contacts[i].data.Instagram);
}
}
addContactEmailToPubSub(contactEmails).then(function(status) {
addTwitterUsernameToPubSub(contactTwitterUsernames).then(function(status) {
addInstagramUsernameToPubSub(contactInstagramUsernames).then(function(status) {
deferred.resolve(true);
}, function(error) {
sentryClient.captureMessage(error);
deferred.reject(false);
});
}, function(error) {
sentryClient.captureMessage(error);
deferred.reject(false);
});
}, function(error) {
sentryClient.captureMessage(error);
deferred.reject(false);
});
} else {
deferred.resolve(false);
}
});
return deferred.promise;
}
function removeContactFromElastic(contactId) {
var deferred = Q.defer();
var esActions = [];
var eachRecord = {
delete: {
_index: 'contacts',
_type: 'contact_v2',
_id: contactId
}
};
esActions.push(eachRecord);
client.bulk({
body: esActions
}, function(error, response) {
if (error) {
deferred.resolve(false);
} else {
deferred.resolve(true);
}
});
return deferred.promise;
}
function syncContact(data) {
var deferred = Q.defer();
if (data.Method && data.Method.toLowerCase() === 'create') {
getDatastore(data, 'Contact').then(function(contacts) {
if (contacts != null) {
getAndSyncElastic(contacts).then(function(elasticResponse) {
if (elasticResponse) {
deferred.resolve('Success!');
} else {
var error = 'Elastic sync failed';
sentryClient.captureMessage(error);
deferred.reject(new Error(error));
throw new Error(error);
}
});
} else {
var error = 'Contact not found';
sentryClient.captureMessage(error);
deferred.reject(new Error(error));
throw new Error(error);
}
}, function(error) {
sentryClient.captureMessage(error);
deferred.reject(new Error(error));
throw new Error(error);
});
} else if (data.Method && data.Method.toLowerCase() === 'delete') {
if (!data.Id) {
throw new Error("Id not provided. Make sure you have a 'Id' property " +
"in your request");
}
var contactId = parseInt(data.Id, 10);
removeContactFromElastic(contactId).then(function(elasticResponse) {
if (elasticResponse) {
deferred.resolve('Success!');
} else {
var error = 'Elastic removal failed for ' + data.Id;
sentryClient.captureMessage(error);
deferred.reject(new Error(error));
throw new Error(error);
}
});
} else {
// This case should never happen unless wrong pub/sub method is called.
var error = 'Can not parse method ' + data.Method;
sentryClient.captureMessage(error);
deferred.reject(new Error(error));
throw new Error(error);
}
return deferred.promise;
}
// Subscribe to Pub/Sub for this particular topic
function subscribe(cb) {
var subscription;
// Event handlers
function handleMessage(message) {
cb(null, message);
}
function handleError(err) {
sentryClient.captureMessage(err);
console.error(err);
}
getTopic(topicName, function(err, topic) {
if (err) {
return cb(err);
}
topic.subscribe(subscriptionName, {
autoAck: true,
reuseExisting: true
}, function(err, sub) {
if (err) {
return cb(err);
}
subscription = sub;
// Listen to and handle message and error events
subscription.on('message', handleMessage);
subscription.on('error', handleError);
console.log('Listening to ' + topicName +
' with subscription ' + subscriptionName);
});
});
// Subscription cancellation function
return function() {
if (subscription) {
// Remove event listeners
subscription.removeListener('message', handleMessage);
subscription.removeListener('error', handleError);
subscription = undefined;
}
};
}
// Begin subscription
subscribe(function(err, message) {
// Any errors received are considered fatal.
if (err) {
sentryClient.captureMessage(err);
console.error(err);
throw err;
}
console.log('Received request to process contacts: ' + message.data.Id.length);
syncContact(message.data)
.then(function(status) {
rp('https://hchk.io/d01a4dde-670b-4083-b749-e1bc1079d616')
.then(function(htmlString) {
console.log('Completed execution for ' + message.data.Id.length);
})
.catch(function(err) {
console.error(err);
});
}, function(error) {
sentryClient.captureMessage(error);
console.error(error);
});
});