-
Notifications
You must be signed in to change notification settings - Fork 0
/
BotController.cs
513 lines (417 loc) · 16.8 KB
/
BotController.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
using OpenSkillBot.Skill;
using System;
using Newtonsoft.Json;
using System.IO;
using Discord;
using System.Linq;
using System.Timers;
using System.Threading.Tasks;
using System.Collections.Generic;
using Discord.Rest;
using OpenSkillBot.Tournaments;
using OpenSkillBot.Achievements;
using OpenSkillBot.Serialization;
namespace OpenSkillBot
{
public class PendingMatch
{
private Team team1;
private Team team2;
public PendingMatch(Team team1, Team team2, bool isTourney = false)
{
Team1 = team1;
team1ids = team1.Players.Select(p => p.UUId);
Team2 = team2;
team2ids = team2.Players.Select(p => p.UUId);
IsTourney = isTourney;
}
public PendingMatch() {
// empty ctor for serialization
}
public PendingMatch(bool isTourney, ulong messageId)
{
this.IsTourney = isTourney;
this.messageId = messageId;
}
public bool IsTourney { get; set; }
[JsonProperty]
private IEnumerable<string> team1ids { get; set; }
[JsonIgnore]
public Team Team1 {
get {
if (team1 == null) team1 = MatchAction.UUIDListToTeam(team1ids);
return team1;
}
private set => team1 = value;
}
[JsonProperty]
private IEnumerable<string> team2ids { get; set; }
[JsonIgnore]
public Team Team2 {
get {
if (team2 == null) team2 = MatchAction.UUIDListToTeam(team2ids);
return team2;
}
private set => team2 = value;
}
[JsonProperty]
private ulong messageId { get; set; } = 0;
public async Task SendMessage() {
if (Program.Config.ActiveMatchesChannelId == 0) return;
var eb = new EmbedBuilder()
.WithFooter(!IsTourney ? "Standard match" : "Tournament match")
.WithColor(!IsTourney ? Discord.Color.Blue : Discord.Color.Purple);
eb.AddField("Team 1", $"{String.Join(", ", Team1.Players.Select(p => p.IGN))}");
eb.AddField("Team 2", $"{String.Join(", ", Team2.Players.Select(p => p.IGN))}");
var msg = await Program.DiscordIO.SendMessage(
"", Program.Config.GetActiveMatchesChannel(), eb.Build()
);
this.messageId = msg.Id;
}
public async Task DeleteMessage() {
if (messageId == 0) return;
var msg = (RestUserMessage) await Program.DiscordIO.GetMessage(messageId, Program.Config.ActiveMatchesChannelId);
await msg.DeleteAsync();
}
public bool IsSameMatch(Team team1, Team team2) {
return (team1.IsSameTeam(this.Team1) && team2.IsSameTeam(this.Team2)) || (team1.IsSameTeam(this.Team2) && team2.IsSameTeam(this.Team1));
}
}
public class ActionsStruct
{
private BotAction latestAction;
[JsonIgnore]
public BotAction LatestAction {
get {
if (LatestActionId == null) return null;
if (latestAction == null) latestAction = MatchHash[LatestActionId];
return latestAction;
}
set {
LatestActionId = value != null ? value.ActionId : null;
latestAction = value;
}
}
public string LatestActionId { get; set; }
// for O(1) lookup of matches :)
public Dictionary<string, BotAction> MatchHash { get; set; } = new Dictionary<string, BotAction>();
}
// support for old type, dont break old version deserialization
public class MatchesStruct {
public BotAction LatestAction { get; set; }
// for O(1) lookup of matches :)
public Dictionary<string, BotAction> MatchHash { get; set; } = new Dictionary<string, BotAction>();
}
// support for old type, dont break old version deserialization
public class MatchesStructOld {
public MatchAction LatestAction { get; set; }
// for O(1) lookup of matches :)
public Dictionary<string, MatchAction> MatchHash { get; set; } = new Dictionary<string, MatchAction>();
}
public class TourneyStruct {
public IDictionary<string, Tournament> CompletedTournaments { get; set; } = new Dictionary<string, Tournament>();
public List<Tournament> Tournaments { get; set; } = new List<Tournament>();
// referential integrity after restart
private Tournament activeTournament;
[JsonIgnore]
public Tournament ActiveTournament {
get {
if (activeTournament == null) {
// search
activeTournament = Tournaments.FirstOrDefault(t => t.Id.Equals(activeTournamentId));
}
return activeTournament;
}
set {
activeTournament = value;
activeTournamentId = value == null ? null : value.Id;
Program.Controller.SerializeTourneys();
}
}
[JsonProperty]
private string activeTournamentId { get; set; }
}
public class BotController
{
private const string lbFileName = "leaderboard.json";
private const string ahFileName = "actionhistory.json";
private const string pmFileName = "pendingmatches.json";
private const string tourneyFileName = "tourneys.json";
private const string achvsFileName = "achievements.json";
public Leaderboard CurLeaderboard;
public AchievementsContainer Achievements = new AchievementsContainer();
private Timer lbTimer = new Timer(3000);
private bool lbChangeQueued = false;
private string resetToken;
public string GenerateResetToken() {
resetToken = Player.RandomString(6);;
return resetToken;
}
public bool CheckResetToken(string token) {
return token.Equals(this.resetToken);
}
public ActionsStruct Actions = new ActionsStruct();
public BotAction LatestAction { get => Actions.LatestAction; set => Actions.LatestAction = value; }
// for O(1) lookup of matches :)
public Dictionary<string, BotAction> MatchHash { get => Actions.MatchHash; set => Actions.MatchHash = value; }
bool testMode;
public BotController(bool initialize = true, bool testMode = false) {
this.testMode = testMode;
if (initialize) Initialize();
}
bool initialized;
public void Initialize() {
if (initialized || testMode) return;
// get leaderboard
if (File.Exists(lbFileName)) {
CurLeaderboard = SerializeHelper.Deserialize<Leaderboard>(lbFileName);
CurLeaderboard.Initialize();
}
else {
CurLeaderboard = new Leaderboard();
UpdateLeaderboard();
}
// get action history
if (File.Exists(ahFileName)) {
try {
Actions = SerializeHelper.Deserialize<ActionsStruct>(ahFileName);
} catch (JsonException) {
try {
Console.WriteLine("Could not deserialise to ActionsStruct. Trying to deserialise in old format.");
var oldMatches = SerializeHelper.Deserialize<MatchesStruct>(ahFileName);
if (Actions == null) Actions = new ActionsStruct();
Actions.LatestAction = oldMatches.LatestAction;
Actions.MatchHash = oldMatches.MatchHash;
} catch (JsonException) {
Console.WriteLine("Could not deserialise to MatchesStruct. Trying to deserialise in old format.");
// backwards compatibility for old version
var oldVer = SerializeHelper.Deserialize<MatchesStructOld>(ahFileName);
Actions.LatestAction = oldVer.LatestAction;
foreach (var k in oldVer.MatchHash.Keys) {
Actions.MatchHash.Add(k, oldVer.MatchHash[k]);
}
}
}
if (LatestAction != null)
LatestAction.RepopulateLinks();
}
// get pending matches
if (File.Exists(pmFileName)) {
pendingMatches = SerializeHelper.Deserialize<List<PendingMatch>>(pmFileName);
}
// get tournaments
if (File.Exists(tourneyFileName)) {
Tourneys = SerializeHelper.Deserialize<TourneyStruct>(tourneyFileName);
}
// get achievements
if (File.Exists(achvsFileName)) {
Achievements = SerializeHelper.Deserialize<AchievementsContainer>(achvsFileName);
}
CurLeaderboard.LeaderboardChanged += (o,e) => {
UpdateLeaderboard();
};
// have the leaderboard update be set on a timer so that it doesn't fire multiple times a second unnecessarily
lbTimer.Elapsed += (o, e) => {
if (lbChangeQueued) UpdateLeaderboard();
};
lbTimer.Start();
initialized = true;
}
public async void UpdateLeaderboard() {
lbChangeQueued = false;
// only send if the leaderboard channel is set
if (Program.Config.LeaderboardChannelId != 0) {
// split the message size so it's less than discord's message limit
var lbStr = CurLeaderboard.GenerateLeaderboardText(2500);
var lbStrArr = lbStr.ToArray();
if (lbStrArr.Length != 0 && !string.IsNullOrWhiteSpace(lbStrArr[0]))
await Program.DiscordIO.PopulateChannel(Program.Config.LeaderboardChannelId, lbStrArr);
}
SerializeLeaderboard();
}
public void SerializeAll() {
SerializeLeaderboard();
SerializeActions();
SerializePending();
SerializeTourneys();
SerializeAchievements();
}
public bool SerializeLeaderboard() {
if (testMode) return true;
try
{
SerializeHelper.Serialize(CurLeaderboard, lbFileName);
return true;
}
catch (System.Exception)
{
Console.WriteLine("WARNING: Failed to save leaderboard!");
return false;
}
}
public bool SerializeActions() {
if (testMode) return true;
try {
SerializeHelper.Serialize(Actions, ahFileName);
return true;
}
catch (System.Exception) {
Console.WriteLine("WARNING: Failed to save action history!");
return false;
}
}
public bool SerializePending() {
if (testMode) return true;
// Convert the pending players to a list of UUIDs
try {
SerializeHelper.Serialize(pendingMatches, pmFileName);
return true;
}
catch (System.Exception) {
Console.WriteLine("WARNING: Failed to save pending matches!");
return false;
}
}
public bool SerializeTourneys() {
if (testMode) return true;
// Convert the pending players to a list of UUIDs
try {
SerializeHelper.Serialize(Tourneys, tourneyFileName);
return true;
}
catch (System.Exception) {
Console.WriteLine("WARNING: Failed to save tournaments!");
return false;
}
}
public bool SerializeAchievements() {
if (testMode) return true;
// Convert the pending players to a list of UUIDs
try {
SerializeHelper.Serialize(Achievements, achvsFileName);
return true;
}
catch (System.Exception) {
Console.WriteLine("WARNING: Failed to save achievements!");
return false;
}
}
private List<PendingMatch> pendingMatches = new List<PendingMatch>();
public async Task<PendingMatch> StartMatchAction(Team team1, Team team2, bool isTourney = false, bool force = false) {
if (!force) {
foreach (var p in team1.Players) {
if (p.IsPlaying) return null;
}
foreach (var p in team2.Players) {
if (p.IsPlaying) return null;
}
}
var pm = new PendingMatch(team1, team2, isTourney);
await pm.SendMessage();
pendingMatches.Add(pm);
// deafen in discord
foreach (var p in team1.Players) {
await p.Deafen();
p.IsPlaying = true;
}
foreach (var p in team2.Players) {
await p.Deafen();
p.IsPlaying = true;
}
SerializePending();
return pm;
}
public async Task<MatchAction> AddMatchAction(Team team1, Team team2, int result, bool isTourney = false) {
// swap if result is 2
if (result == 2) {
var temp = team1;
team1 = team2;
team2 = temp;
}
// mark as not playing
foreach (var p in team1.Players) {
p.IsPlaying = false;
}
foreach (var p in team2.Players) {
p.IsPlaying = false;
}
// Find the pending match containing the same team.
foreach (var p in pendingMatches) {
if (p.IsSameMatch(team1, team2)) {
pendingMatches.Remove(p);
await p.DeleteMessage();
SerializePending();
break;
}
}
MatchAction action = new MatchAction(team1, team2, result == 0, isTourney, result == -1);
if (isTourney) {
action.TourneyId = Tourneys.ActiveTournament.Id;
}
if (result != -1) {
await AddAction(action);
}
else {
await action.UndeafenPlayers();
}
return action;
}
public async Task AddAction(BotAction action) {
if (LatestAction != null) {
// note: this does recalculate
await LatestAction.InsertAfter(action);
}
else {
await action.DoAction();
}
LatestAction = action;
SerializeActions();
}
public BotAction FindAction(string id) {
if (MatchHash.ContainsKey(id)) return MatchHash[id];
return null;
}
public void AddActionToHash(BotAction m) {
if (MatchHash.ContainsKey(m.ActionId)) MatchHash[m.ActionId] = m;
else MatchHash.Add(m.ActionId, m);
}
public void RemoveActionFromHash(BotAction m) {
if (MatchHash.ContainsKey(m.ActionId)) MatchHash.Remove(m.ActionId);
}
// compatibility with older code
public List<Tournament> Tournaments { get => Tourneys.Tournaments; set => Tourneys.Tournaments = value; }
public TourneyStruct Tourneys = new TourneyStruct();
public bool IsTourneyActive => Tourneys.ActiveTournament.IsActive;
public async Task AddTournament(Tournament t) {
Tournaments.Add(t);
SerializeTourneys();
await t.SendMessage();
}
public async Task RemoveTournament(Tournament t) {
Tournaments.Remove(t);
SerializeTourneys();
await t.DeleteMessage();
}
public async Task<bool> StartTournament(Tournament t) {
if (t.IsActive) return false;
await t.Start(true);
// Tourneys.ActiveTournament = t;
SerializeTourneys();
return true;
}
public async Task<bool> ForceStop(Tournament t) {
// if (!Tourneys.ActiveTournament.IsActive) return false;
await t.Start(false);
SerializeTourneys();
return true;
}
public async Task<BotAction> UndoAction() {
if (LatestAction == null) return null;
var action = LatestAction;
await action.Undo();
LatestAction = action.PrevAction;
SerializeActions();
return action;
}
}
}