forked from DarkActive/PVPNetConnect
/
PVPNetConnection.cs
1545 lines (1327 loc) · 55.3 KB
/
PVPNetConnection.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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* A very basic RTMPS client
*
* @author Gabriel Van Eyck
*/
/*/////////////////////////////////////////////////////////////////////////////////
//
//Ported to C# by Ryan A. LaSarre
//
/*/////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Web.Script.Serialization;
using PVPNetConnect.Assets;
using PVPNetConnect.RiotObjects;
using PVPNetConnect.RiotObjects.Summoner;
using PVPNetConnect.RiotObjects.Leagues;
using PVPNetConnect.RiotObjects.Statistics;
using PVPNetConnect.RiotObjects.Client;
using PVPNetConnect.RiotObjects.Game;
namespace PVPNetConnect
{
/// <summary>
/// PVPNetConnection class, main class used to connect to Riot Servers and perform calls and receive data.
/// </summary>
public class PVPNetConnection
{
#region Member Declarations
/// <summary>
/// The boolean check for connection being active.
/// </summary>
private bool isConnected = false;
/// <summary>
/// The client
/// </summary>
private TcpClient client;
/// <summary>
/// The SSL stream
/// </summary>
private SafeSslStream sslStream;
/// <summary>
/// The ip address
/// </summary>
private string ipAddress;
/// <summary>
/// The auth token
/// </summary>
private string authToken;
/// <summary>
/// The account ID
/// </summary>
private int accountID;
/// <summary>
/// The session token
/// </summary>
private string sessionToken;
/// <summary>
/// The DS id
/// </summary>
private string DSId;
/* Initial Login Information */
/// <summary>
/// The user
/// </summary>
private string user;
/// <summary>
/// The password
/// </summary>
private string password;
/// <summary>
/// The server
/// </summary>
private string server;
/// <summary>
/// The login queue
/// </summary>
private string loginQueue;
/// <summary>
/// The locale
/// </summary>
private string locale;
/// <summary>
/// The client version
/// </summary>
private string clientVersion;
/* Garena information */
/// <summary>
/// The use garena
/// </summary>
private bool useGarena = false;
/// <summary>
/// The garena token
/// </summary>
private string garenaToken;
/// <summary>
/// The user ID
/// </summary>
private string userID;
/* Invoke Variables */
/// <summary>
/// The rand
/// </summary>
private Random rand = new Random();
/// <summary>
/// The serializer
/// </summary>
private JavaScriptSerializer serializer = new JavaScriptSerializer();
/// <summary>
/// The invoke ID
/// </summary>
private int invokeID = 2;
/// <summary>
/// The pending invokes
/// </summary>
private List<int> pendingInvokes = new List<int>();
/// <summary>
/// The results
/// </summary>
private Dictionary<int, TypedObject> results = new Dictionary<int, TypedObject>();
/// <summary>
/// The callbacks
/// </summary>
private Dictionary<int, RiotGamesObject> callbacks = new Dictionary<int, RiotGamesObject>();
/// <summary>
/// The decode thread
/// </summary>
private Thread decodeThread;
/// <summary>
/// The heartbeat count
/// </summary>
private int heartbeatCount = 1;
/// <summary>
/// The heartbeat thread
/// </summary>
private Thread heartbeatThread;
#endregion
#region Event Handlers
/// <summary>
/// Handler to call when [on connect].
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
public delegate void OnConnectHandler(object sender, EventArgs e);
/// <summary>
/// Occurs when [on connect].
/// </summary>
public event OnConnectHandler OnConnect;
/// <summary>
/// Handler to call when [on login queue update].
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="positionInLine">The position in line.</param>
public delegate void OnLoginQueueUpdateHandler(object sender, int positionInLine);
/// <summary>
/// Occurs when [on login queue update].
/// </summary>
public event OnLoginQueueUpdateHandler OnLoginQueueUpdate;
/// <summary>
/// Handler to call when [on login].
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="username">The username.</param>
/// <param name="ipAddress">The ip address.</param>
public delegate void OnLoginHandler(object sender, string username, string ipAddress);
/// <summary>
/// Occurs when [on login].
/// </summary>
public event OnLoginHandler OnLogin;
/// <summary>
/// Handler to call when [on disconnect].
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
public delegate void OnDisconnectHandler(object sender, EventArgs e);
/// <summary>
/// Occurs when [on disconnect].
/// </summary>
public event OnDisconnectHandler OnDisconnect;
/// <summary>
/// Handler to call when [on error].
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="error">The error.</param>
public delegate void OnErrorHandler(object sender, Error error);
/// <summary>
/// Occurs when [on error].
/// </summary>
public event OnErrorHandler OnError;
#endregion
#region Connect, Login, and Heartbeat Methods
/// <summary>
/// Connects the specified user.
/// </summary>
/// <param name="user">The user.</param>
/// <param name="password">The password.</param>
/// <param name="region">The region.</param>
/// <param name="clientVersion">The client version.</param>
public void Connect(string user, string password, Region region, string clientVersion)
{
if (!isConnected)
{
this.user = user;
this.password = password;
this.clientVersion = clientVersion;
if (region == Region.NA)
{
this.server = "prod.na1.lol.riotgames.com";
this.loginQueue = "https://lq.na1.lol.riotgames.com/";
this.locale = "en_US";
}
else if (region == Region.EUW)
{
this.server = "prod.eu.lol.riotgames.com";
this.loginQueue = "https://lq.eu.lol.riotgames.com/";
this.locale = "en_GB";
}
else if (region == Region.EUN)
{
this.server = "prod.eun1.lol.riotgames.com";
this.loginQueue = "https://lq.eun1.lol.riotgames.com/";
this.locale = "en_GB";
}
else if (region == Region.KR)
{
this.server = "prod.kr.lol.riotgames.com";
this.loginQueue = "https://lq.kr.lol.riotgames.com/";
this.locale = "ko_KR";
}
else if (region == Region.BR)
{
this.server = "prod.br.lol.riotgames.com";
this.loginQueue = "https://lq.br.lol.riotgames.com/";
this.locale = "pt_BR";
}
else if (region == Region.TR)
{
this.server = "prod.tr.lol.riotgames.com";
this.loginQueue = "https://lq.tr.lol.riotgames.com/";
this.locale = "pt_BR";
}
else if (region == Region.PBE)
{
this.server = "prod.pbe1.lol.riotgames.com";
this.loginQueue = "https://lq.pbe1.lol.riotgames.com/";
this.locale = "en_US";
}
else if (region == Region.SG || region == Region.MY || region == Region.SGMY)
{
this.server = "prod.lol.garenanow.com";
this.loginQueue = "https://lq.lol.garenanow.com/";
this.locale = "en_US";
this.useGarena = true;
}
else if (region == Region.TW)
{
this.server = "prodtw.lol.garenanow.com";
this.loginQueue = "https://loginqueuetw.lol.garenanow.com/";
this.locale = "en_US";
this.useGarena = true;
}
else if (region == Region.TH)
{
this.server = "prodth.lol.garenanow.com";
this.loginQueue = "https://lqth.lol.garenanow.com/";
this.locale = "en_US";
this.useGarena = true;
}
else if (region == Region.PH)
{
this.server = "prodph.lol.garenanow.com";
this.loginQueue = "https://storeph.lol.garenanow.com/";
this.locale = "en_US";
this.useGarena = true;
}
else if (region == Region.VN)
{
this.server = "prodvn.lol.garenanow.com";
this.loginQueue = "https://lqvn.lol.garenanow.com/";
this.locale = "en_US";
this.useGarena = true;
}
else
{
Error("Unknown Region: " + region, ErrorType.General);
Disconnect();
return;
}
ThreadPool.QueueUserWorkItem(new WaitCallback(Connect), this);
}
}
private static void Connect(object sender)
{
PVPNetConnection pvpnet = (PVPNetConnection)sender;
//Sets up our sslStream to riots servers
try
{
pvpnet.client = new TcpClient(pvpnet.server, 2099);
}
catch
{
pvpnet.Error("Riots servers are currently unabailable.", ErrorType.AuthKey);
pvpnet.Disconnect();
return;
}
//Check for riot webserver status
//along with gettin out Auth Key that we need for the login process.
if (pvpnet.useGarena)
if (!pvpnet.GetGarenaToken())
return;
if (!pvpnet.GetAuthKey())
return;
if (!pvpnet.GetIpAddress())
return;
// TODO: Added SslStream.Syncrhonized() for thread safe.
pvpnet.sslStream = new SafeSslStream(new SslStream(SslStream.Synchronized(pvpnet.client.GetStream()), false, pvpnet.AcceptAllCertificates));
var ar = pvpnet.sslStream.BeginAuthenticateAsClient(pvpnet.server, null, null);
using (ar.AsyncWaitHandle)
{
if (ar.AsyncWaitHandle.WaitOne(-1))
{
pvpnet.sslStream.EndAuthenticateAsClient(ar);
}
}
if (!pvpnet.Handshake())
return;
ThreadPool.QueueUserWorkItem(new WaitCallback(BeginReceive), pvpnet);
if (!pvpnet.SendConnect())
return;
if (!pvpnet.Login())
return;
//ThreadPool.QueueUserWorkItem(new WaitCallback(StartHeartbeat), pvpnet);
}
/// <summary>
/// Accepts all certificates.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="certificate">The certificate.</param>
/// <param name="chain">The chain.</param>
/// <param name="sslPolicyErrors">The SSL policy errors.</param>
/// <returns>Returns true, meaning all certificates accepted.</returns>
private bool AcceptAllCertificates(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
/// <summary>
/// Gets the garena token.
/// </summary>
/// <returns>Returns true if successful, false if not.</returns>
private bool GetGarenaToken()
{
// temp fix, to suppress warnings
userID = "0";
garenaToken = "0";
/*
try
{
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
//GET OUR USER ID
List<byte> userIdRequestBytes = new List<byte>();
byte[] junk = new byte[] { 0x49, 0x00, 0x00, 0x00, 0x10, 0x01, 0x00, 0x79, 0x2f };
userIdRequestBytes.AddRange(junk);
userIdRequestBytes.AddRange(encoding.GetBytes(user));
for (int i = 0; i < 16; i++)
userIdRequestBytes.Add(0x00);
System.Security.Cryptography.MD5 md5Cryp = System.Security.Cryptography.MD5.Create();
byte[] inputBytes = encoding.GetBytes(password);
byte[] md5 = md5Cryp.ComputeHash(inputBytes);
foreach (byte b in md5)
userIdRequestBytes.AddRange(encoding.GetBytes(String.Format("%02x", b)));
userIdRequestBytes.Add(0x00);
userIdRequestBytes.Add(0x01);
junk = new byte[] { 0xD4, 0xAE, 0x52, 0xC0, 0x2E, 0xBA, 0x72, 0x03 };
userIdRequestBytes.AddRange(junk);
int timestamp = (int)(DateTime.UtcNow.TimeOfDay.TotalMilliseconds / 1000);
for (int i = 0; i < 4; i++)
userIdRequestBytes.Add((byte)((timestamp >> (8 * i)) & 0xFF));
userIdRequestBytes.Add(0x00);
userIdRequestBytes.AddRange(encoding.GetBytes("intl"));
userIdRequestBytes.Add(0x00);
byte[] userIdBytes = userIdRequestBytes.ToArray();
TcpClient client = new TcpClient("203.117.158.170", 9100);
client.GetStream().Write(userIdBytes, 0, userIdBytes.Length);
client.GetStream().Flush();
int id = 0;
for (int i = 0; i < 4; i++)
id += client.GetStream().ReadByte() * (1 << (8 * i));
userID = Convert.ToString(id);
//GET TOKEN
List<byte> tokenRequestBytes = new List<byte>();
junk = new byte[] { 0x32, 0x00, 0x00, 0x00, 0x01, 0x03, 0x80, 0x00, 0x00 };
tokenRequestBytes.AddRange(junk);
tokenRequestBytes.AddRange(encoding.GetBytes(user));
tokenRequestBytes.Add(0x00);
foreach (byte b in md5)
tokenRequestBytes.AddRange(encoding.GetBytes(String.Format("%02x", b)));
tokenRequestBytes.Add(0x00);
tokenRequestBytes.Add(0x00);
tokenRequestBytes.Add(0x00);
byte[] tokenBytes = tokenRequestBytes.ToArray();
client = new TcpClient("lol.auth.garenanow.com", 12000);
client.GetStream().Write(tokenBytes, 0, tokenBytes.Length);
client.GetStream().Flush();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++)
client.GetStream().ReadByte();
int c;
while ((c = client.GetStream().ReadByte()) != 0)
sb.Append((char)c);
garenaToken = sb.ToString();
client.Close();
return true;
}
catch
{
Error("Unable to acquire garena token", ErrorType.Login);
Disconnect();
return false;
}
*/
Error("Garena Servers are not yet supported", ErrorType.Login);
Disconnect();
return false;
}
/// <summary>
/// Gets the auth key.
/// </summary>
/// <returns>Returns true if successful, false if not.</returns>
private bool GetAuthKey()
{
try
{
StringBuilder sb = new StringBuilder();
string payload = "user=" + user + ",password=" + password;
string query = "payload=" + payload;
if (useGarena)
payload = garenaToken;
WebRequest con = WebRequest.Create(loginQueue + "login-queue/rest/queue/authenticate");
con.Method = "POST";
Stream outputStream = con.GetRequestStream();
outputStream.Write(Encoding.ASCII.GetBytes(query), 0, Encoding.ASCII.GetByteCount(query));
WebResponse webresponse = con.GetResponse();
Stream inputStream = webresponse.GetResponseStream();
int c;
while ((c = inputStream.ReadByte()) != -1)
sb.Append((char)c);
TypedObject result = serializer.Deserialize<TypedObject>(sb.ToString());
outputStream.Close();
inputStream.Close();
con.Abort();
if (!result.ContainsKey("token"))
{
int node = (int)result.GetInt("node");
string champ = result.GetString("champ");
int rate = (int)result.GetInt("rate");
int delay = (int)result.GetInt("delay");
int id = 0;
int cur = 0;
object[] tickers = result.GetArray("tickers");
foreach (object o in tickers)
{
Dictionary<string, object> to = (Dictionary<string, object>)o;
int tnode = (int)to["node"];
if (tnode != node)
continue;
id = (int)to["id"];
cur = (int)to["current"];
break;
}
while (id - cur > rate)
{
sb.Clear();
OnLoginQueueUpdate(this, id - cur);
Thread.Sleep(delay);
con = WebRequest.Create(loginQueue + "login-queue/rest/queue/ticker/" + champ);
con.Method = "GET";
webresponse = con.GetResponse();
inputStream = webresponse.GetResponseStream();
int d;
while ((d = inputStream.ReadByte()) != -1)
sb.Append((char)d);
result = serializer.Deserialize<TypedObject>(sb.ToString());
inputStream.Close();
con.Abort();
if (result == null)
continue;
cur = HexToInt(result.GetString(node.ToString()));
}
while (sb.ToString() == null || !result.ContainsKey("token"))
{
try
{
sb.Clear();
if (id - cur < 0)
OnLoginQueueUpdate(this, 0);
else
OnLoginQueueUpdate(this, id - cur);
Thread.Sleep(delay / 10);
con = WebRequest.Create(loginQueue + "login-queue/rest/queue/authToken/" + user.ToLower());
con.Method = "GET";
webresponse = con.GetResponse();
inputStream = webresponse.GetResponseStream();
int f;
while ((f = inputStream.ReadByte()) != -1)
sb.Append((char)f);
result = serializer.Deserialize<TypedObject>(sb.ToString());
inputStream.Close();
con.Abort();
}
catch
{
}
}
}
OnLoginQueueUpdate(this, 0);
authToken = result.GetString("token");
return true;
}
catch (Exception e)
{
if (e.Message == "The remote name could not be resolved: '" + loginQueue + "'")
{
Error("Please make sure you are connected the internet!", ErrorType.AuthKey);
Disconnect();
}
else if (e.Message == "The remote server returned an error: (403) Forbidden.")
{
Error("Your username or password is incorrect!", ErrorType.Password);
Disconnect();
}
else
{
Error("Unable to get Auth Key \n" + e, ErrorType.AuthKey);
Disconnect();
}
return false;
}
}
/// <summary>
/// Hexes to int.
/// </summary>
/// <param name="hex">The hex number.</param>
/// <returns>Returns the integer converted from hex number.</returns>
private int HexToInt(string hex)
{
int total = 0;
for (int i = 0; i < hex.Length; i++)
{
char c = hex.ToCharArray()[i];
if (c >= '0' && c <= '9')
total = total * 16 + c - '0';
else
total = total * 16 + c - 'a' + 10;
}
return total;
}
/// <summary>
/// Gets the ip address.
/// </summary>
/// <returns>Returns true if successful, false if not.</returns>
private bool GetIpAddress()
{
try
{
StringBuilder sb = new StringBuilder();
WebRequest con = WebRequest.Create("http://ll.leagueoflegends.com/services/connection_info");
WebResponse response = con.GetResponse();
int c;
while ((c = response.GetResponseStream().ReadByte()) != -1)
sb.Append((char)c);
con.Abort();
TypedObject result = serializer.Deserialize<TypedObject>(sb.ToString());
ipAddress = result.GetString("ip_address");
return true;
}
catch (Exception e)
{
Error("Unable to connect to Riot Games web server \n" + e.Message, ErrorType.General);
Disconnect();
return false;
}
}
/// <summary>
/// Handshakes this instance.
/// </summary>
/// <returns>Returns true if successful, false if not.</returns>
private bool Handshake()
{
byte[] handshakePacket = new byte[1537];
rand.NextBytes(handshakePacket);
handshakePacket[0] = (byte)0x03;
sslStream.Write(handshakePacket);
byte S0 = (byte)sslStream.ReadByte();
if (S0 != 0x03)
{
Error("Server returned incorrect version in handshake: " + S0, ErrorType.Handshake);
Disconnect();
return false;
}
byte[] responsePacket = new byte[1536];
sslStream.Read(responsePacket, 0, 1536);
sslStream.Write(responsePacket);
// Wait for response and discard result
byte[] S2 = new byte[1536];
sslStream.Read(S2, 0, 1536);
// Validate handshake
bool valid = true;
for (int i = 8; i < 1536; i++)
{
if (handshakePacket[i + 1] != S2[i])
{
valid = false;
break;
}
}
if (!valid)
{
Error("Server returned invalid handshake", ErrorType.Handshake);
Disconnect();
return false;
}
return true;
}
/// <summary>
/// Sends the connection info to server.
/// </summary>
/// <returns>Returns true if successful, false if not.</returns>
private bool SendConnect()
{
Dictionary<string, object> paramaters = new Dictionary<string, object>();
paramaters.Add("app", "");
paramaters.Add("flashVer", "WIN 10,1,85,3");
paramaters.Add("swfUrl", "app:/mod_ser.dat");
paramaters.Add("tcUrl", "rtmps://" + server + ":" + 2099);
paramaters.Add("fpad", false);
paramaters.Add("capabilities", 239);
paramaters.Add("audioCodecs", 3191);
paramaters.Add("videoCodecs", 252);
paramaters.Add("videoFunction", 1);
paramaters.Add("pageUrl", null);
paramaters.Add("objectEncoding", 3);
RTMPSEncoder.startTime = (long)DateTime.Now.TimeOfDay.TotalMilliseconds;
byte[] connect = RTMPSEncoder.EncodeConnect(paramaters);
sslStream.Write(connect, 0, connect.Length);
while (!results.ContainsKey(1))
Thread.Sleep(10);
TypedObject result = results[1];
results.Remove(1);
if (result["result"].Equals("_error"))
{
Error(GetErrorMessage(result), ErrorType.Connect);
Disconnect();
return false;
}
DSId = result.GetTO("data").GetString("id");
isConnected = true;
if (OnConnect != null)
OnConnect(this, EventArgs.Empty);
return true;
}
/// <summary>
/// Begins login process to server.
/// </summary>
/// <returns>Returns true if successful, false if not.</returns>
private bool Login()
{
TypedObject result, body;
// Login 1
body = new TypedObject("com.riotgames.platform.login.AuthenticationCredentials");
body.Add("password", password);
body.Add("clientVersion", clientVersion);
body.Add("ipAddress", ipAddress);
body.Add("securityAnswer", null);
body.Add("locale", locale);
body.Add("domain", "lolclient.lol.riotgames.com");
body.Add("oldPassword", null);
body.Add("authToken", authToken);
if (useGarena)
{
body.Add("partnerCredentials", "8393 " + garenaToken);
body.Add("username", userID);
}
else
{
body.Add("partnerCredentials", null);
body.Add("username", user);
}
int id = Invoke("loginService", "login", new object[] { body });
result = GetResult(id);
if (result["result"].Equals("_error"))
{
Error(GetErrorMessage(result), ErrorType.Login);
Disconnect();
return false;
}
body = result.GetTO("data").GetTO("body");
sessionToken = body.GetString("token");
accountID = (int)body.GetTO("accountSummary").GetInt("accountId");
// Login 2
if (useGarena)
body = WrapBody(Convert.ToBase64String(Encoding.UTF8.GetBytes(userID + ":" + sessionToken)), "auth", 8);
else
body = WrapBody(Convert.ToBase64String(Encoding.UTF8.GetBytes(user + ":" + sessionToken)), "auth", 8);
body.type = "flex.messaging.messages.CommandMessage";
id = Invoke(body);
result = GetResult(id); // Read result (and discard)
// Subscribe to the necessary items
// bc
body = WrapBody(new object[] { new TypedObject() }, "messagingDestination", 0);
body.type = "flex.messaging.messages.CommandMessage";
TypedObject headers = body.GetTO("headers");
headers.Add("DSSubtopic", "bc");
headers.Remove("DSRequestTimeout");
body["clientID"] = "bc-" + accountID;
id = Invoke(body);
result = GetResult(id); // Read result and discard
// cn
body = WrapBody(new object[] { new TypedObject() }, "messagingDestination", 0);
body.type = "flex.messaging.messages.CommandMessage";
headers = body.GetTO("headers");
headers.Add("DSSubtopic", "cn-" + accountID);
headers.Remove("DSRequestTimeout");
body["clientID"] = "cn-" + accountID;
id = Invoke(body);
result = GetResult(id); // Read result and discard
// gn
body = WrapBody(new object[] { new TypedObject() }, "messagingDestination", 0);
body.type = "flex.messaging.messages.CommandMessage";
headers = body.GetTO("headers");
headers.Add("DSSubtopic", "gn-" + accountID);
headers.Remove("DSRequestTimeout");
body["clientID"] = "gn-" + accountID;
id = Invoke(body);
result = GetResult(id); // Read result and discard
if (OnLogin != null)
OnLogin(this, user, ipAddress);
return true;
}
/// <summary>
/// Gets the error message.
/// </summary>
/// <param name="message">The message.</param>
/// <returns>Returns the error message.</returns>
private string GetErrorMessage(TypedObject message)
{
// Works for clientVersion
return message.GetTO("data").GetTO("rootCause").GetString("message");
}
/// <summary>
/// Starts the heartbeat, and contiuously performs the heartbeat.
/// </summary>
private static void StartHeartbeat(object sender)
{
PVPNetConnection pvpnet = (PVPNetConnection)sender;
while (true)
{
try
{
long hbTime = (long)DateTime.Now.TimeOfDay.TotalMilliseconds;
int id = pvpnet.Invoke("loginService", "performLCDSHeartBeat", new object[] { pvpnet.accountID, pvpnet.sessionToken, pvpnet.heartbeatCount, DateTime.Now.ToString("ddd MMM d yyyy HH:mm:ss 'GMT-0700'") });
pvpnet.Cancel(id); // Ignore result for now
pvpnet.heartbeatCount++;
// Quick sleeps to shutdown the heartbeat quickly on a reconnect
while ((long)DateTime.Now.TimeOfDay.TotalMilliseconds - hbTime < 120000)
Thread.Sleep(100);
}
catch
{
}
}
}
#endregion
#region Disconnect Methods
/// <summary>
/// Disconnects this instance from server.
/// </summary>
public void Disconnect()
{
Thread t = new Thread(() =>
{
if (isConnected)
{
int id = Invoke("loginService", "logout", new object[] { authToken });
Join(id);
}
isConnected = false;
if (heartbeatThread != null)
heartbeatThread.Abort();
if (decodeThread != null)
decodeThread.Abort();
invokeID = 2;
heartbeatCount = 1;
pendingInvokes.Clear();
callbacks.Clear();
results.Clear();
client = null;
sslStream = null;
if (OnDisconnect != null)
OnDisconnect(this, EventArgs.Empty);
});
t.Start();
}
#endregion
#region Error Methods
/// <summary>
/// Formats the error message and shows it.
/// </summary>
/// <param name="message">The error message.</param>
/// <param name="type">The error type.</param>
private void Error(string message, ErrorType type)
{
Console.WriteLine(message);
Error error = new Error()
{
Type = type,
Message = message,
};
if (OnError != null)
OnError(this, error);
}
#endregion
#region Send Methods
/// <summary>
/// Invokes the specified packet.
/// </summary>
/// <param name="packet">The packet.</param>
/// <returns>Returns the invoke id.</returns>
private int Invoke(TypedObject packet)
{
int id = NextInvokeID();
pendingInvokes.Add(id);
try
{
byte[] data = RTMPSEncoder.EncodeInvoke(id, packet);
sslStream.Write(data, 0, data.Length);
return id;
}
catch (IOException e)
{
// Clear the pending invoke