-
Notifications
You must be signed in to change notification settings - Fork 285
/
Pubnub.cs
704 lines (652 loc) · 23 KB
/
Pubnub.cs
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using Newtonsoft.Json.Linq;
using System.Net;
using Newtonsoft.Json;
using System.IO;
using System.IO.Compression;
namespace csharp_webApp
{
public class Channel_status
{
public string channel;
public bool connected, first;
}
public class pubnub
{
private string ORIGIN = "pubsub.pubnub.com";
private string PUBLISH_KEY = "";
private string SUBSCRIBE_KEY = "";
private string SECRET_KEY = "";
private string CIPHER_KEY = "";
private bool SSL = false;
private ManualResetEvent webRequestDone;
volatile private bool abort;
public delegate bool Procedure(object message);
private List<Channel_status> subscriptions;
/**
* PubNub 3.1
*
* Prepare PubNub Class State.
*
* @param string Publish Key.
* @param string Subscribe Key.
* @param string Secret Key.
* @param string Cipher Key.
* @param bool SSL Enabled.
*/
public pubnub(
string publish_key,
string subscribe_key,
string secret_key,
string cipher_key,
bool ssl_on
)
{
this.init(publish_key, subscribe_key, secret_key, cipher_key, ssl_on);
}
/**
* PubNub 3.0 Compatibility
*
* Prepare PubNub Class State.
*
* @param string Publish Key.
* @param string Subscribe Key.
* @param string Secret Key.
* @param bool SSL Enabled.
*/
public pubnub(
string publish_key,
string subscribe_key,
string secret_key,
bool ssl_on
)
{
this.init(publish_key, subscribe_key, secret_key, "", ssl_on);
}
/**
* PubNub 2.0 Compatibility
*
* Prepare PubNub Class State.
*
* @param string Publish Key.
* @param string Subscribe Key.
*/
public pubnub(
string publish_key,
string subscribe_key
)
{
this.init(publish_key, subscribe_key, "", "", false);
}
/**
* PubNub 3.0 without SSL
*
* Prepare PubNub Class State.
*
* @param string Publish Key.
* @param string Subscribe Key.
* @param string Secret Key.
*/
public pubnub(
string publish_key,
string subscribe_key,
string secret_key
)
{
this.init(publish_key, subscribe_key, secret_key, "", false);
}
/**
* Init
*
* Prepare PubNub Class State.
*
* @param string Publish Key.
* @param string Subscribe Key.
* @param string Secret Key.
* @param string Cipher Key.
* @param bool SSL Enabled.
*/
public void init(
string publish_key,
string subscribe_key,
string secret_key,
string cipher_key,
bool ssl_on
)
{
this.PUBLISH_KEY = publish_key;
this.SUBSCRIBE_KEY = subscribe_key;
this.SECRET_KEY = secret_key;
this.CIPHER_KEY = cipher_key;
this.SSL = ssl_on;
// SSL On?
if (this.SSL)
{
this.ORIGIN = "https://" + this.ORIGIN;
}
else
{
this.ORIGIN = "http://" + this.ORIGIN;
}
webRequestDone = new ManualResetEvent(true);
}
/**
* Publish
*
* Send a message to a channel.
*
* @param Dictionary<string, object> args
* args is string channel name and object message
* @return List<object> info.
*/
public List<object> Publish(Dictionary<string, object> args)
{
string channel = args["channel"].ToString();
object message = args["message"];
clsPubnubCrypto pc = new clsPubnubCrypto(this.CIPHER_KEY);
if (this.CIPHER_KEY.Length > 0)
{
if (message.GetType() == typeof(string))
{
message = pc.encrypt(message.ToString());
message = "\"" + message.ToString() + "\"";
}
else if (message.GetType() == typeof(JArray))
{
message = pc.encrypt((JArray)message);
}
else if (message.GetType() == typeof(JObject))
{
message = pc.encrypt((JObject)message);
}
}
else
{
message = JsonConvert.SerializeObject(message);
}
// Generate String to Sign
string signature = "0";
if (this.SECRET_KEY.Length > 0)
{
StringBuilder string_to_sign = new StringBuilder();
string_to_sign
.Append(this.PUBLISH_KEY)
.Append('/')
.Append(this.SUBSCRIBE_KEY)
.Append('/')
.Append(this.SECRET_KEY)
.Append('/')
.Append(channel)
.Append('/')
.Append(message);
// Sign Message
signature = getHMACSHA256(string_to_sign.ToString());
}
// Build URL
List<string> url = new List<string>();
url.Add("publish");
url.Add(this.PUBLISH_KEY);
url.Add(this.SUBSCRIBE_KEY);
url.Add(signature);
url.Add(channel);
url.Add("0");
url.Add(message.ToString());
// Return JSONArray
return _request(url);
}
/**
* Subscribe
*
* This function is NON BLOCKING.
* Listen for a message on a channel.
*
* @param Dictionary<string,object> args.
* args contains channel name and Procedure function callback.
*/
public void Subscribe(Dictionary<string, object> args)
{
args.Add("timestamp", 0);
this._subscribe(args);
}
/**
* _subscribe - Private Interface
*
* @param Dictionary<string, object> args
* args is channel name and Procedure function callback and timetoken
*
*/
private void _subscribe(Dictionary<string, object> args)
{
bool is_disconnect = false;
bool is_alreadyConnect = false;
Procedure callback = null, connect_cb, disconnect_cb, reconnect_cb, error_cb;
clsPubnubCrypto pc = new clsPubnubCrypto(this.CIPHER_KEY);
object timetoken = args["timestamp"];
string channel = args["channel"].ToString();
// Validate Arguments
if (args["callback"] != null)
{
callback = (Procedure)args["callback"];
}
else
{
Console.WriteLine("Invalid Callback.");
}
if(args.ContainsKey("connect_cb") && args["connect_cb"] != null)
connect_cb = (Procedure)args["connect_cb"];
else
connect_cb = new Procedure(doNothing);
if (args.ContainsKey("disconnect_cb") && args["disconnect_cb"] != null)
disconnect_cb = (Procedure)args["disconnect_cb"];
else
disconnect_cb = new Procedure(doNothing);
if (args.ContainsKey("reconnect_cb") && args["reconnect_cb"] != null)
reconnect_cb = (Procedure)args["reconnect_cb"];
else
reconnect_cb = new Procedure(doNothing);
if (args.ContainsKey("error_cb") && args["error_cb"] != null)
error_cb = (Procedure)args["error_cb"];
else
error_cb = (Procedure)args["callback"];
if (channel == null || channel =="")
{
error_cb("Invalid Channel.");
return;
}
// Ensure Single Connection
if (subscriptions != null && subscriptions.Count > 0)
{
bool channel_exist = false;
foreach (Channel_status cs in subscriptions)
{
if (cs.channel == channel)
{
channel_exist = true;
if (!cs.connected)
{
cs.connected = true;
}
else
is_alreadyConnect = true;
break;
}
}
if (!channel_exist)
{
Channel_status cs = new Channel_status();
cs.channel = channel;
cs.connected = true;
subscriptions.Add(cs);
}
else if (is_alreadyConnect)
{
error_cb("Already Connected");
return;
}
}
else
{
// New Channel
Channel_status cs = new Channel_status();
cs.channel = channel;
cs.connected = true;
subscriptions = new List<Channel_status>();
subscriptions.Add(cs);
}
bool is_reconnected = false;
// Begin Recusive Subscribe
while (true)
{
// Begin Recursive Subscribe
try
{
// Build URL
List<string> url = new List<string>();
url.Add("subscribe");
url.Add(this.SUBSCRIBE_KEY);
url.Add(channel);
url.Add("0");
url.Add(timetoken.ToString());
// Stop Connection?
is_disconnect = false;
foreach (Channel_status cs in subscriptions)
{
if (cs.channel == channel)
{
if (!cs.connected)
{
disconnect_cb("Disconnected to channel : " + channel);
is_disconnect = true;
break;
}
}
}
if (is_disconnect)
return;
// Wait for Message
List<object> response = _request(url);
// Stop Connection?
foreach (Channel_status cs in subscriptions)
{
if (cs.channel == channel)
{
if (!cs.connected)
{
disconnect_cb("Disconnected to channel : " + channel);
is_disconnect = true;
break;
}
}
}
if (is_disconnect)
return;
// Problem?
if (response == null || response[1].ToString() == "0")
{
for (int i = 0; i < subscriptions.Count(); i++)
{
Channel_status cs = subscriptions[i];
if (cs.channel == channel)
{
subscriptions.RemoveAt(i);
disconnect_cb("Disconnected to channel : " + channel);
}
}
// Ensure Connected (Call Time Function)
while (true)
{
string time_token = Time().ToString();
if (time_token == "0")
{
// Reconnect Callback
reconnect_cb("Reconnecting to channel : " + channel);
Thread.Sleep(5000);
}
else
{
is_reconnected = true;
break;
}
}
if (is_reconnected)
{
break;
}
}
else
{
foreach (Channel_status cs in subscriptions)
{
if (cs.channel == channel)
{
// Connect Callback
if (!cs.first)
{
cs.first = true;
connect_cb("Connected to channel : " + channel);
break;
}
}
}
}
// Update TimeToken
if (response[1].ToString().Length > 0)
timetoken = (object)response[1];
// Run user Callback and Reconnect if user permits.
object message = "";
JArray val = (JArray)response[0];
for (int i = 0; i < val.Count; i++)
{
if (this.CIPHER_KEY.Length > 0)
{
if (val[i].Type == JTokenType.String)
{
message = pc.decrypt((string)val[i]);
}
else if (val[i].Type == JTokenType.Object)
{
message = pc.decrypt((JObject)val[i]);
}
else if (val[i].Type == JTokenType.Array)
{
message = pc.decrypt((JArray)val[i]);
}
}
else
{
message = val[i];
}
if (!callback(message)) return;
}
}
catch
{
System.Threading.Thread.Sleep(1000);
}
}
if (is_reconnected)
{
// Reconnect Callback
args["channel"] = channel;
args["callback"] = callback;
args["timestamp"] = timetoken;
this._subscribe(args);
}
}
/**
* Request URL
*
* @param List<string> request of url directories.
* @return List<object> from JSON response.
*/
private List<object> _request(List<string> url_components)
{
try
{
string temp = null;
int count = 0;
byte[] buf = new byte[8192];
StringBuilder url = new StringBuilder();
StringBuilder sb = new StringBuilder();
// Add Origin To The Request
url.Append(this.ORIGIN);
// Generate URL with UTF-8 Encoding
foreach (string url_bit in url_components)
{
url.Append("/");
url.Append(_encodeURIcomponent(url_bit));
}
// Create Request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url.ToString());
// Set Timeout
request.Timeout = 310000;
request.ReadWriteTimeout = 310000;
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip");
request.Headers.Add("V", "3.1");
request.UserAgent = "C#-IIS";
webRequestDone.Reset();
IAsyncResult asyncResult = request.BeginGetResponse(new AsyncCallback(requestCallBack), null);
webRequestDone.WaitOne();
if (abort)
{
return new List<object>();
}
// Receive Response
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
// Read
using (Stream stream = response.GetResponseStream())
{
Stream resStream = stream;
if (response.ContentEncoding.ToLower().Contains("gzip"))
{
resStream = new GZipStream(stream, CompressionMode.Decompress);
}
else
{
resStream = stream;
}
do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
temp = Encoding.UTF8.GetString(buf, 0, count);
sb.Append(temp);
}
} while (count > 0);
}
// Parse Response
string message = sb.ToString();
return JsonConvert.DeserializeObject<List<object>>(message);
}
catch (Exception)
{
List<object> error = new List<object>();
if (url_components[0] == "time")
{
error.Add("0");
}
else if (url_components[0] == "history")
{
error.Add("Error: Failed JSONP HTTP Request.");
}
else if (url_components[0] == "publish")
{
error.Add("0");
error.Add("Error: Failed JSONP HTTP Request.");
}
else if (url_components[0] == "subscribe")
{
error.Add("0");
error.Add("0");
}
return error;
}
}
private void requestCallBack(IAsyncResult result)
{
// release thread block
webRequestDone.Set();
}
public void Abort()
{
abort = true;
webRequestDone.Set();
}
/**
* Time
*
* Timestamp from PubNub Cloud.
*
* @return object timestamp.
*/
public object Time()
{
List<string> url = new List<string>();
url.Add("time");
url.Add("0");
List<object> response = _request(url);
return response[0];
}
/**
* History
*
* Load history from a channel.
*
* @param Dictionary<string, string> args
* args is channel name and int limit history count response.
* @return List<object> of history.
*/
public List<object> History(Dictionary<string, string> args)
{
string channel = args["channel"];
int limit = Convert.ToInt32(args["limit"]);
List<string> url = new List<string>();
url.Add("history");
url.Add(this.SUBSCRIBE_KEY);
url.Add(channel);
url.Add("0");
url.Add(limit.ToString());
if (this.CIPHER_KEY.Length > 0)
{
clsPubnubCrypto pc = new clsPubnubCrypto(this.CIPHER_KEY);
return pc.decrypt(_request(url));
}
else
{
return _request(url);
}
}
/**
* Unsubscribe
*
* Unsubscribe/Disconnect to channel.
*
* @param Dictionary<String, Object> containing channel name.
*/
public void Unsubscribe(Dictionary<String, Object> args)
{
String channel = args["channel"].ToString();
foreach (Channel_status cs in subscriptions)
{
if (cs.channel == channel && cs.connected)
{
cs.connected = false;
cs.first = false;
break;
}
}
}
private string _encodeURIcomponent(string s)
{
StringBuilder o = new StringBuilder();
foreach (char ch in s.ToCharArray())
{
if (isUnsafe(ch))
{
o.Append('%');
o.Append(toHex(ch / 16));
o.Append(toHex(ch % 16));
}
else o.Append(ch);
}
return o.ToString();
}
private char toHex(int ch)
{
return (char)(ch < 10 ? '0' + ch : 'A' + ch - 10);
}
private bool isUnsafe(char ch)
{
return " ~`!@#$%^&*()+=[]\\{}|;':\",./<>?".IndexOf(ch) >= 0;
}
private static string getHMACSHA256(string text)
{
HMACSHA256 sha256 = new HMACSHA256();
byte[] data = Encoding.Default.GetBytes(text);
byte[] hash = sha256.ComputeHash(data);
string hexaHash = "";
foreach (byte b in hash) hexaHash += String.Format("{0:x2}", b);
return hexaHash;
}
/**
* UUID
* @return string unique identifier
*/
public string UUID()
{
return Guid.NewGuid().ToString();
}
private bool doNothing(object result)
{
// do nothing
return false;
}
}
}