forked from swhitley/TwitterStreamClient
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTwitterStream.cs
More file actions
executable file
·485 lines (400 loc) · 11.6 KB
/
TwitterStream.cs
File metadata and controls
executable file
·485 lines (400 loc) · 11.6 KB
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
using System;
using System.Text;
using System.Web;
using System.IO;
using System.IO.Pipes;
using System.Net;
using System.Configuration;
using System.Threading;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.Serialization.Json;
using System.Messaging;
using System.Security.Cryptography;
using TwitterStreamClient.TwitterObjects;
// TODO: some of the JSON messages can't be read correctly
// so they throw an exception when they cant be parsed
namespace TwitterStreamClient
{
public class TwitterStream
{
private Logger logger = new Logger();
private string username = null;
private string password = null;
private string streamUrl = null;
private static bool debugging = false;
private bool isFiltered = false;
private TwitterStreamFilter filter = null;
private bool useMessageQueue;
private MessageQueue queue;
public string messagePath = @"./private$/Twitter";
public const string filteredEndpoint = "https://stream.twitter.com/1.1/statuses/filter.json";
public const string sampleEndpoint = "https://stream.twitter.com/1.1/statuses/sample.json";
private HttpWebRequest webRequest = null;
private HttpWebResponse webResponse = null;
private StreamReader responseStream = null;
private Encoding defaultEncoding = System.Text.Encoding.GetEncoding ("utf-8");
private Thread backgroundThread = null;
private bool abortFlag = false;
private SynchronizedQueue<string> jsonQueue;
/* Obtain parameters from App.config */
public TwitterStream ()
{
username = ConfigurationManager.AppSettings ["twitter_username"];
password = ConfigurationManager.AppSettings ["twitter_password"];
if (ConfigurationManager.AppSettings ["twitter_password_encrypted"] == "true") {
password = Common.Decrypt (password);
}
//Twitter Streaming API
streamUrl = ConfigurationManager.AppSettings ["stream_url"];
}
/*
* Constructor - Makes stream with no filter by default
* and no IPC message queue
*
* To use with a message queue for IPC, call SetUseQueue(true)
*
*/
public TwitterStream (string user, string pass, bool isEncrypted)
{
if (isEncrypted) {
password = Common.Decrypt (pass);
} else {
password = pass;
}
username = user;
password = pass;
jsonQueue = new SynchronizedQueue<string> ();
SetFiltered(false);
}
/*
* SetDebugging(bool debug)
*
* if true, will output json messages to the console
*/
public void SetDebugging (bool debug)
{
debugging = debug;
}
/*
* SetFiltered(bool filter)
*
* If set to true, changes the Twitter API endpoint
* to the filtered url (filter.json)
*
* If set to false, uses the unfiltered url (sample.json)
*/
private void SetFiltered (bool filter)
{
isFiltered = filter;
if (isFiltered) {
streamUrl = filteredEndpoint;
} else {
streamUrl = sampleEndpoint;
}
}
/*
* SetStreamFilter(TwitterStreamFilter filter)
*
* Filter object contains all filters that can be
* used with the Twitter API
*
*/
public void SetStreamFilter (TwitterStreamFilter filter)
{
this.filter = filter;
SetFiltered(filter != null);
}
/*
* SetUseQueue(bool enabled)
*
* Creates the MessageQueue if one doesn't already exist
* with messagePath endpoint
*
*/
public void SetUseQueue (bool enabled)
{
if (useMessageQueue != enabled) {
if (MessageQueue.Exists (messagePath)) {
queue = new MessageQueue (messagePath);
} else {
queue = MessageQueue.Create (messagePath);
}
useMessageQueue = enabled;
}
}
/* StartAsyncStream
*
* If useMessageQueue == true, pipes all JSON messages
* to MessageQueue
*
* If useMessageQueue == false, pipes all JSON messages to
* thread-safe queue
*
*
*/
public void StartAsyncStream ()
{
if (!useMessageQueue) {
if (backgroundThread != null) {
if (backgroundThread.IsAlive) {
Console.WriteLine ("Stream already started." +
"Close other stream before continuing.");
}
}
}
PrepareRequest ();
backgroundThread = new Thread (new ThreadStart (ProcessStream));
backgroundThread.Start ();
}
/*
* IsStreamRunning
*
* returns whether or not background thread is currently running
*/
public bool IsStreamRunning ()
{
if (backgroundThread != null) {
return (backgroundThread.IsAlive);
} else {
return false;
}
}
public void StopAsyncStream ()
{
if (backgroundThread != null) {
if (backgroundThread.IsAlive) {
abortFlag = true;
}
}
}
private void PrepareRequest ()
{
//Connect
webRequest = (HttpWebRequest)WebRequest.Create (streamUrl);
webRequest.Credentials = new NetworkCredential (username, password);
webRequest.Timeout = -1;
if (filter != null) {
string postParams = filter.ToString ();
if (postParams.Length > 0) {
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
if (debugging) {
Console.WriteLine (postParams);
}
byte[] _twitterTrack = defaultEncoding.GetBytes (postParams);
webRequest.ContentLength = _twitterTrack.Length;
Stream _twitterPost = webRequest.GetRequestStream ();
_twitterPost.Write (_twitterTrack, 0, _twitterTrack.Length);
_twitterPost.Close ();
}
}
}
/*
* GetBlockingNextStatus
* returns next twitter status processed from message
*
* NOTE: this method will block until next status
* is received
*
* Public Stream also returns deleted status, and
* these are still processed as status, so most fields
* will be null, but the object won't be null.
*
* TODO: implement a timeout so we don't block forever
*/
public Status GetBlockingNextStatus ()
{
Status status;
string message;
// check if there are any messages
message = jsonQueue.RemoveItem ();
// process message
status = MessageProcess (message);
//Console.WriteLine ("Status received");
return status;
}
public bool IsStatusAvailable()
{
return jsonQueue.IsItemAvailable();
}
/*
* ProcessStream
*
* Starts WebRequest and opens a stream for the response
* Implements backoff for HTTP errors and Network errors
*
* If MessageQueue is used, pipes all JSON messages to MessageQueue
* else pipes all JSON to thread-safe queue
*/
private void ProcessStream ()
{
int wait = 250;
string jsonText = "";
try {
while (!abortFlag) {
try {
// perform the request
webResponse = (HttpWebResponse)webRequest.GetResponse ();
responseStream = new StreamReader (webResponse.GetResponseStream (), defaultEncoding);
if (debugging) {
Console.WriteLine ("Twitter stream started");
}
//Read the stream.
while (!abortFlag) {
jsonText = responseStream.ReadLine ();
// post the message to the endpoint
if (useMessageQueue) {
Message message = new Message (jsonText);
queue.Send (message);
} else {
jsonQueue.AddItem (jsonText);
}
//Success
wait = 250;
//Write Status
if (debugging) {
Console.WriteLine ("Stream:");
Console.Write (jsonText);
}
}
} catch (WebException ex) {
Console.WriteLine (ex.Message);
Console.WriteLine (ex.StackTrace);
logger.append (ex.Message, Logger.LogLevel.ERROR);
if (ex.Status == WebExceptionStatus.ProtocolError) {
//-- From Twitter Docs --
//When a HTTP error (> 200) is returned, back off exponentially.
//Perhaps start with a 10 second wait, double on each subsequent failure,
//and finally cap the wait at 240 seconds.
//Exponential Backoff
if (wait < 10000) {
wait = 10000;
} else {
if (wait < 240000) {
wait = wait * 2;
}
}
} else {
//-- From Twitter Docs --
//When a network error (TCP/IP level) is encountered, back off linearly.
//Perhaps start at 250 milliseconds and cap at 16 seconds.
//Linear Backoff
if (wait < 16000) {
wait += 250;
}
}
} catch (Exception ex) {
Console.WriteLine (ex.Message);
Console.WriteLine (ex.StackTrace);
logger.append (ex.Message, Logger.LogLevel.ERROR);
if (webRequest != null) {
webRequest.Abort ();
}
if (responseStream != null) {
responseStream.Close ();
responseStream = null;
}
if (webResponse != null) {
webResponse.Close ();
webResponse = null;
}
Console.WriteLine ("Waiting: " + wait);
Thread.Sleep (wait);
}
}
} catch (Exception ex) {
Console.WriteLine (ex.Message);
Console.WriteLine (ex.StackTrace);
logger.append (ex.Message, Logger.LogLevel.ERROR);
}
abortFlag = false;
if (debugging) {
Console.WriteLine ("Thread finished");
}
}
/*
* QueueRead
*
* Prints the next JSON message stored in
* MessageQueue
*
* If MessageQueue is not used, this method won't do anything
*
*/
public void QueueRead ()
{
MessageQueue q;
string multiThread = ConfigurationManager.AppSettings ["multithread"];
Logger logger = new Logger ();
try {
if (MessageQueue.Exists (messagePath)) {
q = new MessageQueue (messagePath);
} else {
Console.WriteLine ("Queue does not exists.");
return;
}
while (true) {
Message message;
try {
message = q.Receive ();
message.Formatter =
new XmlMessageFormatter (new String[] { "System.String" });
if (multiThread == "true") {
ThreadPool.QueueUserWorkItem (MessageProcess, message);
} else {
MessageProcess (message);
}
} catch {
continue;
}
}
} catch (Exception ex) {
Console.WriteLine (ex.Message);
logger.append (ex.Message, Logger.LogLevel.ERROR);
}
}
private Status MessageProcess (string message)
{
Status status = new Status ();
Logger logger = new Logger ();
DataContractJsonSerializer json = new DataContractJsonSerializer (status.GetType ());
try {
byte[] byteArray = Encoding.UTF8.GetBytes (message);
MemoryStream stream = new MemoryStream (byteArray);
//TODO: Check for multiple objects.
status = json.ReadObject (stream) as Status;
if (debugging) {
Console.WriteLine ("MessageProcess:");
Console.WriteLine (message);
}
} catch (Exception ex) {
Console.WriteLine (ex.Message);
Console.WriteLine (ex.StackTrace);
logger.append (ex.Message, Logger.LogLevel.ERROR);
}
return status;
}
private void MessageProcess (object objMessage)
{
Status status = new Status ();
Logger logger = new Logger ();
DataContractJsonSerializer json = new DataContractJsonSerializer (status.GetType ());
try {
Message message = objMessage as Message;
byte[] byteArray = Encoding.UTF8.GetBytes (message.Body.ToString ());
MemoryStream stream = new MemoryStream (byteArray);
//TODO: Check for multiple objects.
status = json.ReadObject (stream) as Status;
if (debugging) {
Console.WriteLine ("MessageProcess:");
Console.WriteLine (message.Body.ToString ());
}
} catch (Exception ex) {
Console.WriteLine (ex.Message);
Console.WriteLine (ex.StackTrace);
logger.append (ex.Message, Logger.LogLevel.ERROR);
}
}
}
}