forked from ZeroK-RTS/Zero-K-Infrastructure
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TasClient.cs
893 lines (728 loc) · 32.5 KB
/
TasClient.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
#region using
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using ZkData;
using ZkData.UnitSyncLib;
using Timer = System.Timers.Timer;
#endregion
namespace LobbyClient
{
public class TasClient:Connection
{
public const int MaxAlliances = 16;
public const int MaxTeams = 16;
public ProtocolExtension Extensions { get; private set; }
public delegate void Invoker();
public delegate void Invoker<TArg>(TArg arg);
readonly string appName = "UnknownClient";
Dictionary<int, Battle> existingBattles = new Dictionary<int, Battle>();
Dictionary<string, User> existingUsers = new Dictionary<string, User>();
readonly bool forcedLocalIP = false;
bool isLoggedIn;
Dictionary<string, Channel> joinedChannels = new Dictionary<string, Channel>();
int lastUdpSourcePort;
int lastUserStatus;
readonly string localIp;
int pingInterval = 30; // how often to ping server (in seconds)
readonly Timer pingTimer;
public string serverHost { get; private set; }
int serverPort;
public Dictionary<int, Battle> ExistingBattles { get { return existingBattles; } set { existingBattles = value; } }
public Dictionary<string, User> ExistingUsers { get { return existingUsers; } set { existingUsers = value; } }
public override async Task OnConnected()
{
MyBattle = null;
ExistingUsers = new Dictionary<string, User>();
joinedChannels = new Dictionary<string, Channel>();
existingBattles = new Dictionary<int, Battle>();
isLoggedIn = false;
}
public override async Task OnConnectionClosed(bool wasRequested)
{
ExistingUsers = new Dictionary<string, User>();
joinedChannels = new Dictionary<string, Channel>();
existingBattles = new Dictionary<int, Battle>();
MyBattle = null;
isLoggedIn = false;
ConnectionLost(this, new TasEventArgs(string.Format("Connection {0}", wasRequested ? "closed on user request" : "disconnected")));
}
public override async Task OnLineReceived(string line)
{
try {
dynamic obj = CommandJsonSerializer.DeserializeLine(line);
await Process(obj);
} catch (Exception ex) {
Trace.TraceError("Error processing line {0} : {1}", line, ex);
}
}
public async Task SendCommand<T>(T data)
{
try {
var line = CommandJsonSerializer.SerializeToLine(data);
await SendString(line);
} catch (Exception ex) {
Trace.TraceError("Error sending {0} : {1}", data,ex);
}
}
static CommandJsonSerializer CommandJsonSerializer = new CommandJsonSerializer();
public bool IsLoggedIn { get { return isLoggedIn; } }
public Dictionary<string, Channel> JoinedChannels { get { return joinedChannels; } }
public Battle MyBattle { get; protected set; }
//public int MyBattleID { get { return MyBattle != null ? MyBattle.BattleID : 0; } }
public UserBattleStatus MyBattleStatus
{
get
{
if (MyBattle != null) {
UserBattleStatus ubs;
MyBattle.Users.TryGetValue(UserName, out ubs);
return ubs;
}
return null;
}
}
public int MyBattleID
{
get
{
var bat = MyBattle;
if (bat != null) return bat.BattleID;
else return 0;
}
}
public User MyUser
{
get
{
User us;
ExistingUsers.TryGetValue(UserName, out us);
return us;
}
}
public int PingInterval
{
get { return pingInterval; }
set
{
pingInterval = value;
pingTimer.Interval = pingInterval*1000;
}
}
public string ServerSpringVersion {get { return ServerWelcome != null ? ServerWelcome.Engine : null; } }
public string UserName { get; private set; }
public string UserPassword { get; private set; }
public event EventHandler<User> UserAdded = delegate { };
public event EventHandler<UserDisconnected> UserRemoved = delegate { };
public event EventHandler<OldNewPair<User>> UserStatusChanged = delegate { };
public event EventHandler<Battle> BattleFound = delegate { };
public event EventHandler<ChannelUserInfo> ChannelUserAdded = delegate { };
public event EventHandler<ChannelUserRemovedInfo> ChannelUserRemoved = delegate { };
public event EventHandler<Welcome> Connected = delegate { };
public event EventHandler<JoinChannelResponse> ChannelJoinFailed = delegate { };
public event EventHandler<TasEventArgs> LoginAccepted = delegate { };
public event EventHandler<LoginResponse> LoginDenied = delegate { };
public event EventHandler<TasSayEventArgs> Said = delegate { }; // this is fired when any kind of say message is recieved
public event EventHandler<SayingEventArgs> Saying = delegate { }; // this client is trying to say somethign
public event EventHandler<BattleUserEventArgs> BattleUserJoined = delegate { };
public event EventHandler<BattleUserEventArgs> BattleUserLeft = delegate { };
public event EventHandler<CancelEventArgs<Channel>> PreviewChannelJoined = delegate { };
public event EventHandler<TasEventArgs> RegistrationAccepted = delegate { };
public event EventHandler<RegisterResponse> RegistrationDenied = delegate { };
public event EventHandler<Battle> BattleRemoved = delegate { }; // raised just after the battle is removed from the battle list
public event EventHandler<Battle> MyBattleRemoved = delegate { }; // raised just after the battle is removed from the battle list
public event EventHandler<Battle> BattleClosed = delegate { };
public event EventHandler<Battle> BattleOpened = delegate { };
public event EventHandler<Battle> BattleJoined = delegate { };
public event EventHandler<UserBattleStatus> BattleUserStatusChanged = delegate { };
public event EventHandler<UserBattleStatus> BattleMyUserStatusChanged = delegate { };
public event EventHandler<Channel> ChannelJoined = delegate { };
public event EventHandler<Channel> ChannelLeft = delegate { };
public event EventHandler<BotBattleStatus> BattleBotAdded = delegate { };
public event EventHandler<BotBattleStatus> BattleBotUpdated = delegate { };
public event EventHandler<BotBattleStatus> BattleBotRemoved = delegate { };
public event EventHandler<TasEventArgs> ConnectionLost = delegate { };
public event EventHandler<Say> Rang = delegate { };
public event EventHandler<CancelEventArgs<TasSayEventArgs>> PreviewSaid = delegate { };
public event EventHandler<Battle> MyBattleHostExited = delegate { };
public event EventHandler<Battle> MyBattleStarted = delegate { };
public event EventHandler<SetRectangle> StartRectAdded = delegate { };
public event EventHandler<SetRectangle> StartRectRemoved = delegate { };
public event EventHandler<OldNewPair<Battle>> BattleInfoChanged = delegate { };
public event EventHandler<OldNewPair<Battle>> BattleMapChanged = delegate { };
public event EventHandler<OldNewPair<Battle>> MyBattleMapChanged = delegate { };
public event EventHandler<Battle> ModOptionsChanged = delegate { };
public event EventHandler<TasEventArgs> ChannelTopicChanged = delegate { };
public event EventHandler<EventArgs<User>> UserExtensionsChanged = delegate { };
public event EventHandler<EventArgs<User>> MyExtensionsChanged = delegate { };
public TasClient(string appName, Login.ClientTypes? clientTypes = null, string ipOverride = null)
{
if (clientTypes.HasValue) this.clientType = clientTypes.Value;
this.appName = appName;
if (!string.IsNullOrEmpty(ipOverride))
{
localIp = ipOverride;
forcedLocalIP = true;
}
else
{
var addresses = Dns.GetHostAddresses(Dns.GetHostName());
localIp = addresses[0].ToString();
foreach (var adr in addresses)
{
if (adr.AddressFamily == AddressFamily.InterNetwork)
{
localIp = adr.ToString();
break;
}
}
}
Extensions = new ProtocolExtension(this, (user, data) => {
User u;
if (ExistingUsers.TryGetValue(user, out u))
{
UserExtensionsChanged(this, new EventArgs<User>(u));
}
});
pingTimer = new Timer(pingInterval*1000) { AutoReset = true };
pingTimer.Elapsed += OnPingTimer;
}
public async Task AddBattleRectangle(int allyno, BattleRect rect)
{
{
if (allyno < Spring.MaxAllies && allyno >= 0) {
await SendCommand(new SetRectangle() { Number = allyno, Rectangle = rect });
}
}
}
private async Task Process(SetRectangle rect)
{
var bat = MyBattle;
if (bat != null) {
if (rect.Rectangle == null) {
BattleRect org;
bat.Rectangles.TryRemove(rect.Number, out org);
StartRectAdded(this, rect);
} else {
bat.Rectangles[rect.Number] = rect.Rectangle;
StartRectRemoved(this, rect);
}
}
}
private async Task Process(SetModOptions options)
{
var bat = MyBattle;
if (bat != null) {
bat.ModOptions = options.Options;
ModOptionsChanged(this, bat);
}
}
public Task AddBot(string name, string aiDll, int? allyNumber= null, int? teamNumber= null)
{
var u = new UpdateBotStatus();
if (aiDll != null) u.AiLib = aiDll;
if (name != null) u.Name = name;
if (allyNumber != null) u.AllyNumber = allyNumber;
if (teamNumber != null) u.TeamNumber = teamNumber;
return SendCommand(u);
}
public Task ChangeMap(string name)
{
return SendCommand(new BattleUpdate() { Header = new BattleHeader() { BattleID = MyBattleID, Map = name } });
}
public async Task ChangeMyBattleStatus(bool? spectate = null,
SyncStatuses? syncStatus = null,
int? ally = null,
int? team = null)
{
var ubs = MyBattleStatus;
if (ubs != null) {
var status = new UpdateUserBattleStatus() { IsSpectator = spectate, Sync = syncStatus, AllyNumber = ally, TeamNumber = team, Name = UserName};
await SendCommand(status);
}
}
public Task ChangeMyUserStatus(bool? isAway = null, bool? isInGame = null)
{
return SendCommand(new ChangeUserStatus() { IsAfk = isAway, IsInGame = isInGame });
}
SynchronizationContext context;
public void Connect(string host, int port)
{
context = SynchronizationContext.Current;
serverHost = host;
serverPort = port;
WasDisconnectRequested = false;
pingTimer.Start();
Connect(host, port, forcedLocalIP ? localIp : null);
}
public bool WasDisconnectRequested { get; private set; }
public void RequestDisconnect()
{
WasDisconnectRequested = true;
RequestClose();
}
public async Task ForceAlly(string username, int ally)
{
if (MyBattle != null && MyBattle.Users.ContainsKey(username)) {
var ubs = new UpdateUserBattleStatus() { Name = username, AllyNumber = ally };
await SendCommand(ubs);
}
}
public async Task ForceSpectator(string username, bool spectatorState = true)
{
if (MyBattle != null && MyBattle.Users.ContainsKey(username))
{
var ubs = new UpdateUserBattleStatus() { Name = username, IsSpectator = spectatorState };
await SendCommand(ubs);
}
}
public async Task ForceTeam(string username, int team)
{
if (MyBattle != null && MyBattle.Users.ContainsKey(username))
{
var ubs = new UpdateUserBattleStatus() { Name = username, TeamNumber = team };
await SendCommand(ubs);
}
}
public void GameSaid(string username, string text)
{
InvokeSaid(new TasSayEventArgs(SayPlace.Game, "", username, text, false));
}
public bool GetExistingUser(string name, out User u)
{
return ExistingUsers.TryGetValue(name, out u);
}
public User GetUserCaseInsensitive(string userName)
{
return ExistingUsers.Values.FirstOrDefault(u => String.Equals(u.Name, userName, StringComparison.InvariantCultureIgnoreCase));
}
public Task JoinBattle(int battleID, string password = null)
{
return SendCommand(new JoinBattle() { BattleID = battleID, Password = password });
}
public Task JoinChannel(string channelName, string key=null)
{
return SendCommand(new JoinChannel() { ChannelName = channelName, Password = key });
}
public Task Kick(string username, int? battleID=null, string reason = null)
{
return SendCommand(new KickFromBattle() { Name = username, BattleID = battleID, Reason = reason });
}
public Task AdminKickFromLobby(string username,string reason)
{
return SendCommand(new KickFromServer() { Name = username, Reason = reason });
}
public void AdminSetTopic(string channel, string topic) {
Say(SayPlace.User, "ChanServ", string.Format("!topic #{0} {1}", channel, topic.Replace("\n","\\n")),false);
}
public void AdminSetChannelPassword(string channel, string password) {
if (string.IsNullOrEmpty(password)) {
Say(SayPlace.User, "ChanServ",string.Format("!lock #{0} {1}", channel, password),false);
} else {
Say(SayPlace.User, "ChanServ", string.Format("!unlock #{0}", channel), false);
}
}
public async Task LeaveBattle()
{
if (MyBattle != null) {
await SendCommand(new LeaveBattle() { BattleID = MyBattle.BattleID });
}
}
public async Task LeaveChannel(string channelName)
{
if (joinedChannels.ContainsKey(channelName)) {
await SendCommand(new LeaveChannel() { ChannelName = channelName });
}
}
public static long GetMyUserID() {
var nics = NetworkInterface.GetAllNetworkInterfaces().Where(x=> !String.IsNullOrWhiteSpace(x.GetPhysicalAddress().ToString())
&& x.NetworkInterfaceType != NetworkInterfaceType.Loopback && x.NetworkInterfaceType != NetworkInterfaceType.Tunnel);
var wantedNic = nics.FirstOrDefault();
if (wantedNic != null)
{
return Crc.Crc32(wantedNic.GetPhysicalAddress().GetAddressBytes());
}
return 0;
}
public Task Login(string userName, string password)
{
UserName = userName;
UserPassword = password;
return SendCommand(new Login() { Name = userName, PasswordHash = Utils.HashLobbyPassword(password), ClientType = clientType, UserID = GetMyUserID()});
}
Login.ClientTypes clientType = LobbyClient.Login.ClientTypes.ZeroKLobby | (Environment.OSVersion.Platform == PlatformID.Unix ? LobbyClient.Login.ClientTypes.Linux : 0);
public Task OpenBattle(Battle nbattle)
{
if (MyBattle != null) LeaveBattle();
return SendCommand(new OpenBattle() {
Header =
new BattleHeader() {
Engine = nbattle.EngineVersion,
Game = nbattle.ModName,
Ip = nbattle.Ip ?? localIp,
Port = nbattle.HostPort,
Map = nbattle.MapName,
Password = nbattle.Password,
MaxPlayers = nbattle.MaxPlayers,
Title = nbattle.Title
}
});
}
public Task Register(string username, string password)
{
return SendCommand(new Register() { Name = username, PasswordHash = Utils.HashLobbyPassword(password) });
}
public async Task RemoveBattleRectangle(int allyno)
{
if (MyBattle.Rectangles.ContainsKey(allyno)) {
await SendCommand(new SetRectangle() { Number = allyno, Rectangle = null });
}
}
public async Task RemoveBot(string name)
{
var bat = MyBattle;
if (bat != null && bat.Bots.ContainsKey(name)) await SendCommand(new RemoveBot{Name = name});
}
public Task Ring(SayPlace place, string channel, string text = null)
{
return Say(place, channel, text ?? ("Ringing " + channel), false, isRing: true);
}
public async Task ForceJoinBattle(string name, string battleHostName) {
var battle = ExistingBattles.Values.FirstOrDefault(x => x.Founder.Name == battleHostName);
if (battle != null) await ForceJoinBattle(name, battle.BattleID);
}
public Task ForceJoinBattle(string name, int battleID)
{
return SendCommand(new ForceJoinBattle() { Name = name, BattleID = battleID });
}
public Task ForceJoinChannel(string user, string channel)
{
return SendCommand(new ForceJoinChannel() { UserName = user, ChannelName = channel });
}
public Task ForceLeaveChannel(string user, string channel, string reason = null)
{
return SendCommand(new KickFromChannel() { ChannelName = channel, UserName = user, Reason = reason });
}
/// <summary>
/// Say something through chat system
/// </summary>
/// <param Name="place">Pick user (private message) channel or battle</param>
/// <param Name="channel">Channel or User Name</param>
/// <param Name="inputtext">chat text</param>
/// <param Name="isEmote">is message emote? (channel or battle only)</param>
/// <param Name="linePrefix">text to be inserted in front of each line (example: "!pm xyz")</param>
public async Task Say(SayPlace place, string channel, string inputtext, bool isEmote, string linePrefix = "", bool isRing = false)
{
if (String.IsNullOrEmpty(inputtext)) return;
var lines = inputtext.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var text in lines)
{
if (String.IsNullOrEmpty(text)) continue;
var sentText = linePrefix + text;
var args = new SayingEventArgs(place, channel, sentText, isEmote);
Saying(this, args);
if (args.Cancel) continue;
if (args.SayPlace == SayPlace.Channel && !JoinedChannels.ContainsKey(args.Channel)) {
await JoinChannel(args.Channel);
}
var say = new Say() { Target = args.Channel, Place = args.SayPlace, Text = args.Text, IsEmote = args.IsEmote, Ring = isRing};
await SendCommand(say);
}
}
public Task SendRaw(string text)
{
if (!text.EndsWith("\n")) text += "\n";
return SendString(text);
}
public Task SetModOptions(Dictionary<string,string> data)
{
return SendCommand(new SetModOptions() { Options = data });
}
public Task UpdateModOptions(Dictionary<string, string> data)
{
var cur = new Dictionary<string, string>(MyBattle.ModOptions);
foreach (var d in data) {
cur[d.Key] = d.Value;
}
return SetModOptions(cur);
}
/// <summary>
/// Starts game and automatically does hole punching if necessary
/// </summary>
public void StartGame()
{
ChangeMyUserStatus(false, true);
}
public async Task UpdateBot(string name, string aiDll, int? allyNumber = null, int? teamNumber = null)
{
var bat = MyBattle;
if (bat != null && bat.Bots.ContainsKey(name)) {
await AddBot(name, aiDll, allyNumber, teamNumber);
}
}
public async Task Process(UpdateBotStatus status)
{
var bat = MyBattle;
if (bat != null)
{
BotBattleStatus ubs;
bat.Bots.TryGetValue(status.Name, out ubs);
if (ubs != null) {
ubs.UpdateWith(status);
BattleBotUpdated(this, ubs);
} else {
var nubs = new BotBattleStatus(status.Name, status.Owner, status.AiLib);
nubs.UpdateWith(status);
bat.Bots[status.Name] = nubs;
BattleBotAdded(this, nubs);
}
}
}
public async Task Process(RemoveBot status)
{
var bat = MyBattle;
if (bat != null)
{
BotBattleStatus ubs;
if (bat.Bots.TryRemove(status.Name, out ubs)) {
BattleBotRemoved(this, ubs);
}
}
}
User UserGetter(string n)
{
User us;
if (existingUsers.TryGetValue(n, out us)) return us;
else return new User() { Name = n };
}
async Task Process(BattleAdded bat)
{
var newBattle = new Battle();
newBattle.UpdateWith(bat.Header, UserGetter);
existingBattles[newBattle.BattleID] = newBattle;
newBattle.Founder.IsInBattleRoom = true;
BattleFound(this, newBattle);
}
async Task Process(JoinedBattle bat)
{
User user;
existingUsers.TryGetValue(bat.User, out user);
Battle battle;
ExistingBattles.TryGetValue(bat.BattleID, out battle);
if (user != null && battle != null) {
battle.Users[user.Name] = new UserBattleStatus(user.Name, user);
user.IsInBattleRoom = true;
BattleUserJoined(this, new BattleUserEventArgs(user.Name, bat.BattleID));
if (user.Name == UserName) {
MyBattle = battle;
if (battle.Founder.Name == UserName) BattleOpened(this, battle);
BattleJoined(this, MyBattle);
}
}
}
async Task Process(LeftBattle left)
{
User user;
Battle bat;
existingUsers.TryGetValue(left.User, out user);
existingBattles.TryGetValue(left.BattleID, out bat);
if (bat != null && user != null) {
user.IsInBattleRoom = false;
UserBattleStatus removed;
bat.Users.TryRemove(left.User, out removed);
if (MyBattle != null && left.BattleID == MyBattleID) {
if (UserName == left.User) {
bat.Rectangles.Clear();
bat.Bots.Clear();
bat.ModOptions.Clear();
MyBattle = null;
BattleClosed(this, bat);
}
}
BattleUserLeft(this, new BattleUserEventArgs(user.Name, left.BattleID));
}
}
async Task Process(BattleRemoved br)
{
Battle battle;
if (!existingBattles.TryGetValue(br.BattleID, out battle)) return;
foreach (var u in battle.Users.Keys)
{
User user;
if (ExistingUsers.TryGetValue(u, out user)) user.IsInBattleRoom = false;
}
existingBattles.Remove(br.BattleID);
if (battle == MyBattle)
{
BattleClosed(this, battle);
MyBattleRemoved(this, battle);
}
BattleRemoved(this, battle);
}
async Task Process(LoginResponse loginResponse)
{
if (loginResponse.ResultCode == LoginResponse.Code.Ok) {
isLoggedIn = true;
LoginAccepted(this, new TasEventArgs());
} else {
isLoggedIn = false;
LoginDenied(this, loginResponse);
}
}
async Task Process(Ping ping)
{
lastPing = DateTime.UtcNow;
}
async Task Process(User userUpdate)
{
User user;
User old = null;
existingUsers.TryGetValue(userUpdate.Name, out user);
if (user != null) {
old = user.Clone();
user.UpdateWith(userUpdate);
} else user = userUpdate;
existingUsers[user.Name] = user;
if (old == null) UserAdded(this, user);
if (old != null) {
var bat = MyBattle;
if (bat != null && bat.Founder.Name == user.Name)
{
if (user.IsInGame && !old.IsInGame) MyBattleStarted(this,bat );
if (!user.IsInGame && old.IsInGame) MyBattleHostExited(this, bat);
}
}
UserStatusChanged(this, new OldNewPair<User>(old, user));
}
async Task Process(RegisterResponse registerResponse)
{
if (registerResponse.ResultCode == RegisterResponse.Code.Ok)
{
RegistrationAccepted(this, new TasEventArgs());
}
else
{
RegistrationDenied(this, registerResponse);
}
}
async Task Process(Say say)
{
InvokeSaid(new TasSayEventArgs(say.Place, say.Target,say.User, say.Text, say.IsEmote));
if (say.Ring) Rang(this, say);
}
public Welcome ServerWelcome = new Welcome();
async Task Process(Welcome welcome)
{
ServerWelcome = welcome;
Connected(this, welcome);
}
async Task Process(JoinChannelResponse response)
{
if (response.Success) {
var chan = new Channel() {
Name = response.Channel.ChannelName,
Topic = response.Channel.Topic,
TopicSetBy = response.Channel.TopicSetBy,
TopicSetDate = response.Channel.TopicSetDate,
};
JoinedChannels[response.ChannelName] = chan;
foreach (var u in response.Channel.Users) {
User user;
if (existingUsers.TryGetValue(u, out user)) chan.Users[u] = user;
}
var cancelEvent = new CancelEventArgs<Channel>(chan);
PreviewChannelJoined(this, cancelEvent);
if (!cancelEvent.Cancel) {
ChannelJoined(this, chan);
ChannelUserAdded(this, new ChannelUserInfo() {Channel = chan, Users = chan.Users.Values.ToList()});
}
} else {
ChannelJoinFailed(this, response);
}
}
async Task Process(ChannelUserAdded arg)
{
Channel chan;
if (joinedChannels.TryGetValue(arg.ChannelName, out chan)) {
if (!chan.Users.ContainsKey(arg.UserName)) {
User user;
if (existingUsers.TryGetValue(arg.UserName, out user)) {
chan.Users[arg.UserName] = user;
ChannelUserAdded(this, new ChannelUserInfo() { Channel = chan, Users = new List<User>(){user}});
}
}
}
}
async Task Process(ChannelUserRemoved arg)
{
Channel chan;
if (joinedChannels.TryGetValue(arg.ChannelName, out chan)) {
User org;
if (chan.Users.TryRemove(arg.UserName, out org))
{
if (arg.UserName == UserName) ChannelLeft(this, chan);
ChannelUserRemoved(this, new ChannelUserRemovedInfo() { Channel = chan, User = org });
}
}
}
async Task Process(UserDisconnected arg)
{
existingUsers.Remove(arg.Name);
UserRemoved(this, arg);
}
async Task Process(UpdateUserBattleStatus status)
{
var bat = MyBattle;
if (bat != null) {
UserBattleStatus ubs;
bat.Users.TryGetValue(status.Name, out ubs);
if (ubs != null) {
ubs.UpdateWith(status);
if (status.Name == UserName) BattleMyUserStatusChanged(this, ubs);
BattleUserStatusChanged(this, ubs);
}
}
}
async Task Process(BattleUpdate batUp)
{
var h = batUp.Header;
Battle bat;
if (existingBattles.TryGetValue(h.BattleID.Value, out bat)) {
var org = bat.Clone();
bat.UpdateWith(h, UserGetter);
var pair = new OldNewPair<Battle>(org, bat);
if (org.MapName != bat.MapName) {
if (bat == MyBattle) MyBattleMapChanged(this, pair);
BattleMapChanged(this, pair);
}
BattleInfoChanged(this, pair);
}
}
void InvokeSaid(TasSayEventArgs sayArgs)
{
var previewSaidEventArgs = new CancelEventArgs<TasSayEventArgs>(sayArgs);
PreviewSaid(this, previewSaidEventArgs);
if (!previewSaidEventArgs.Cancel) Said(this, sayArgs);
}
DateTime lastPing;
void OnPingTimer(object sender, EventArgs args)
{
if (context != null) context.Post(x=>PingTimerInternal(),null);
else PingTimerInternal();
}
private void PingTimerInternal()
{
if (IsConnected) SendCommand(new Ping());
else if(!WasDisconnectRequested) Connect(serverHost, serverPort);
}
}
}