forked from MeltwaterArchive/NodeJS-Consumer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatasift.js
342 lines (276 loc) · 7.37 KB
/
datasift.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
var http = require('http');
var util = require('util');
var events = require('events');
/**
* Creates DataSift instance
*
* @param string username
* @param string API key
*
* @return void
*/
function DataSift(username, apiKey, host, port) {
events.EventEmitter.call(this);
var self = this;
//The username
this.username = username;
//The API key
this.apiKey = apiKey;
//The user agent
this.userAgent = 'DataSiftNodeConsumer/0.2.1';
//The host
if (host !== undefined) {
this.host = host;
} else {
this.host = 'stream.datasift.com';
}
//The port
if (port !== undefined) {
this.port = port;
} else {
this.port = 80;
}
//The request object
this.request = null;
//The response object
this.response = null;
//Last connect
this.lastConnect = null;
//Data
this.data = '';
//When did we last receive data?
this.lastReceivedDataDate = null;
//Add a listener for processing closing
process.on('exit', function () {
self.disconnect();
});
//Connect timeout
this.connectTimeout = null;
//Convert the next error to a success
this.convertNextError = false;
//Error callback
this.errorCallback = function(err, emitDisconnect) {
if (emitDisconnect === undefined) {
emitDisconnect = false;
}
self.emit('error', err);
self.disconnect(emitDisconnect);
}
//Disconnection callback
this.disconnectCallback = function() {
//Handle disconnection
self.disconnect(true);
}
//Data callback
this.dataCallback = function(chunk) {
//Convert to utf8 from buffer
chunk = chunk.toString('utf8');
//Add chunk to data
self.data += chunk;
//If the string contains a line break we will have JSON to process
if (chunk.indexOf("\n") > 0) {
//Split by line space and look for json start
var data = self.data.split("\n");
if (data[0] !== undefined) {
var json = null;
try {json = JSON.parse(data[0])} catch (e) {}
if (json != null) {
self.receivedData(json);
}
}
//Add the second half of the chunk to a new piece of data
self.data = data[1];
}
}
//Response callback
this.responseCallback = function(response) {
self.response = response;
//Set the last successful connect
self.lastConnect = new Date().getTime();
//Clear the request timeout
if (self.connectTimeout != null) {
clearTimeout(self.connectTimeout);
}
//Emit a connected event
self.emit('connect');
//Disconnection
response.connection.on('end', self.disconnectCallback);
//When we receive data do something with it
response.on('data', self.dataCallback);
};
}
util.inherits(DataSift, events.EventEmitter);
/**
* Open a connection to DataSift
*
* @return void
*/
DataSift.prototype.connect = function() {
var self = this;
//Connect if we are allowed
if (this.lastConnect == null || this.lastConnect < new Date().getTime() - 250) {
//Create the headers
var headers = {
'User-Agent' : this.userAgent,
'Host' : this.host,
'Connection' : 'Keep-Alive',
'Transfer-Encoding' : 'chunked',
'Authorization' : this.username + ':' + this.apiKey
};
//Create an http client
var client = http.createClient(this.port, this.host);
//Make the request
this.request = client.request("GET", '/', headers);
//Check for an error on connection
client.on('error', function(){
self.errorCallback(new Error('Error connecting to DataSift: Could not reach DataSift. Check your internet connection.'));
});
//Add a connection timeout
this.connectTimeout = setTimeout(function() {
if (self.request != null) {
self.request.abort();
self.errorCallback(new Error('Error connecting to DataSift: Timed out waiting for a response'));
self.disconnect(true);
}
clearTimeout(self.connectTimeout);
self.connectTimeout = null;
}, 5000);
//Check for an error
this.request.on('error', this.errorCallback);
//Add a listener for the response
this.request.on('response', this.responseCallback);
this.request.write("\n", 'utf8');
} else {
//Not allowed to reconnect so emit error
this.errorCallback(new Error('You cannot reconnect too soon after a disconnection'), true);
}
};
/**
* Disconnected from DataSift
*
* @param boolean forced if the disconnection was forced or not
*
* @return void
*/
DataSift.prototype.disconnect = function(forced) {
if (forced && this.request !== null) {
//Reset request and response
this.emit('disconnect');
//Remove listeners
this.request.removeListener('error', this.errorCallback);
this.request.removeListener('response', this.responseCallback);
if (this.response != null) {
this.response.connection.removeListener('end', this.disconnectCallback);
this.response.removeListener('data', this.dataCallback);
}
//Clear the request and response objects
this.request = null;
this.response = null;
// We do not want to convert the next error in this case
this.convertNextError = false;
} else if (this.request !== null) {
//Send the stop message and convert the error response
this.convertNextError = true;
this.send(JSON.stringify({"action":"stop"}));
}
};
/**
* Subscribe to a hash
*
* @param string hash the stream hash
*
* @return void
*/
DataSift.prototype.subscribe = function(hash) {
//Check the hash
if (!this.checkHash(hash)) {
//Send error
this.emit('error', new Error('Invalid hash given: ' + hash));
} else {
//Send json message to DataSift to subscribe
this.send(JSON.stringify({"action":"subscribe", "hash":hash}));
}
};
/**
* Unsubscribe from a hash
*
* @param string hash the stream hash
*
* @return void
*/
DataSift.prototype.unsubscribe = function(hash) {
//Check the hash
if (!this.checkHash(hash)) {
//Send error
this.emit('error', new Error('Invalid hash given: ' + hash));
} else {
//Send json message to DataSift to unsubscribe
this.send(JSON.stringify({"action":"unsubscribe", "hash":hash}));
}
};
/**
* Send data to DataSift
*
* @param string message the message
*
* @return void
*/
DataSift.prototype.send = function(message) {
if (this.request != null) {
this.request.write(message, 'utf8');
} else {
this.emit('error', new Error('You cannot send actions without being connected to DataSift'));
}
};
/**
* Process received data
*
* @param Object the json object
*
* @return void
*/
DataSift.prototype.receivedData = function(json) {
this.lastReceivedDataDate = new Date();
//Check for errors
if (json.status == "failure") {
if (this.convertNextError) {
this.emit('success', json.message);
this.convertNextError = false;
} else {
this.errorCallback(new Error(json.message));
this.disconnect(true);
}
//Check for warnings
} else if (json.status == "warning") {
this.emit('warning', json.message, json);
//Check for successes
} else if (json.status == "success") {
this.emit('success', json.message, json);
//Check for deletes
} else if (json.data !== undefined && json.data.deleted === true) {
this.emit('delete', json);
//Check for ticks
} else if (json.tick !== undefined) {
this.emit('tick', json);
//Normal interaction
} else {
this.emit('interaction', json);
}
};
/**
* Subscribe to a hash
*
* @param string hash the stream hash
*
* @return void
*/
DataSift.prototype.checkHash = function(hash) {
try {hash = /([a-f0-9]{32})/i.exec(hash)[1];} catch(e) {}
if (hash == null) {
return false;
} else {
return true;
}
};
//Add exports
module.exports = DataSift;