-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCS2SimpleVote.cs
More file actions
1622 lines (1404 loc) · 71.7 KB
/
CS2SimpleVote.cs
File metadata and controls
1622 lines (1404 loc) · 71.7 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 CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Attributes.Registration;
using CounterStrikeSharp.API.Modules.Commands;
using CounterStrikeSharp.API.Modules.Cvars;
using CounterStrikeSharp.API.Modules.Menu;
using CounterStrikeSharp.API.Modules.Timers;
using CounterStrikeSharp.API.Modules.Utils;
using System.Collections.Concurrent;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace CS2SimpleVote;
// --- Configuration ---
public class VoteConfig : BasePluginConfig
{
[JsonPropertyName("steam_api_key")] public string SteamApiKey { get; set; } = "YOUR_STEAM_API_KEY_HERE";
[JsonPropertyName("collection_id")] public string CollectionId { get; set; } = "123456789";
[JsonPropertyName("vote_round")] public int VoteRound { get; set; } = 10;
[JsonPropertyName("enable_rtv")] public bool EnableRtv { get; set; } = true;
[JsonPropertyName("enable_nominate")] public bool EnableNominate { get; set; } = true;
[JsonPropertyName("nominate_per_page")] public int NominatePerPage { get; set; } = 6;
[JsonPropertyName("rtv_percentage")] public float RtvPercentage { get; set; } = 0.60f;
[JsonPropertyName("rtv_change_delay")] public float RtvDelaySeconds { get; set; } = 5.0f;
[JsonPropertyName("vote_options_count")] public int VoteOptionsCount { get; set; } = 8;
[JsonPropertyName("vote_reminder_enabled")] public bool EnableReminders { get; set; } = true;
[JsonPropertyName("vote_reminder_interval")] public float ReminderIntervalSeconds { get; set; } = 30.0f;
// --- New Features ---
[JsonPropertyName("server_name")] public string ServerName { get; set; } = "My CS2 Server";
[JsonPropertyName("show_map_message")] public bool ShowCurrentMapMessage { get; set; } = true;
[JsonPropertyName("map_message_interval")] public float CurrentMapMessageInterval { get; set; } = 300.0f;
[JsonPropertyName("enable_recent_maps")] public bool EnableRecentMaps { get; set; } = true;
[JsonPropertyName("recent_maps_count")] public int RecentMapsCount { get; set; } = 5;
[JsonPropertyName("vote_open_for_rounds")] public int VoteOpenForRounds { get; set; } = 1;
[JsonPropertyName("show_midvote_progress")] public bool ShowMidVoteProgress { get; set; } = true;
[JsonPropertyName("admins")] public List<ulong> Admins { get; set; } = new();
}
public class MapItem
{
public string Id { get; set; } = "";
public string Name { get; set; } = "";
}
// --- Main Plugin ---
public class CS2SimpleVote : BasePlugin, IPluginConfig<VoteConfig>
{
public override string ModuleName => "CS2SimpleVote";
public override string ModuleVersion => "1.1.2";
private const string ColorDefault = "\x01";
private const string ColorGreen = "\x04";
public VoteConfig Config { get; set; } = new();
// Data Sources
private List<MapItem> _availableMaps = new();
private List<MapItem> _recentMaps = new();
private HttpClient _httpClient = new();
private CounterStrikeSharp.API.Modules.Timers.Timer? _reminderTimer;
private CounterStrikeSharp.API.Modules.Timers.Timer? _mapInfoTimer;
private CounterStrikeSharp.API.Modules.Timers.Timer? _centerMessageTimer;
// State: Voting
private bool _voteInProgress;
private bool _voteFinished;
private bool _isScheduledVote;
private int _currentVoteRoundDuration;
private bool _isForceVote;
private string? _previousWinningMapId;
private string? _previousWinningMapName;
private bool _matchEnded;
private bool _nextMapSetByAdmin;
private int _forceVoteTimeRemaining;
private string? _nextMapName;
private string? _pendingMapId;
private readonly HashSet<int> _rtvVoters = new();
private readonly Dictionary<int, string> _activeVoteOptions = new();
private readonly Dictionary<int, int> _playerVotes = new();
// State: Nomination
private readonly List<MapItem> _nominatedMaps = new();
private readonly HashSet<ulong> _hasNominatedSteamIds = new();
private readonly Dictionary<ulong, MapItem> _nominationOwner = new();
private readonly Dictionary<ulong, string> _nominationNames = new();
private readonly Dictionary<int, List<MapItem>> _nominatingPlayers = new();
private readonly Dictionary<int, int> _playerNominationPage = new();
private CommandInfo.CommandListenerCallback? _playerChatDelegate;
// State: Forcemap
private readonly Dictionary<int, List<MapItem>> _forcemapPlayers = new();
private readonly Dictionary<int, int> _playerForcemapPage = new();
// State: SetNextMap
private readonly Dictionary<int, List<MapItem>> _setnextmapPlayers = new();
private readonly Dictionary<int, int> _playerSetNextMapPage = new();
// Logger
private BlockingCollection<string> _logQueue = new();
private Task? _logTask;
private string _logFilePath = "";
// File Paths
private string _historyFilePath = "";
private string _cacheFilePath = "";
// Cancellation for background task
private CancellationTokenSource _cts = new();
// Flag to prevent execution after unload
private bool _unloaded = false;
private bool _hasLoadedCollectionMaps = false;
private bool _isApiLoading = false;
public void OnConfigParsed(VoteConfig config)
{
Config = config;
Config.VoteOptionsCount = Math.Clamp(Config.VoteOptionsCount, 2, 10);
if (Config.NominatePerPage < 1) Config.NominatePerPage = 6;
}
public override void Load(bool hotReload)
{
_unloaded = false;
// Reset all vote/match state on hot reload to prevent stale flags
// (ResetState normally only runs on OnMapStart, which doesn't fire on reload)
if (hotReload)
{
ResetState();
}
// Construct the path to the config folder manually:
// ModuleDirectory is ".../plugins/CS2SimpleVote"
// We want ".../configs/plugins/CS2SimpleVote"
string configDir = Path.GetFullPath(Path.Combine(ModuleDirectory, "../../configs/plugins/CS2SimpleVote"));
// If for some reason the folder structure is non-standard and that doesn't exist, fallback to ModuleDirectory
if (!Directory.Exists(configDir))
{
// Try to create it, if fail, use plugin folder
try { Directory.CreateDirectory(configDir); }
catch { configDir = ModuleDirectory; }
}
_historyFilePath = Path.Combine(configDir, "recent_maps.json");
_cacheFilePath = Path.Combine(configDir, "map_cache.json");
_logFilePath = Path.Combine(configDir, "CS2SimpleVote_debug.log");
StartLogWriter();
LogRoutine(new { hotReload }, null);
// Clear existing memory state before loading
_recentMaps.Clear();
// 1. Load Data Immediately (Sync)
LoadMapHistory();
LoadMapCache();
// 3. Start Background Update
Task.Run(() => FetchCollectionMaps(_cts.Token));
RegisterEventHandler<EventRoundStart>(OnRoundStart);
RegisterEventHandler<EventRoundEnd>(OnRoundEnd);
RegisterEventHandler<EventCsWinPanelMatch>(OnMatchEnd);
RegisterEventHandler<EventPlayerDisconnect>(OnPlayerDisconnect);
RegisterListener<Listeners.OnMapStart>(OnMapStart);
_playerChatDelegate = OnPlayerChat;
AddCommandListener("say", _playerChatDelegate, HookMode.Post);
AddCommandListener("say_team", _playerChatDelegate, HookMode.Post);
AddCommand("css_dumpmaps", "Dump all available map names to console", (caller, cmdInfo) =>
{
if (caller != null) { cmdInfo.ReplyToCommand("This command can only be used from the server console."); return; }
if (_availableMaps.Count == 0) { cmdInfo.ReplyToCommand("[CS2SimpleVote] No maps loaded yet. API may still be fetching."); return; }
cmdInfo.ReplyToCommand($"--- CS2SimpleVote: {_availableMaps.Count} Available Maps (Collection: {Config.CollectionId}) ---");
foreach (var map in _availableMaps.OrderBy(m => m.Name, StringComparer.OrdinalIgnoreCase))
{
cmdInfo.ReplyToCommand($" {map.Name} (ID: {map.Id})");
}
cmdInfo.ReplyToCommand($"--- End ({_availableMaps.Count} maps loaded) ---");
});
}
public override void Unload(bool hotReload)
{
LogRoutine(new { hotReload }, null);
_unloaded = true;
// 1. Cancel background tasks (FetchCollectionMaps) first
_cts.Cancel();
// 2. Kill all timers to prevent any further callbacks
_reminderTimer?.Kill();
_reminderTimer = null;
_mapInfoTimer?.Kill();
_mapInfoTimer = null;
_centerMessageTimer?.Kill();
_centerMessageTimer = null;
// 3. Complete the log queue so the log writer can drain and exit
try { _logQueue.CompleteAdding(); } catch (ObjectDisposedException) { }
// 4. Wait for the log writer task to finish (with timeout to avoid hanging)
if (_logTask != null)
{
try { _logTask.Wait(TimeSpan.FromSeconds(3)); } catch { /* timeout or cancelled, proceed */ }
_logTask = null;
}
// 5. Clear collections to release references
_availableMaps.Clear();
_recentMaps.Clear();
_rtvVoters.Clear();
_activeVoteOptions.Clear();
_playerVotes.Clear();
_nominatedMaps.Clear();
_hasNominatedSteamIds.Clear();
_nominationOwner.Clear();
_nominationNames.Clear();
_nominatingPlayers.Clear();
_playerNominationPage.Clear();
_forcemapPlayers.Clear();
_playerForcemapPage.Clear();
_setnextmapPlayers.Clear();
_playerSetNextMapPage.Clear();
// 6. Remove listeners and handlers
DeregisterEventHandler<EventRoundStart>(OnRoundStart);
DeregisterEventHandler<EventRoundEnd>(OnRoundEnd);
DeregisterEventHandler<EventCsWinPanelMatch>(OnMatchEnd);
DeregisterEventHandler<EventPlayerDisconnect>(OnPlayerDisconnect);
RemoveListener<Listeners.OnMapStart>(OnMapStart);
if (_playerChatDelegate != null)
{
RemoveCommandListener("say", _playerChatDelegate, HookMode.Post);
RemoveCommandListener("say_team", _playerChatDelegate, HookMode.Post);
_playerChatDelegate = null;
}
// 7. Dispose managed resources and recreate for potential hot reload
_cts.Dispose();
_cts = new CancellationTokenSource();
try { _logQueue.Dispose(); } catch { }
_logQueue = new BlockingCollection<string>();
try { _httpClient.Dispose(); } catch { }
_httpClient = new HttpClient();
}
private void OnMapStart(string mapName)
{
LogRoutine(new { mapName }, null);
ResetState();
Server.ExecuteCommand("mp_endmatch_votenextmap 0");
if (Config.EnableRecentMaps)
{
UpdateHistoryWithCurrentMap(mapName);
}
if (Config.ShowCurrentMapMessage && Config.CurrentMapMessageInterval > 0)
{
_mapInfoTimer = AddTimer(Config.CurrentMapMessageInterval, () =>
{
if (_unloaded) return;
// Find full title from available maps
string displayMapName = _availableMaps.FirstOrDefault(m => mapName.Contains(m.Name) || m.Id == mapName || mapName.Contains(m.Id))?.Name ?? mapName;
Server.PrintToChatAll($" {ColorDefault}You're playing {ColorGreen}{displayMapName}{ColorDefault} on {ColorGreen}{Config.ServerName}{ColorDefault}!");
}, TimerFlags.REPEAT | TimerFlags.STOP_ON_MAPCHANGE);
}
}
private void ResetState()
{
LogRoutine(new { }, null);
_matchEnded = false;
_nextMapSetByAdmin = false;
_voteInProgress = false;
_voteFinished = false;
_isScheduledVote = false;
_isForceVote = false;
_currentVoteRoundDuration = 0;
_nextMapName = null;
_pendingMapId = null;
_previousWinningMapId = null;
_previousWinningMapName = null;
_forceVoteTimeRemaining = 0;
_rtvVoters.Clear();
_playerVotes.Clear();
_activeVoteOptions.Clear();
_nominatedMaps.Clear();
_hasNominatedSteamIds.Clear();
_nominationOwner.Clear();
_nominationNames.Clear();
_nominatingPlayers.Clear();
_playerNominationPage.Clear();
_forcemapPlayers.Clear();
_playerForcemapPage.Clear();
_setnextmapPlayers.Clear();
_playerSetNextMapPage.Clear();
_reminderTimer?.Kill();
_reminderTimer = null;
_mapInfoTimer?.Kill();
_mapInfoTimer = null;
_centerMessageTimer?.Kill();
_centerMessageTimer = null;
}
// --- File Persistence ---
private void LoadMapHistory()
{
if (!File.Exists(_historyFilePath)) return;
string json = File.ReadAllText(_historyFilePath);
// Try loading the new MapItem format first
try
{
var loaded = JsonSerializer.Deserialize<List<MapItem>>(json);
if (loaded != null && loaded.Count > 0 && !string.IsNullOrEmpty(loaded[0].Id))
{
_recentMaps = loaded;
return;
}
}
catch { /* Not MapItem format, try legacy */ }
// Migrate legacy List<string> format
try
{
var legacyIds = JsonSerializer.Deserialize<List<string>>(json) ?? new List<string>();
_recentMaps = new List<MapItem>();
foreach (var raw in legacyIds)
{
string id = raw;
// Extract numeric ID from engine paths like "workshop/123456/de_map"
var segments = raw.Split('/');
if (segments.Length >= 2 && segments[0].Equals("workshop", StringComparison.OrdinalIgnoreCase)
&& segments[1].Length > 0 && segments[1].All(char.IsDigit))
{
id = segments[1];
}
_recentMaps.Add(new MapItem { Id = id, Name = id });
}
Console.WriteLine($"[CS2SimpleVote] Migrated {_recentMaps.Count} legacy recent map entries.");
}
catch { _recentMaps = new List<MapItem>(); }
}
private void SaveMapHistory()
{
try { File.WriteAllText(_historyFilePath, JsonSerializer.Serialize(_recentMaps)); }
catch (Exception ex) { Console.WriteLine($"[CS2SimpleVote] Failed to save history: {ex.Message}"); }
}
private void LoadMapCache()
{
if (File.Exists(_cacheFilePath))
{
try
{
var cached = JsonSerializer.Deserialize<List<MapItem>>(File.ReadAllText(_cacheFilePath));
if (cached != null) _availableMaps = cached;
}
catch { /* Ignore corrupt cache */ }
}
}
private void SaveMapCache()
{
try { File.WriteAllText(_cacheFilePath, JsonSerializer.Serialize(_availableMaps)); }
catch (Exception ex) { Console.WriteLine($"[CS2SimpleVote] Failed to save cache: {ex.Message}"); }
}
private void UpdateHistoryWithCurrentMap(string currentMapName)
{
LogRoutine(new { currentMapName }, null);
// Try to find the map by ID first (most reliable for workshop maps)
var mapItem = _availableMaps.FirstOrDefault(m => !string.IsNullOrEmpty(m.Id) && currentMapName.Contains(m.Id, StringComparison.OrdinalIgnoreCase));
// Fallback to name if not found by ID (for local maps or if ID isn't in path)
if (mapItem == null)
{
string cleanName = currentMapName.Split('/').Last();
mapItem = _availableMaps.FirstOrDefault(m => !string.IsNullOrEmpty(m.Name) && (cleanName.Equals(m.Name, StringComparison.OrdinalIgnoreCase) || m.Name.Contains(cleanName, StringComparison.OrdinalIgnoreCase) || cleanName.Contains(m.Name, StringComparison.OrdinalIgnoreCase) && m.Name.Length >= 4));
}
string idToAdd;
string nameToAdd;
if (mapItem != null)
{
idToAdd = mapItem.Id;
nameToAdd = mapItem.Name;
}
else
{
// Extract numeric workshop ID from engine paths like "workshop/3070321328/de_dust2"
var segments = currentMapName.Split('/');
if (segments.Length >= 2 && segments[0].Equals("workshop", StringComparison.OrdinalIgnoreCase)
&& segments[1].All(char.IsDigit) && segments[1].Length > 0)
{
idToAdd = segments[1];
}
else
{
idToAdd = currentMapName;
}
nameToAdd = idToAdd;
}
_recentMaps.RemoveAll(m => m.Id == idToAdd);
_recentMaps.Add(new MapItem { Id = idToAdd, Name = nameToAdd });
if (_recentMaps.Count > Config.RecentMapsCount) _recentMaps.RemoveAt(0);
SaveMapHistory();
// Backfill names for any legacy entries now that _availableMaps may be populated
for (int i = 0; i < _recentMaps.Count; i++)
{
if (_recentMaps[i].Name == _recentMaps[i].Id || string.IsNullOrEmpty(_recentMaps[i].Name))
{
var known = _availableMaps.FirstOrDefault(m => m.Id == _recentMaps[i].Id);
if (known != null) _recentMaps[i].Name = known.Name;
}
}
}
// --- Steam API ---
private async Task FetchCollectionMaps(CancellationToken token = default)
{
LogRoutine(new { token }, null);
if (string.IsNullOrEmpty(Config.SteamApiKey) || string.IsNullOrEmpty(Config.CollectionId)) return;
try
{
_isApiLoading = true;
var collContent = new FormUrlEncodedContent(new[] {
new KeyValuePair<string, string>("key", Config.SteamApiKey),
new KeyValuePair<string, string>("collectioncount", "1"),
new KeyValuePair<string, string>("publishedfileids[0]", Config.CollectionId)
});
var collRes = await _httpClient.PostAsync("https://api.steampowered.com/ISteamRemoteStorage/GetCollectionDetails/v1/", collContent, token);
string collJson = await collRes.Content.ReadAsStringAsync(token);
using var collDoc = JsonDocument.Parse(collJson);
var rootResp = collDoc.RootElement.GetProperty("response");
if (!rootResp.TryGetProperty("collectiondetails", out var collDetails) || collDetails.GetArrayLength() == 0)
{
throw new Exception("Invalid response or missing collection details from Steam API. Check Collection ID.");
}
var firstColl = collDetails[0];
if (!firstColl.TryGetProperty("children", out var children))
{
int resultObj = firstColl.TryGetProperty("result", out var resToken) ? resToken.GetInt32() : -1;
throw new Exception($"Collection has no children or is inaccessible. Steam result code: {resultObj}. Check if the Steam API Key is valid and collection is public.");
}
var fileIds = children.EnumerateArray()
.Select(c => c.GetProperty("publishedfileid").GetString())
.Where(id => !string.IsNullOrEmpty(id))
.Cast<string>()
.ToList();
if (fileIds.Count == 0) throw new Exception("No files found in collection.");
var itemPairs = new List<KeyValuePair<string, string>> {
new("key", Config.SteamApiKey),
new("itemcount", fileIds.Count.ToString())
};
for (int i = 0; i < fileIds.Count; i++) itemPairs.Add(new($"publishedfileids[{i}]", fileIds[i]));
var itemRes = await _httpClient.PostAsync("https://api.steampowered.com/ISteamRemoteStorage/GetPublishedFileDetails/v1/", new FormUrlEncodedContent(itemPairs), token);
string itemJson = await itemRes.Content.ReadAsStringAsync(token);
using var itemDoc = JsonDocument.Parse(itemJson);
var newMapList = new List<MapItem>();
var failedIds = new List<string>();
if (itemDoc.RootElement.TryGetProperty("response", out var itemResp) && itemResp.TryGetProperty("publishedfiledetails", out var pubDetails))
{
foreach (var item in pubDetails.EnumerateArray())
{
string? mapId = item.TryGetProperty("publishedfileid", out var idProp) ? idProp.GetString() : null;
string? mapName = item.TryGetProperty("title", out var titleProp) ? titleProp.GetString() : null;
if (string.IsNullOrEmpty(mapId))
{
Console.WriteLine($"[CS2SimpleVote] Skipped collection item: missing publishedfileid");
continue;
}
if (string.IsNullOrEmpty(mapName))
{
int result = item.TryGetProperty("result", out var resProp) ? resProp.GetInt32() : -1;
Console.WriteLine($"[CS2SimpleVote] Map ID {mapId} failed on legacy API (result code: {result}), will retry with modern API...");
failedIds.Add(mapId);
continue;
}
newMapList.Add(new MapItem { Id = mapId, Name = mapName });
}
}
// Retry failed items using the modern IPublishedFileService endpoint
if (failedIds.Count > 0)
{
Console.WriteLine($"[CS2SimpleVote] Retrying {failedIds.Count} item(s) via IPublishedFileService/GetDetails...");
try
{
var queryParts = new List<string> { $"key={Uri.EscapeDataString(Config.SteamApiKey)}" };
for (int i = 0; i < failedIds.Count; i++)
queryParts.Add($"publishedfileids%5B{i}%5D={failedIds[i]}");
var retryUrl = $"https://api.steampowered.com/IPublishedFileService/GetDetails/v1/?{string.Join("&", queryParts)}";
var retryRes = await _httpClient.GetAsync(retryUrl, token);
string retryJson = await retryRes.Content.ReadAsStringAsync(token);
using var retryDoc = JsonDocument.Parse(retryJson);
if (retryDoc.RootElement.TryGetProperty("response", out var retryResp) && retryResp.TryGetProperty("publishedfiledetails", out var retryDetails))
{
foreach (var item in retryDetails.EnumerateArray())
{
string? mapId = item.TryGetProperty("publishedfileid", out var ridProp) ? ridProp.GetString() : null;
string? mapName = item.TryGetProperty("title", out var rtitleProp) ? rtitleProp.GetString() : null;
if (!string.IsNullOrEmpty(mapId) && !string.IsNullOrEmpty(mapName))
{
Console.WriteLine($"[CS2SimpleVote] Recovered map via modern API: {mapName} (ID: {mapId})");
newMapList.Add(new MapItem { Id = mapId, Name = mapName });
}
else if (!string.IsNullOrEmpty(mapId))
{
Console.WriteLine($"[CS2SimpleVote] Map ID {mapId} also failed on modern API — item is likely deleted or banned");
}
}
}
}
catch (Exception retryEx)
{
Console.WriteLine($"[CS2SimpleVote] Modern API retry failed: {retryEx.Message}");
}
}
if (newMapList.Count < fileIds.Count)
{
Console.WriteLine($"[CS2SimpleVote] WARNING: {fileIds.Count - newMapList.Count} of {fileIds.Count} collection items could not be loaded");
}
_availableMaps = newMapList;
_hasLoadedCollectionMaps = true;
_isApiLoading = false;
Console.WriteLine($"[CS2SimpleVote] Updated {_availableMaps.Count} maps from Steam.");
SaveMapCache();
}
catch (OperationCanceledException)
{
_isApiLoading = false;
}
catch (ObjectDisposedException)
{
_isApiLoading = false;
// Plugin unloaded while fetching
}
catch (Exception ex)
{
_isApiLoading = false;
Console.WriteLine($"[CS2SimpleVote] Error API: {ex.Message}");
}
}
// --- Helpers ---
private bool IsValidPlayer(CCSPlayerController? player) => player != null && player.IsValid && !player.IsBot && !player.IsHLTV;
private bool IsWarmup()
{
try { return Utilities.FindAllEntitiesByDesignerName<CCSGameRulesProxy>("cs_gamerules").FirstOrDefault()?.GameRules?.WarmupPeriod ?? false; }
catch { return false; }
}
private bool IsCurrentMap(MapItem map) => Server.MapName.Contains(map.Id, StringComparison.OrdinalIgnoreCase) || Server.MapName.Equals(map.Name, StringComparison.OrdinalIgnoreCase);
private IEnumerable<CCSPlayerController> GetHumanPlayers() => Utilities.GetPlayers().Where(IsValidPlayer);
// --- Command Handlers (all handled via OnPlayerChat listener) ---
private HookResult OnPlayerChat(CCSPlayerController? player, CommandInfo info)
{
LogRoutine(new { player, info }, null);
if (_unloaded) return HookResult.Continue;
if (!IsValidPlayer(player)) return HookResult.Continue;
var p = player!;
string msg = info.GetArg(1).Trim();
string cleanMsg = msg.StartsWith("!") ? msg[1..] : msg;
// Parse command and potential arguments
string[] inputs = cleanMsg.Split(' ', 2);
string cmd = inputs[0];
string? args = inputs.Length > 1 ? inputs[1].Trim() : null;
if (_nominatingPlayers.ContainsKey(p.Slot)) return HandleNominationInput(p, cleanMsg);
if (_forcemapPlayers.ContainsKey(p.Slot)) return HandleForcemapInput(p, cleanMsg);
if (_setnextmapPlayers.ContainsKey(p.Slot)) return HandleSetNextMapInput(p, cleanMsg);
if (cmd.Equals("rtv", StringComparison.OrdinalIgnoreCase)) { Server.NextFrame(() => AttemptRtv(p)); return HookResult.Continue; }
if (cmd.Equals("nominatelist", StringComparison.OrdinalIgnoreCase)) { Server.NextFrame(() => PrintNominationList(p)); return HookResult.Continue; }
if (cmd.Equals("help", StringComparison.OrdinalIgnoreCase)) { Server.NextFrame(() => PrintHelp(p)); return HookResult.Continue; }
if (cmd.Equals("forcevote", StringComparison.OrdinalIgnoreCase)) { Server.NextFrame(() => AttemptForceVote(p)); return HookResult.Continue; }
if (cmd.Equals("finishvote", StringComparison.OrdinalIgnoreCase)) { Server.NextFrame(() => AttemptFinishVote(p)); return HookResult.Continue; }
if (cmd.Equals("endwarmup", StringComparison.OrdinalIgnoreCase)) { Server.NextFrame(() => AttemptEndWarmup(p)); return HookResult.Continue; }
if (cmd.Equals("votedebug", StringComparison.OrdinalIgnoreCase)) { Server.NextFrame(() => AttemptVoteDebug(p)); return HookResult.Continue; }
if (cmd.Equals("revote", StringComparison.OrdinalIgnoreCase)) { Server.NextFrame(() => AttemptRevote(p)); return HookResult.Continue; }
if (cmd.Equals("nextmap", StringComparison.OrdinalIgnoreCase)) { Server.NextFrame(() => PrintNextMap(p)); return HookResult.Continue; }
if (cmd.Equals("lastmap", StringComparison.OrdinalIgnoreCase)) { Server.NextFrame(() => PrintLastMap(p)); return HookResult.Continue; }
if (cmd.Equals("recentmaps", StringComparison.OrdinalIgnoreCase)) { Server.NextFrame(() => PrintRecentMaps(p, args)); return HookResult.Continue; }
if (cmd.Equals("nominate", StringComparison.OrdinalIgnoreCase) || cmd.Equals("nom", StringComparison.OrdinalIgnoreCase))
{
Server.NextFrame(() => AttemptNominate(p, args));
return HookResult.Continue;
}
if (cmd.Equals("forcemap", StringComparison.OrdinalIgnoreCase))
{
Server.NextFrame(() => AttemptForcemap(p, args));
return HookResult.Continue;
}
if (cmd.Equals("setnextmap", StringComparison.OrdinalIgnoreCase))
{
Server.NextFrame(() => AttemptSetNextMap(p, args));
return HookResult.Continue;
}
if (_voteInProgress) return HandleVoteInput(p, cleanMsg);
return HookResult.Continue;
}
// --- Logic ---
private void AttemptRevote(CCSPlayerController? player)
{
LogRoutine(new { player }, null);
if (!IsValidPlayer(player)) return;
if (!_voteInProgress) { player!.PrintToChat($" {ColorDefault}There is no vote currently in progress."); return; }
player!.PrintToChat($" {ColorDefault}Redisplaying vote options. You may recast your vote.");
PrintVoteOptionsToPlayer(player);
}
private void AttemptVoteDebug(CCSPlayerController? player)
{
if (player != null && !IsValidPlayer(player)) return;
bool isConsole = player == null;
if (!isConsole && !Config.Admins.Contains(player!.SteamID))
{
player.PrintToChat($" {ColorDefault}You do not have permission to use this command.");
return;
}
string loadedStatus = _hasLoadedCollectionMaps ? $"{ColorGreen}Loaded{ColorDefault}" : "Not Loaded";
string apiStatus = _isApiLoading ? "Loading..." : (_hasLoadedCollectionMaps ? $"{ColorGreen}Finished{ColorDefault}" : "Failed/Not Started");
string lastMapDisplay = _recentMaps.Count > 1 ? _recentMaps[_recentMaps.Count - 2].Name : "None";
var debugInfo = new List<string>
{
$" {ColorDefault}--- {ColorGreen}Vote Debug Info {ColorDefault}---",
$" {ColorDefault}Plugin Status: {ColorGreen}Active",
$" {ColorDefault}Maps Loaded: {loadedStatus} ({_availableMaps.Count} maps)",
$" {ColorDefault}Steam API Status: {apiStatus}",
$" {ColorDefault}Vote In Progress: {(_voteInProgress ? "Yes" : "No")}",
$" {ColorDefault}Vote Finished: {(_voteFinished ? "Yes" : "No")}",
$" {ColorDefault}Match Ended: {(_matchEnded ? "Yes" : "No")}",
$" {ColorDefault}RTV Voters: {_rtvVoters.Count}",
$" {ColorDefault}Nominated Maps: {_nominatedMaps.Count}",
$" {ColorDefault}Last Map: {ColorGreen}{lastMapDisplay}",
$" {ColorDefault}Target Collection ID: {Config.CollectionId}"
};
if (_activeVoteOptions.Count > 0)
{
debugInfo.Add($" {ColorDefault}--- {ColorGreen}Active Vote Data {ColorDefault}---");
foreach (var kvp in _activeVoteOptions)
{
int votes = _playerVotes.Values.Count(v => v == kvp.Key);
debugInfo.Add($" {ColorDefault}Option [{kvp.Key}] {ColorGreen}{GetMapName(kvp.Value)}{ColorDefault}: {votes} votes");
}
}
if (isConsole)
{
foreach (var line in debugInfo)
{
Console.WriteLine(line.Replace(ColorDefault, "").Replace(ColorGreen, ""));
}
}
else
{
foreach (var line in debugInfo)
{
player!.PrintToChat(line);
}
}
// Snapshot state for thread-safe dumping to avoid lagging the game server
var dumpState = new
{
State = new {
VoteInProgress = _voteInProgress,
VoteFinished = _voteFinished,
IsScheduledVote = _isScheduledVote,
CurrentVoteRoundDuration = _currentVoteRoundDuration,
IsForceVote = _isForceVote,
PreviousWinningMapId = _previousWinningMapId,
PreviousWinningMapName = _previousWinningMapName,
MatchEnded = _matchEnded,
ForceVoteTimeRemaining = _forceVoteTimeRemaining,
NextMapName = _nextMapName,
PendingMapId = _pendingMapId
},
Collections = new {
RtvVoters = _rtvVoters.ToList(),
ActiveVoteOptions = _activeVoteOptions.ToDictionary(k => k.Key.ToString(), v => v.Value),
PlayerVotes = _playerVotes.ToDictionary(k => k.Key.ToString(), v => v.Value),
NominatedMaps = _nominatedMaps.Select(m => new { m.Id, m.Name }).ToList(),
RecentMaps = _recentMaps.Select(m => new { m.Id, m.Name }).ToList()
}
};
// Offload large JSON serialization and console I/O to a background thread
Task.Run(() =>
{
try
{
string json = System.Text.Json.JsonSerializer.Serialize(dumpState, new System.Text.Json.JsonSerializerOptions { WriteIndented = true });
Console.WriteLine("\n[CS2SimpleVote] --- FULL MEMORY DUMP ---");
Console.WriteLine(json);
Console.WriteLine("[CS2SimpleVote] --- END DUMP ---\n");
}
catch (Exception ex)
{
Console.WriteLine($"\n[CS2SimpleVote] Error creating memory dump: {ex.Message}\n");
}
});
}
private void PrintHelp(CCSPlayerController? player)
{
LogRoutine(new { player }, null);
if (!IsValidPlayer(player)) return;
var p = player!;
bool isAdmin = Config.Admins.Contains(p.SteamID);
p.PrintToChat($" {ColorDefault}---{ColorGreen} CS2SimpleVote Commands {ColorDefault}---");
if (isAdmin)
{
p.PrintToChat($" {ColorGreen}!endwarmup {ColorDefault}- End the current warmup (Admin only)");
p.PrintToChat($" {ColorGreen}!finishvote {ColorDefault}- End an active vote early (Admin only)");
p.PrintToChat($" {ColorGreen}!forcemap [name] {ColorDefault}- Force change map (Admin only)");
p.PrintToChat($" {ColorGreen}!forcevote {ColorDefault}- Force start map vote (Admin only)");
p.PrintToChat($" {ColorGreen}!setnextmap [name] {ColorDefault}- Set the next map directly (Admin only)");
p.PrintToChat($" {ColorGreen}!votedebug {ColorDefault}- Show debug info (Admin only)");
}
p.PrintToChat($" {ColorGreen}!help {ColorDefault}- List available commands");
p.PrintToChat($" {ColorGreen}!lastmap {ColorDefault}- Show last played map");
p.PrintToChat($" {ColorGreen}!nextmap {ColorDefault}- Show next map");
p.PrintToChat($" {ColorGreen}!nominate [name] {ColorDefault}- Nominate a map");
p.PrintToChat($" {ColorGreen}!nominatelist {ColorDefault}- List nominated maps");
p.PrintToChat($" {ColorGreen}!recentmaps {ColorDefault}- Show recently played maps");
p.PrintToChat($" {ColorGreen}!revote {ColorDefault}- Recast vote");
p.PrintToChat($" {ColorGreen}!rtv {ColorDefault}- Rock the Vote");
}
private void PrintNominationList(CCSPlayerController? player)
{
LogRoutine(new { player }, null);
if (!IsValidPlayer(player)) return;
if (_nominatedMaps.Count == 0) { player!.PrintToChat($" {ColorDefault}No maps currently nominated."); return; }
player!.PrintToChat($" {ColorDefault}--- {ColorGreen}Nominated Maps ({_nominatedMaps.Count}/{Config.VoteOptionsCount}) {ColorDefault}---");
foreach (var map in _nominatedMaps)
{
var owner = _nominationOwner.FirstOrDefault(x => x.Value.Id == map.Id);
string nominator = (owner.Value != null && _nominationNames.TryGetValue(owner.Key, out var name)) ? name : "Unknown";
player.PrintToChat($" {ColorGreen} - {nominator} {ColorDefault}- {ColorGreen}{map.Name}");
}
}
private void PrintNextMap(CCSPlayerController? player)
{
LogRoutine(new { player }, null);
if (string.IsNullOrEmpty(_nextMapName)) { if (IsValidPlayer(player)) player!.PrintToChat($" {ColorDefault}The next map has not been decided yet."); return; }
Server.PrintToChatAll($" {ColorDefault}The next map will be: {ColorGreen}{_nextMapName}");
}
private void PrintLastMap(CCSPlayerController? player)
{
LogRoutine(new { player }, null);
if (_recentMaps.Count > 1)
{
// The current map is usually pushed to the end of _recentMaps upon OnMapStart.
// Meaning, the "last" map before the current one is at count - 2.
var lastMap = _recentMaps[_recentMaps.Count - 2];
Server.PrintToChatAll($" {ColorDefault}The last played map was: {ColorGreen}{lastMap.Name}");
}
else
{
if (IsValidPlayer(player)) player!.PrintToChat($" {ColorDefault}No previous map data found.");
}
}
private void PrintRecentMaps(CCSPlayerController? player, string? arg = null)
{
LogRoutine(new { player, arg }, null);
if (!IsValidPlayer(player)) return;
var p = player!;
if (_recentMaps.Count == 0 || (_recentMaps.Count == 1 && IsCurrentMap(_recentMaps[0])))
{
p.PrintToChat($" {ColorDefault}No recent maps data available yet.");
return;
}
int maxDisplayCount = Config.RecentMapsCount;
if (!string.IsNullOrEmpty(arg) && int.TryParse(arg, out int parsedLimit))
{
if (parsedLimit > 0 && parsedLimit <= Config.RecentMapsCount)
{
maxDisplayCount = parsedLimit;
}
else
{
p.PrintToChat($" {ColorDefault}Please enter a number between 1 and {Config.RecentMapsCount}.");
return;
}
}
string titleText = $"Last {maxDisplayCount} Recent Maps";
string dashes = new string('-', titleText.Length);
p.PrintToChat($" {ColorDefault}{dashes}");
p.PrintToChat($" {ColorGreen}{titleText}");
p.PrintToChat($" {ColorDefault}{dashes}");
var reversed = _recentMaps.AsEnumerable().Reverse().ToList();
// Print up to recent configurations limit. Skipping index 0 if it's the current map.
int displayCount = 1;
for(int i = 0; i < reversed.Count; i++)
{
if (displayCount > maxDisplayCount) break;
// Usually index 0 in the reversed list is the current active map because it gets appended to the end of the history.
// Let's filter out current map to show only purely *past* maps
if (IsCurrentMap(reversed[i])) continue;
p.PrintToChat($" {ColorGreen}{displayCount}. {ColorDefault}{reversed[i].Name}");
displayCount++;
}
}
private void AttemptRtv(CCSPlayerController? player)
{
LogRoutine(new { player }, null);
if (!IsValidPlayer(player)) return;
var p = player!;
if (IsWarmup()) { p.PrintToChat($" {ColorDefault}RTV is disabled during warmup."); return; }
if (!Config.EnableRtv) { p.PrintToChat($" {ColorDefault}RTV is currently disabled."); return; }
if (_voteInProgress || _voteFinished) return;
if (!_rtvVoters.Add(p.Slot)) { p.PrintToChat($" {ColorDefault}You have already rocked the vote."); return; }
int currentPlayers = GetHumanPlayers().Count();
int votesNeeded = (int)Math.Ceiling(currentPlayers * Config.RtvPercentage);
Server.PrintToChatAll($" {ColorDefault}{ColorGreen}{p.PlayerName}{ColorDefault} wants to change the map! ({_rtvVoters.Count}/{votesNeeded})");
if (_rtvVoters.Count >= votesNeeded) { Server.PrintToChatAll($" {ColorDefault}RTV Threshold reached! Starting vote..."); StartMapVote(isRtv: true); }
}
private void AttemptNominate(CCSPlayerController? player, string? searchTerm = null)
{
LogRoutine(new { player, searchTerm }, null);
if (!IsValidPlayer(player)) return;
var p = player!;
if (!Config.EnableNominate) { p.PrintToChat($" {ColorDefault}Nominations are currently disabled."); return; }
if (_voteInProgress || _voteFinished) { p.PrintToChat($" {ColorDefault}Voting has already finished."); return; }
bool isRenomination = _hasNominatedSteamIds.Contains(p.SteamID);
if (!isRenomination && _nominatedMaps.Count >= Config.VoteOptionsCount) { p.PrintToChat($" {ColorDefault}The nomination list is full!"); return; }
var validMaps = _availableMaps
.Where(m => !_nominatedMaps.Any(n => n.Id == m.Id))
.Where(m => !IsCurrentMap(m))
.ToList();
if (!string.IsNullOrEmpty(searchTerm))
{
validMaps = validMaps.Where(m => m.Name.Contains(searchTerm, StringComparison.OrdinalIgnoreCase)).ToList();
}
if (validMaps.Count == 0)
{
p.PrintToChat(string.IsNullOrEmpty(searchTerm) ? $" {ColorDefault}No maps available to nominate." : $" {ColorDefault}No maps found matching: {ColorGreen}{searchTerm}");
return;
}
// If there is only one match and a search term was used, nominate it immediately
if (validMaps.Count == 1 && !string.IsNullOrEmpty(searchTerm))
{
var selectedMap = validMaps[0];
if (_nominatedMaps.Any(m => m.Id == selectedMap.Id))
{
p.PrintToChat($" {ColorDefault}That map is already nominated.");
}
else
{
ProcessNomination(p, selectedMap);
}
return;
}
_nominatingPlayers[p.Slot] = validMaps;
_playerNominationPage[p.Slot] = 0;
DisplayNominationMenu(p);
}
private void DisplayNominationMenu(CCSPlayerController player)
{
if (!_nominatingPlayers.TryGetValue(player.Slot, out var maps)) return;
int page = _playerNominationPage.GetValueOrDefault(player.Slot, 0);
int totalPages = (int)Math.Ceiling((double)maps.Count / Config.NominatePerPage);
if (page >= totalPages) page = 0;
_playerNominationPage[player.Slot] = page;
int startIndex = page * Config.NominatePerPage;
int endIndex = Math.Min(startIndex + Config.NominatePerPage, maps.Count);
player.PrintToChat($" {ColorDefault}Page {page + 1}/{totalPages}. Type number to select (or 'cancel'):");
for (int i = startIndex; i < endIndex; i++) { int displayNum = (i - startIndex) + 1; player.PrintToChat($" {ColorGreen}[{displayNum}] {ColorDefault}{maps[i].Name}"); }
if (totalPages > 1) player.PrintToChat($" {ColorGreen}[0] {ColorDefault}Next Page");
}
private HookResult HandleNominationInput(CCSPlayerController player, string input)
{
LogRoutine(new { player, input }, null);
if (input.Equals("cancel", StringComparison.OrdinalIgnoreCase)) { CloseNominationMenu(player); player.PrintToChat($" {ColorDefault}Nomination cancelled."); return HookResult.Handled; }
if (input == "0") { _playerNominationPage[player.Slot]++; DisplayNominationMenu(player); return HookResult.Handled; }
if (int.TryParse(input, out int selection))
{
var maps = _nominatingPlayers[player.Slot];
int page = _playerNominationPage[player.Slot];
int realIndex = (page * Config.NominatePerPage) + (selection - 1);
if (realIndex >= 0 && realIndex < maps.Count && realIndex >= (page * Config.NominatePerPage) && realIndex < ((page + 1) * Config.NominatePerPage))
{
var selectedMap = maps[realIndex];
bool isRenomination = _hasNominatedSteamIds.Contains(player.SteamID);
if (!isRenomination && _nominatedMaps.Count >= Config.VoteOptionsCount) player.PrintToChat($" {ColorDefault}Nomination list is full.");
else if (_nominatedMaps.Any(m => m.Id == selectedMap.Id)) player.PrintToChat($" {ColorDefault}That map was just nominated by someone else.");
else { ProcessNomination(player, selectedMap); }
CloseNominationMenu(player);
return HookResult.Handled;
}
}
return HookResult.Continue;
}
private void ProcessNomination(CCSPlayerController player, MapItem map)
{
LogRoutine(new { player, map }, null);
_nominationNames[player.SteamID] = player.PlayerName;
if (_hasNominatedSteamIds.Contains(player.SteamID))
{
if (_nominationOwner.TryGetValue(player.SteamID, out var oldMap))
{
_nominatedMaps.RemoveAll(m => m.Id == oldMap.Id);
}
_nominatedMaps.Add(map);
_nominationOwner[player.SteamID] = map;
Server.PrintToChatAll($" {ColorDefault}Player {ColorGreen}{player.PlayerName}{ColorDefault} changed their nomination to {ColorGreen}{map.Name}{ColorDefault}.");
}
else
{
_nominatedMaps.Add(map);
_hasNominatedSteamIds.Add(player.SteamID);
_nominationOwner[player.SteamID] = map;
Server.PrintToChatAll($" {ColorDefault}Player {ColorGreen}{player.PlayerName}{ColorDefault} nominated {ColorGreen}{map.Name}{ColorDefault}.");
}
}