-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerStats.cs
More file actions
1674 lines (1421 loc) · 65.4 KB
/
ServerStats.cs
File metadata and controls
1674 lines (1421 loc) · 65.4 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
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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Attributes;
using CounterStrikeSharp.API.Modules.Commands;
using CounterStrikeSharp.API.Modules.Entities;
using CounterStrikeSharp.API.Modules.Events;
using CounterStrikeSharp.API.Modules.Timers;
using CounterStrikeSharp.API.Modules.Utils;
using CsTimer = CounterStrikeSharp.API.Modules.Timers.Timer;
namespace ServerStats
{
[MinimumApiVersion(80)]
public class PlayerStatsEventTracker : BasePlugin
{
public class DebugLogEntry
{
public string Timestamp { get; set; } = "";
public string Reason { get; set; } = "";
public string PreviousMatchId { get; set; } = "";
public string NewMatchId { get; set; } = "";
public string CurrentMap { get; set; } = "";
}
public class MatchDatabase
{
public string MatchID { get; set; } = "";
public string MapName { get; set; } = "";
public string WorkshopID { get; set; } = "";
public string CollectionID { get; set; } = "";
public DateTime StartTime { get; set; }
public DateTime LastUpdated { get; set; }
public bool MatchComplete { get; set; }
public int CTWins { get; set; }
public int TWins { get; set; }
public int TotalRounds { get; set; }
[JsonConverter(typeof(InlineListConverter<int>))]
public List<int> CTScoreHistory { get; set; } = new();
[JsonConverter(typeof(InlineListConverter<int>))]
public List<int> TScoreHistory { get; set; } = new();
[JsonIgnore]
public bool IsWarmup { get; set; }
public List<PlayerMatchData> Players { get; set; } = new();
public List<CombatLog> KillFeed { get; set; } = new();
public List<ObjectiveLog> EventFeed { get; set; } = new();
public List<ChatLog> ChatFeed { get; set; } = new();
}
public class PlayerMatchData
{
public ulong SteamID { get; set; }
public string Name { get; set; } = "Unknown";
public bool IsBot { get; set; }
[JsonPropertyName("Team")]
[JsonConverter(typeof(InlineListConverter<int>))]
public List<int> TeamHistory { get; set; } = new();
[JsonPropertyName("Kills")]
[JsonConverter(typeof(InlineListConverter<int>))]
public List<int> KillsHistory { get; set; } = new();
[JsonPropertyName("Deaths")]
[JsonConverter(typeof(InlineListConverter<int>))]
public List<int> DeathsHistory { get; set; } = new();
[JsonPropertyName("Assists")]
[JsonConverter(typeof(InlineListConverter<int>))]
public List<int> AssistsHistory { get; set; } = new();
[JsonPropertyName("ZeusKills")]
[JsonConverter(typeof(InlineListConverter<int>))]
public List<int> ZeusKillsHistory { get; set; } = new();
[JsonPropertyName("MVPs")]
[JsonConverter(typeof(InlineListConverter<int>))]
public List<int> MVPsHistory { get; set; } = new();
[JsonPropertyName("Score")]
[JsonConverter(typeof(InlineListConverter<int>))]
public List<int> ScoreHistory { get; set; } = new();
[JsonPropertyName("Alive")]
[JsonConverter(typeof(InlineListConverter<bool>))]
public List<bool> AliveHistory { get; set; } = new();
[JsonPropertyName("Inventory")]
[JsonConverter(typeof(InlineListConverter<string>))]
public List<string> InventoryHistory { get; set; } = new();
[JsonIgnore] public int CurrentTeam { get; set; }
[JsonIgnore] public int CurrentKills { get; set; }
[JsonIgnore] public int CurrentRoundKills { get; set; }
[JsonIgnore] public int CurrentDeaths { get; set; }
[JsonIgnore] public int CurrentAssists { get; set; }
[JsonIgnore] public int CurrentZeusKills { get; set; }
[JsonIgnore] public int CurrentMVPs { get; set; }
[JsonIgnore] public int CurrentScore { get; set; }
}
public class CombatLog
{
public int Round { get; set; }
public string Type { get; set; } = "Unknown";
public string PlayerTeam { get; set; } = "";
public string PlayerName { get; set; } = "Unknown";
public ulong PlayerSteamID { get; set; }
public string OpponentName { get; set; } = "None";
public ulong OpponentSteamID { get; set; }
public string Weapon { get; set; } = "";
public int Damage { get; set; }
public bool IsHeadshot { get; set; }
public string Timestamp { get; set; } = "";
}
public class ObjectiveLog
{
public int Round { get; set; }
public string PlayerName { get; set; } = "Unknown";
public ulong PlayerSteamID { get; set; }
public string Event { get; set; } = "";
public string Timestamp { get; set; } = "";
}
public class ChatLog
{
public int Round { get; set; }
public string PlayerName { get; set; } = "Unknown";
public ulong PlayerSteamID { get; set; }
public string Message { get; set; } = "";
public bool TeamChat { get; set; }
public string Timestamp { get; set; } = "";
}
public class InlineListConverter<T> : JsonConverter<List<T>>
{
public override List<T>? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return JsonSerializer.Deserialize<List<T>>(ref reader, options);
}
public override void Write(Utf8JsonWriter writer, List<T> value, JsonSerializerOptions options)
{
var compactOptions = new JsonSerializerOptions { WriteIndented = false };
string jsonString = JsonSerializer.Serialize(value, compactOptions);
writer.WriteRawValue(jsonString);
}
}
// Live Data Container - Optimized to be a single persistent object
private MatchDatabase _matchData = new();
// Fast lookup to find player objects inside _matchData.Players
private readonly ConcurrentDictionary<ulong, PlayerMatchData> _playerLookup = new();
private int _currentRound = 1;
// Caching scores locally to check for 0-0 reset
private int _ctWins = 0;
private int _tWins = 0;
private bool _roundStatsSnapshotTaken = false;
private bool _matchEndedNormally = false;
private const int TEAM_CT_MANAGER_ID = 3;
private const int TEAM_T_MANAGER_ID = 2;
private readonly Dictionary<string, string> _workshopMapIds = new();
private string _loadedCollectionId = "N/A";
private readonly List<string> _loadLog = new();
private bool _usesMatchLibrarian = true;
private FileSystemWatcher? _fileWatcher;
private DateTime _lastReloadTime = DateTime.MinValue;
private bool _announceZeusLeader = false;
private bool _announceAces = false;
private int _highestZeusKills = 0;
private readonly Dictionary<int, int> _lastDeathTick = new();
private CsTimer? _spectatorKickTimer = null;
private CsTimer? _noHumansRestartTimer = null;
private CancellationTokenSource _workshopCts = new();
private CommandInfo.CommandListenerCallback? _chatCommandDelegate;
private string _steamApiKey = "";
private const string WorkshopContentRelPath = "../bin/linuxsteamrt64/steamapps/workshop/content/730";
private const string WorkshopGrabLogRelPath = "addons/counterstrikesharp/configs/plugins/ServerStats/workshopgrab.log";
public override string ModuleName => "ServerStats";
public override string ModuleVersion => "2.1.0";
public override string ModuleAuthor => "|ZAPS| BONE";
public override void Load(bool hotReload)
{
RegisterEventHandler<EventPlayerDeath>(OnPlayerDeath, HookMode.Post);
RegisterEventHandler<EventRoundOfficiallyEnded>(OnRoundEnded, HookMode.Post);
RegisterEventHandler<EventRoundPrestart>(OnRoundPrestart, HookMode.Post);
RegisterEventHandler<EventMapShutdown>(OnMapShutdown, HookMode.Post);
RegisterEventHandler<EventCsWinPanelMatch>(OnMatchEnd, HookMode.Post);
// Removed OnMatchRestart, relying solely on Score 0:0 check in RoundPrestart
// RegisterEventHandler<EventRoundAnnounceMatchStart>(OnMatchRestart, HookMode.Post);
RegisterEventHandler<EventPlayerDisconnect>(OnPlayerDisconnect, HookMode.Post);
RegisterEventHandler<EventPlayerTeam>(OnPlayerTeam, HookMode.Post);
RegisterEventHandler<EventBombPlanted>(OnBombPlanted, HookMode.Post);
RegisterEventHandler<EventBombDefused>(OnBombDefused, HookMode.Post);
RegisterEventHandler<EventBombExploded>(OnBombExploded, HookMode.Post);
RegisterEventHandler<EventHostageFollows>(OnHostagePickup, HookMode.Post);
RegisterEventHandler<EventHostageRescued>(OnHostageRescued, HookMode.Post);
_chatCommandDelegate = OnPlayerChatCommand;
AddCommandListener("say", _chatCommandDelegate);
AddCommandListener("say_team", _chatCommandDelegate);
LoadConfigIni();
LoadWorkshopIni();
InitializeFileWatcher();
// REMOVED: Initializing match ID on load.
// We now strictly wait for OnRoundPrestart to detect a 0-0 score before creating a Match ID.
// This prevents duplicate match creation on map load and ensures restarts on the same map are handled correctly.
AddCommand("css_players", "Print tracked player stats (humans and bots)", (caller, cmdInfo) =>
{
if (caller != null)
{
cmdInfo.ReplyToCommand("Command disabled for players.");
}
else
{
PrintPlayerStats(caller, cmdInfo);
}
});
AddCommand("css_workshoplog", "Show the log of loading workshop.ini", (caller, cmdInfo) =>
{
CmdLog(caller, cmdInfo);
});
AddCommand("css_collectionid", "Output the server's loaded collection ID", (caller, cmdInfo) =>
{
cmdInfo.ReplyToCommand($"Server Collection ID: {_loadedCollectionId}");
});
AddCommand("css_databaseon", "Check if database recording is enabled", (caller, cmdInfo) =>
{
cmdInfo.ReplyToCommand($"[ServerStats] Database Recording (UsesMatchLibrarian): {(_usesMatchLibrarian ? "ENABLED" : "DISABLED")}");
});
string baseGameDir = Server.GameDirectory;
if (Path.GetFileName(baseGameDir) == "game")
{
baseGameDir = Path.Combine(baseGameDir, "csgo");
}
Task.Run(async () =>
{
try
{
await ProcessWorkshopCollection(baseGameDir, _workshopCts.Token);
}
catch (OperationCanceledException) { }
catch (Exception ex)
{
LogWorkshopGrabber(baseGameDir, $"CRITICAL ERROR: {ex.Message}");
}
});
}
public override void Unload(bool hotReload)
{
_workshopCts.Cancel();
_workshopCts.Dispose();
_workshopCts = new CancellationTokenSource();
if (_noHumansRestartTimer != null)
{
_noHumansRestartTimer.Kill();
_noHumansRestartTimer = null;
}
if (_spectatorKickTimer != null)
{
_spectatorKickTimer.Kill();
_spectatorKickTimer = null;
}
if (_fileWatcher != null)
{
_fileWatcher.EnableRaisingEvents = false;
_fileWatcher.Changed -= OnConfigFileChanged;
_fileWatcher.Dispose();
_fileWatcher = null;
}
if (_chatCommandDelegate != null)
{
RemoveCommandListener("say", _chatCommandDelegate, HookMode.Pre);
RemoveCommandListener("say_team", _chatCommandDelegate, HookMode.Pre);
_chatCommandDelegate = null;
}
// Deregister all event handlers to prevent GC delegate crashes after hot reload
DeregisterEventHandler<EventPlayerDeath>(OnPlayerDeath, HookMode.Post);
DeregisterEventHandler<EventRoundOfficiallyEnded>(OnRoundEnded, HookMode.Post);
DeregisterEventHandler<EventRoundPrestart>(OnRoundPrestart, HookMode.Post);
DeregisterEventHandler<EventMapShutdown>(OnMapShutdown, HookMode.Post);
DeregisterEventHandler<EventCsWinPanelMatch>(OnMatchEnd, HookMode.Post);
DeregisterEventHandler<EventPlayerDisconnect>(OnPlayerDisconnect, HookMode.Post);
DeregisterEventHandler<EventPlayerTeam>(OnPlayerTeam, HookMode.Post);
DeregisterEventHandler<EventBombPlanted>(OnBombPlanted, HookMode.Post);
DeregisterEventHandler<EventBombDefused>(OnBombDefused, HookMode.Post);
DeregisterEventHandler<EventBombExploded>(OnBombExploded, HookMode.Post);
DeregisterEventHandler<EventHostageFollows>(OnHostagePickup, HookMode.Post);
DeregisterEventHandler<EventHostageRescued>(OnHostageRescued, HookMode.Post);
}
private string ServerStatsConfigDir => Path.Combine(Server.GameDirectory, "csgo", "addons", "counterstrikesharp", "configs", "plugins", "ServerStats");
private string WorkshopIniPath => Path.Combine(ServerStatsConfigDir, "workshop.ini");
private string GeneralConfigPath => Path.Combine(ServerStatsConfigDir, "config.ini");
private string MatchLibrarianDir => Path.Combine(Server.GameDirectory, "csgo", "addons", "counterstrikesharp", "configs", "plugins", "MatchLibrarian");
private string MatchesDirPath => Path.Combine(MatchLibrarianDir, "matches");
private async Task ProcessWorkshopCollection(string csgoDir, CancellationToken token)
{
string configIniPath = Path.GetFullPath(Path.Combine(csgoDir, "addons/counterstrikesharp/configs/plugins/ServerStats/config.ini"));
string workshopIniPath = Path.GetFullPath(Path.Combine(csgoDir, "addons/counterstrikesharp/configs/plugins/ServerStats/workshop.ini"));
string workshopContentPath = Path.GetFullPath(Path.Combine(csgoDir, WorkshopContentRelPath));
LogWorkshopGrabber(csgoDir, $"--- Starting Workshop Map Loader Session: {DateTime.UtcNow} ---");
string collectionId = "";
if (File.Exists(configIniPath))
{
foreach (var line in File.ReadAllLines(configIniPath))
{
var trimmed = line.Trim();
if (string.IsNullOrEmpty(trimmed) || trimmed.StartsWith("#") || trimmed.StartsWith("//")) continue;
if (trimmed.StartsWith("api_key=", StringComparison.OrdinalIgnoreCase))
{
var parts = trimmed.Split('=', 2);
if (parts.Length > 1) _steamApiKey = parts[1].Trim();
}
else if (trimmed.StartsWith("collection_id=", StringComparison.OrdinalIgnoreCase))
{
var parts = trimmed.Split('=', 2);
if (parts.Length > 1) collectionId = parts[1].Trim();
}
}
}
if (string.IsNullOrEmpty(_steamApiKey))
{
LogWorkshopGrabber(csgoDir, "Error: 'api_key=' not found or empty in config.ini");
return;
}
if (string.IsNullOrEmpty(collectionId))
{
LogWorkshopGrabber(csgoDir, "Error: 'collection_id=' not found in config.ini");
return;
}
token.ThrowIfCancellationRequested();
LogWorkshopGrabber(csgoDir, $"Processing Collection ID from Config: {collectionId}");
List<string> mapIds;
try
{
mapIds = await FetchCollectionItems(collectionId, token);
LogWorkshopGrabber(csgoDir, $"API success. Found {mapIds.Count} items in collection.");
}
catch (OperationCanceledException) { throw; }
catch (Exception ex)
{
LogWorkshopGrabber(csgoDir, $"API Request Failed: {ex.Message}");
return;
}
token.ThrowIfCancellationRequested();
Dictionary<string, string> validMaps = new Dictionary<string, string>();
if (!Directory.Exists(workshopContentPath))
{
LogWorkshopGrabber(csgoDir, $"Error: Workshop content path missing: {workshopContentPath}");
return;
}
foreach (var mapId in mapIds)
{
string mapFolderPath = Path.Combine(workshopContentPath, mapId);
if (!Directory.Exists(mapFolderPath)) continue;
var vpkFiles = Directory.GetFiles(mapFolderPath, "*.vpk");
if (vpkFiles.Length == 0) continue;
string mainVpkPath;
var dirVpk = vpkFiles.FirstOrDefault(f => f.EndsWith("_dir.vpk", StringComparison.OrdinalIgnoreCase));
if (dirVpk != null)
{
mainVpkPath = dirVpk;
}
else
{
Array.Sort(vpkFiles);
mainVpkPath = vpkFiles[0];
}
string? internalMapName = ExtractMapNameFromVpk(mainVpkPath, mapId, csgoDir);
if (!string.IsNullOrEmpty(internalMapName))
{
validMaps[internalMapName] = mapId;
LogWorkshopGrabber(csgoDir, $"Identified: {internalMapName} -> {mapId}");
}
else
{
LogWorkshopGrabber(csgoDir, $"Warning: Could not parse map name from VPK for ID {mapId}");
}
}
List<string> newOutput = new List<string>();
newOutput.Add($"// Generated by ServerStats from Collection: {collectionId}");
foreach (var kvp in validMaps.OrderBy(x => x.Key))
{
newOutput.Add($"{kvp.Key}={kvp.Value}");
}
try
{
File.WriteAllLines(workshopIniPath, newOutput);
LogWorkshopGrabber(csgoDir, $"Success! Updated workshop.ini with {validMaps.Count} maps.");
Server.NextFrame(LoadWorkshopIni);
}
catch (Exception ex)
{
LogWorkshopGrabber(csgoDir, $"Error writing workshop.ini: {ex.Message}");
}
}
private async Task<List<string>> FetchCollectionItems(string collectionId, CancellationToken token)
{
using var client = new HttpClient();
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("collectioncount", "1"),
new KeyValuePair<string, string>("publishedfileids[0]", collectionId)
});
string url = $"https://api.steampowered.com/ISteamRemoteStorage/GetCollectionDetails/v1/?key={_steamApiKey}";
var response = await client.PostAsync(url, content, token);
response.EnsureSuccessStatusCode();
string json = await response.Content.ReadAsStringAsync(token);
var data = JsonSerializer.Deserialize<SteamCollectionResponse>(json);
List<string> ids = new List<string>();
if (data?.response?.collectiondetails != null && data.response.collectiondetails.Count > 0)
{
var children = data.response.collectiondetails[0].children;
if (children != null)
{
foreach (var child in children)
{
if (child.publishedfileid != null)
ids.Add(child.publishedfileid);
}
}
}
return ids;
}
private void LogMatchCreationDebug(string reason, string newId)
{
try
{
string debugFilePath = Path.Combine(MatchLibrarianDir, "debug.json");
List<DebugLogEntry> logEntries;
if (File.Exists(debugFilePath))
{
string existingJson = File.ReadAllText(debugFilePath);
try
{
logEntries = JsonSerializer.Deserialize<List<DebugLogEntry>>(existingJson) ?? new List<DebugLogEntry>();
}
catch
{
logEntries = new List<DebugLogEntry>();
}
}
else
{
logEntries = new List<DebugLogEntry>();
}
var entry = new DebugLogEntry
{
Timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss"),
Reason = reason,
PreviousMatchId = _matchData.MatchID,
NewMatchId = newId,
CurrentMap = Server.MapName
};
logEntries.Add(entry);
if (logEntries.Count > 50)
{
logEntries = logEntries.Skip(logEntries.Count - 50).ToList();
}
var jsonOptions = new JsonSerializerOptions { WriteIndented = true };
File.WriteAllText(debugFilePath, JsonSerializer.Serialize(logEntries, jsonOptions));
}
catch (Exception ex)
{
Console.WriteLine($"[ServerStats] Failed to write debug.json: {ex.Message}");
}
}
private string? ExtractMapNameFromVpk(string vpkPath, string mapId, string logDir)
{
try
{
using var fs = new FileStream(vpkPath, FileMode.Open, FileAccess.Read);
using var reader = new BinaryReader(fs);
uint signature = reader.ReadUInt32();
if (signature != 0x55aa1234) return null;
uint version = reader.ReadUInt32();
uint treeSize = reader.ReadUInt32();
if (version == 2) reader.ReadBytes(16);
long treeStart = fs.Position;
long treeEnd = treeStart + treeSize;
List<string> foundMaps = new List<string>();
while (fs.Position < treeEnd)
{
string extension = ReadNullTerminatedString(reader);
if (extension == "") break;
while (fs.Position < treeEnd)
{
string path = ReadNullTerminatedString(reader);
if (path == "") break;
string normPath = path.Replace("\\", "/");
bool isMapLocation = (normPath == "maps" || string.IsNullOrWhiteSpace(normPath));
while (fs.Position < treeEnd)
{
string filename = ReadNullTerminatedString(reader);
if (filename == "") break;
uint crc = reader.ReadUInt32();
ushort preloadBytes = reader.ReadUInt16();
reader.ReadUInt16();
reader.ReadUInt32();
reader.ReadUInt32();
ushort terminator = reader.ReadUInt16();
if (terminator != 0xFFFF) break;
if (preloadBytes > 0) reader.ReadBytes(preloadBytes);
if (extension == "vpk" && isMapLocation)
{
foundMaps.Add(filename);
}
}
}
}
if (foundMaps.Count > 0)
{
foundMaps.Sort();
return foundMaps[0];
}
}
catch
{
}
return null;
}
private string ReadNullTerminatedString(BinaryReader reader)
{
List<byte> charBytes = new List<byte>();
while (true)
{
if (reader.BaseStream.Position >= reader.BaseStream.Length) break;
byte b = reader.ReadByte();
if (b == 0x00) break;
charBytes.Add(b);
}
return Encoding.UTF8.GetString(charBytes.ToArray());
}
private void LogWorkshopGrabber(string baseDir, string message)
{
try
{
string logFullPath = Path.Combine(baseDir, WorkshopGrabLogRelPath);
string timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss");
string logLine = $"[{timestamp}] {message}{Environment.NewLine}";
string? directory = Path.GetDirectoryName(logFullPath);
if (directory != null && !Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
File.AppendAllText(logFullPath, logLine);
}
catch { }
}
private void StartNewMatchId(string reason)
{
// Reset main variables
string newId = DateTime.UtcNow.ToString("yyyy-MM-dd-HH-mm-ss");
LogMatchCreationDebug(reason, newId);
// Create a fresh MatchDatabase object.
_matchData = new MatchDatabase();
_matchData.MatchID = newId;
_matchData.StartTime = DateTime.UtcNow;
_highestZeusKills = 0;
// Clear lookups as the old objects are gone
_playerLookup.Clear();
_lastDeathTick.Clear();
_currentRound = 1;
_matchEndedNormally = false;
_roundStatsSnapshotTaken = false;
Console.WriteLine($"[ServerStats] Started new Match ID: {_matchData.MatchID} ({reason})");
}
private void InitializeFileWatcher()
{
try
{
if (!Directory.Exists(ServerStatsConfigDir)) Directory.CreateDirectory(ServerStatsConfigDir);
if (!Directory.Exists(MatchLibrarianDir)) Directory.CreateDirectory(MatchLibrarianDir);
if (!Directory.Exists(MatchesDirPath)) Directory.CreateDirectory(MatchesDirPath);
_fileWatcher = new FileSystemWatcher(ServerStatsConfigDir);
_fileWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
_fileWatcher.Filter = "*.ini";
_fileWatcher.Changed += OnConfigFileChanged;
_fileWatcher.EnableRaisingEvents = true;
Console.WriteLine($"[ServerStats] Watching for config changes in: {ServerStatsConfigDir}");
}
catch (Exception ex)
{
Console.WriteLine($"[ServerStats] Failed to initialize file watcher: {ex.Message}");
}
}
private void OnConfigFileChanged(object sender, FileSystemEventArgs e)
{
if ((DateTime.UtcNow - _lastReloadTime).TotalSeconds < 1) return;
_lastReloadTime = DateTime.UtcNow;
if (e.Name != null && e.Name.Contains("workshop.ini"))
{
Server.NextFrame(LoadWorkshopIni);
}
else if (e.Name != null && e.Name.Contains("config.ini"))
{
Server.NextFrame(LoadConfigIni);
}
}
private void LoadConfigIni()
{
try
{
if (!Directory.Exists(ServerStatsConfigDir)) Directory.CreateDirectory(ServerStatsConfigDir);
if (!File.Exists(GeneralConfigPath))
{
string defaultConfig = @"// ServerStats General Configuration
UsesMatchLibrarian=true
// Announce when a player takes the lead in Zeus kills (true/false)
announce_zeus_leader=true
// Announce when a player gets an Ace (5 kills in a round) (true/false)
announce_aces=true
// Insert your Steam Web API Key below
api_key=
// Insert your Workshop Collection ID below
collection_id=";
File.WriteAllText(GeneralConfigPath, defaultConfig);
_usesMatchLibrarian = true;
_loadedCollectionId = "N/A";
_announceZeusLeader = true;
Console.WriteLine("[ServerStats] Created default config.ini.");
return;
}
foreach (var line in File.ReadAllLines(GeneralConfigPath))
{
var trimmed = line.Trim();
if (string.IsNullOrEmpty(trimmed) || trimmed.StartsWith("//") || trimmed.StartsWith("#")) continue;
var parts = trimmed.Split('=', 2);
if (parts.Length != 2) continue;
var key = parts[0].Trim();
var value = parts[1].Trim();
if (key.Equals("UsesMatchLibrarian", StringComparison.OrdinalIgnoreCase))
{
if (bool.TryParse(value, out bool result)) _usesMatchLibrarian = result;
}
else if (key.Equals("api_key", StringComparison.OrdinalIgnoreCase))
{
_steamApiKey = value;
}
else if (key.Equals("announce_zeus_leader", StringComparison.OrdinalIgnoreCase))
{
if (bool.TryParse(value, out bool result)) _announceZeusLeader = result;
}
else if (key.Equals("announce_aces", StringComparison.OrdinalIgnoreCase))
{
if (bool.TryParse(value, out bool result)) _announceAces = result;
}
else if (key.Equals("collection_id", StringComparison.OrdinalIgnoreCase))
{
_loadedCollectionId = value;
}
}
}
catch (Exception ex)
{
Console.WriteLine($"[ServerStats] Error loading config.ini: {ex.Message}");
}
}
private void LoadWorkshopIni()
{
_workshopMapIds.Clear();
_loadLog.Clear();
_loadLog.Add($"Reading workshop.ini from: {WorkshopIniPath}");
try
{
if (!Directory.Exists(ServerStatsConfigDir)) Directory.CreateDirectory(ServerStatsConfigDir);
if (!File.Exists(WorkshopIniPath))
{
string defaultWorkshop = @"// This file is automatically generated by ServerStats if api_key and collection_id are set in config.ini
// You can also manually add map=id pairs here.";
File.WriteAllText(WorkshopIniPath, defaultWorkshop);
_loadLog.Add("Created default workshop.ini.");
Console.WriteLine("[ServerStats] Created default workshop.ini.");
}
string[] lines = File.ReadAllLines(WorkshopIniPath);
foreach (string line in lines)
{
string trimmed = line.Trim();
if (string.IsNullOrEmpty(trimmed) || trimmed.StartsWith("//") || trimmed.StartsWith("#")) continue;
string[] parts = trimmed.Split('=');
if (parts.Length < 2) continue;
string key = parts[0].Trim();
string value = parts[1].Trim();
if (key.Equals("collection_id", StringComparison.OrdinalIgnoreCase))
{
}
else
{
if (!_workshopMapIds.ContainsKey(key))
{
_workshopMapIds.Add(key, value);
}
}
}
_loadLog.Add($"DONE: Loaded CollectionID: {_loadedCollectionId} | Mapped Maps: {_workshopMapIds.Count}");
Console.WriteLine($"[ServerStats] Loaded CollectionID: {_loadedCollectionId} and {_workshopMapIds.Count} map IDs.");
}
catch (Exception ex)
{
_loadLog.Add($"EXCEPTION: {ex.Message}");
Console.WriteLine($"[ServerStats] Exception loading workshop.ini: {ex.Message}");
}
}
private void CmdLog(CCSPlayerController? caller, CommandInfo info)
{
info.ReplyToCommand("--- workshop.ini Load Log ---");
foreach (var msg in _loadLog) info.ReplyToCommand(msg);
info.ReplyToCommand("--- End Log ---");
}
private bool IsWarmup()
{
try
{
var gameRulesProxy = Utilities.FindAllEntitiesByDesignerName<CCSGameRulesProxy>("cs_gamerules").FirstOrDefault();
if (gameRulesProxy == null || !gameRulesProxy.IsValid || gameRulesProxy.GameRules == null) return false;
return gameRulesProxy.GameRules.WarmupPeriod;
}
catch { return false; }
}
private HookResult OnRoundPrestart(EventRoundPrestart @event, GameEventInfo info)
{
bool isWarmup = IsWarmup();
_matchData.IsWarmup = isWarmup;
_roundStatsSnapshotTaken = false;
foreach (var kvp in _playerLookup)
{
kvp.Value.CurrentRoundKills = 0;
}
UpdateTeamScores();
// ONLY start a new match ID if the score is 0-0 and it is NOT warmup.
// This covers map changes (starts at 0-0), restartgame (resets to 0-0), etc.
if (!isWarmup && _ctWins == 0 && _tWins == 0)
{
// Logic to prevent re-triggering if we just started
// If total rounds recorded is > 0, we definitely need a reset.
// If total rounds is 0, we might have just reset.
// However, "StartNewMatchId" is cheap if the data is already empty.
// A simple way to verify if we *just* reset is checking if the list is empty.
// But we want to guarantee a new ID on 0-0.
// To avoid looping in the same round, we rely on the fact RoundPrestart fires once per round.
// If we have data from a previous match in memory, or if this is a fresh start event.
// We simply check if we have any round history. If we do, this 0-0 is definitely a new match.
// If we don't have round history, we can still reset to be safe and ensure the timestamp is fresh.
StartNewMatchId("Score Reset 0-0");
}
return HookResult.Continue;
}
private HookResult OnMapShutdown(EventMapShutdown @event, GameEventInfo info)
{
// Optional: Save on shutdown to prevent total data loss if server crashes,
// even though prompt said "only... on each round end".
// Generally safer to keep this, but respecting the prompt's focus on logic.
// I will leave it out to strictly follow "Only save updates... on each round end".
return HookResult.Continue;
}
private HookResult OnMatchEnd(EventCsWinPanelMatch @event, GameEventInfo info)
{
_matchEndedNormally = true;
_matchData.MatchComplete = true;
// Kill any outstanding timers that could fire during map transition
if (_noHumansRestartTimer != null) { _noHumansRestartTimer.Kill(); _noHumansRestartTimer = null; }
if (_spectatorKickTimer != null) { _spectatorKickTimer.Kill(); _spectatorKickTimer = null; }
try
{
if (!_roundStatsSnapshotTaken)
{
SnapshotRoundStats();
}
SaveMatchData();
Console.WriteLine($"[ServerStats] Match Finished. Final data saved for ID: {_matchData.MatchID}");
}
catch (Exception ex)
{
Console.WriteLine($"[ServerStats] OnMatchEnd error: {ex.Message}");
}
return HookResult.Continue;
}
private HookResult OnPlayerDisconnect(EventPlayerDisconnect @event, GameEventInfo info)
{
var player = @event.Userid;
if (player != null && !player.IsBot && !player.IsHLTV)
{
var remainingActiveHumans = Utilities.GetPlayers().Count(p =>
!p.IsBot &&
!p.IsHLTV &&
p.Slot != player.Slot &&
(p.TeamNum == 2 || p.TeamNum == 3));
if (remainingActiveHumans == 0 && _noHumansRestartTimer == null && !_matchEndedNormally)
{
Console.WriteLine("[ServerStats] No active humans detected. Scheduling restart in 90 seconds.");
_noHumansRestartTimer = AddTimer(90.0f, OnNoHumansRestartTimer, TimerFlags.STOP_ON_MAPCHANGE);
}
CheckAndHandlePlayerCounts(player.Slot);
}
return HookResult.Continue;
}
private HookResult OnPlayerTeam(EventPlayerTeam @event, GameEventInfo info)
{
Server.NextFrame(() => CheckAndHandlePlayerCounts());
return HookResult.Continue;
}
private void CheckAndHandlePlayerCounts(int? ignoreSlot = null)
{
var allPlayers = Utilities.GetPlayers();
int activeHumans = 0;
int specHumans = 0;
foreach (var p in allPlayers)
{
if (p == null || !p.IsValid || p.IsBot || p.IsHLTV) continue;
if (ignoreSlot.HasValue && p.Slot == ignoreSlot.Value) continue;
if (p.TeamNum == 2 || p.TeamNum == 3)
{
activeHumans++;
}
else if (p.TeamNum == 1)
{
specHumans++;
}
}
if (activeHumans == 0 && specHumans > 0)
{
if (_spectatorKickTimer == null)
{
Server.PrintToChatAll($" {ChatColors.Red}[SERVERSTATS] WARNING: NO ACTIVE PLAYERS. SPECTATORS WILL BE KICKED IN 30 SECONDS.");
_spectatorKickTimer = AddTimer(30.0f, KickSpectatorsAndRestart, TimerFlags.STOP_ON_MAPCHANGE);
}
}
else if (activeHumans > 0)
{
if (_spectatorKickTimer != null)
{
_spectatorKickTimer.Kill();
_spectatorKickTimer = null;
Server.PrintToChatAll(" [ServerStats] Active player joined. Spectator kick timer cancelled.");
}
CancelNoHumansRestartTimer();
}
else if (activeHumans == 0 && specHumans == 0 && _spectatorKickTimer != null)
{
_spectatorKickTimer.Kill();
_spectatorKickTimer = null;
}
}
private void CancelNoHumansRestartTimer()
{
if (_noHumansRestartTimer != null)
{
_noHumansRestartTimer.Kill();
_noHumansRestartTimer = null;
Console.WriteLine("[ServerStats] No-humans restart timer cancelled. Active players present.");
}
}