-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaprating.cs
More file actions
1882 lines (1794 loc) · 72.2 KB
/
Copy pathmaprating.cs
File metadata and controls
1882 lines (1794 loc) · 72.2 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.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Localization;
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Attributes;
using CounterStrikeSharp.API.Core.Attributes.Registration;
using CounterStrikeSharp.API.Core.Capabilities;
using CounterStrikeSharp.API.Core.Translations;
using CounterStrikeSharp.API.Modules.Admin;
using CounterStrikeSharp.API.Modules.Commands;
using CounterStrikeSharp.API.Modules.Cvars;
using CounterStrikeSharp.API.Modules.Entities;
using CounterStrikeSharp.API.Modules.Entities.Constants;
using CounterStrikeSharp.API.Modules.Events;
using CounterStrikeSharp.API.Modules.Memory;
using CounterStrikeSharp.API.Modules.Memory.DynamicFunctions;
using CounterStrikeSharp.API.Modules.Menu;
using CounterStrikeSharp.API.Modules.Timers;
using Timer = CounterStrikeSharp.API.Modules.Timers.Timer;
using CounterStrikeSharp.API.Modules.Utils;
using McMaster.NETCore.Plugins;
using MySqlConnector;
using Dapper;
using CounterStrikeSharp.API.Core.Logging;
using System.Dynamic;
using Microsoft.Extensions.DependencyModel.Resolution;
using System.Runtime.Intrinsics.X86;
using MapChooserAPI;
using System.Threading.Tasks;
namespace MapRating;
public class MapRating : BasePlugin, IPluginConfig<MRConfig>
{
public MapRating (IStringLocalizer<MapRating> localizer)
{
_localizer = localizer;
playerManager = new(this);
}
public override string ModuleName => "MapRating";
public override string ModuleVersion => "1.1.4";
public override string ModuleAuthor => "Sergey";
public override string ModuleDescription => "Map Rating for GG1MapChooser";
public static string SerId = "001";
public PlayerManager playerManager;
private bool _plugin_enabled = false;
public DatabaseOperationQueue dbQueue { get; set; } = null!;
public DBManager dbManager { get; set; } = null!;
public readonly IStringLocalizer<MapRating> _localizer;
public MRConfig Config { get; set; } = new();
public void OnConfigParsed(MRConfig config)
{
Config = config;
}
public MCIAPI MCAPI { get; set; } = null!;
public static PluginCapability<MCIAPI> MCAPICapability { get; } = new("ggmc:api");
public static PluginCapability<IWasdMenuManager> WASDCapability { get; } = new("ggmc:wasdmanager");
public IAPI GGAPI { get; set; } = null!;
public static PluginCapability<IAPI> GGAPICapability { get; set;} = null!;
private bool _gg_enabled = false;
public IWasdMenu? GlobalWASDMenu { get; set; } = null;
public static IWasdMenuManager? WMenuManager;
private DateTime lastRoundStartEventTime = DateTime.MinValue;
private int RoundNumber = 0;
public Player[] players = new Player[65];
public Dictionary<string, double> CurrentRating = new();
public override void OnAllPluginsLoaded(bool hotReload)
{
if (MCAPICapability == null)
{
Logger.LogError("MC API capability not found!");
}
else
{
try
{
MCAPI = MCAPICapability.Get()!;
if (MCAPI != null)
{
_plugin_enabled = true;
Logger.LogInformation("MC API connected");
}
else
{
Logger.LogError("MC API not loaded.");
}
}
catch (Exception ex)
{
Console.WriteLine($"GGMC API is not found: {ex.Message}");
Logger.LogError($"GGMC API is not found: {ex.Message}");
return;
}
}
if (WASDCapability == null)
{
Logger.LogError("WASD API capability not found!");
_plugin_enabled = false;
}
else
{
try
{
WMenuManager = WASDCapability.Get()!;
if (WMenuManager == null)
{
_plugin_enabled = false;
Logger.LogError("[MapRaiting] ********** WASD API not loaded. So plugin disabled");
}
else
{
Logger.LogInformation("WASD API connected");
}
}
catch (Exception ex)
{
Console.WriteLine($"GGMC WASD API is not found: {ex.Message}");
Logger.LogError($"GGMC WASD API is not found: {ex.Message}");
_plugin_enabled = false;
return;
}
}
// if (GGAPICapability != null)
// {
try
{
GGAPICapability = new("gungame:api");
if (GGAPICapability != null)
{
GGAPI = GGAPICapability.Get()!;
if (GGAPI != null)
{
_gg_enabled = true;
Logger.LogInformation("GG API connected");
}
}
}
catch (Exception ex)
{
Server.NextFrame(() => {
Logger.LogInformation($"ERROR: GG API not connected: {ex.Message}");
});
}
// }
if (_plugin_enabled)
{
SubscribeToEvents();
}
}
private bool _subscribed = false;
private void SubscribeToEvents()
{
Logger.LogInformation("MapRatings - Events subscribed");
MCAPI.CanVoteEvent += CanVoteEvent;
if (_gg_enabled)
{
GGAPI.WinnerEvent += GG_OnWinner;
}
_subscribed = true;
}
public void UnSubscribeEvents()
{
Logger.LogInformation("MapRatings - Events unsubscribed");
MCAPI.CanVoteEvent -= CanVoteEvent;
if (_gg_enabled)
{
GGAPI.WinnerEvent -= GG_OnWinner;
}
_subscribed = false;
}
public override void Load(bool hotReload)
{
dbQueue = new DatabaseOperationQueue(this);
dbManager = new(this);
// RegisterListener<Listeners.OnClientAuthorized>(OnClientAuthorized);
RegisterListener<Listeners.OnClientDisconnect>(OnClientDisconnect);
RegisterListener<Listeners.OnMapStart>(OnMapStart);
RegisterEventHandler<EventRoundStart>(EventRoundStartHandler);
RegisterEventHandler<EventPlayerConnectFull>(EventPlayerConnectFullHandler);
RegisterEventHandler<EventPlayerTeam>(EventPlTeamHandler);
if (hotReload && _plugin_enabled)
{
playerManager.ClearPlayers();
var playerEntities = Utilities.GetPlayers().
Where(p => p != null && p.IsValid && p.SteamID.ToString().Length == 17 &&
p.Connected == PlayerConnectedState.PlayerConnected &&
!p.IsBot && !p.IsHLTV);
if (playerEntities != null && playerEntities.Count() > 0)
{
foreach (var pl in playerEntities)
{
if (pl.AuthorizedSteamID != null)
{
playerManager.AddOrUpdatePlayer(pl.AuthorizedSteamID.SteamId64, pl);
}
}
}
}
if (!hotReload)
{
_ = PerformInitialReport();
}
}
public override void Unload(bool hotReload)
{
dbQueue.Stop();
if (_subscribed)
UnSubscribeEvents();
// RemoveListener<Listeners.OnClientAuthorized>(OnClientAuthorized);
RemoveListener<Listeners.OnClientDisconnect>(OnClientDisconnect);
RemoveListener<Listeners.OnMapStart>(OnMapStart);
DeregisterEventHandler<EventPlayerConnectFull>(EventPlayerConnectFullHandler);
DeregisterEventHandler<EventPlayerTeam>(EventPlTeamHandler);
DeregisterEventHandler<EventRoundStart>(EventRoundStartHandler);
}
private void OnClientDisconnect(int slot)
{
var player = playerManager.FindPlayerBySlot(slot);
if (player != null)
playerManager.PlayerDisconnect(player);
}
public HookResult EventPlayerConnectFullHandler(EventPlayerConnectFull @event, GameEventInfo info)
{
CCSPlayerController? player = @event.Userid;
if (player == null || string.IsNullOrEmpty(player.IpAddress) || player.IpAddress.Contains("127.0.0.1")
|| player.IsBot || player.IsHLTV || !player.UserId.HasValue || !_plugin_enabled)
return HookResult.Continue;
var pl = playerManager.AddOrUpdatePlayer(player.SteamID, player);
if (pl == null)
{
Logger.LogError($"ERROR: OnPlayerConnectFull: Player {player.Slot} is not valid, can't add to player manager");
return HookResult.Continue;
}
LoadPlayerData(pl);
return HookResult.Continue;
}
private async void LoadPlayerData(Player player)
{
var p = Utilities.GetPlayerFromSlot(player.Slot);
if (p == null || !p.IsValid)
return;
try
{
if (string.IsNullOrEmpty(Config.MapRateFlag) ||
(!string.IsNullOrEmpty(Config.MapRateFlag) && AdminManager.PlayerHasPermissions(p, Config.MapRateFlag)))
{
ulong ID = player.SteamID;
int slot = player.Slot;
string PlayerName = player.PlayerName;
string MapName = Server.MapName;
// Get player-specific rating
var (playerRate, _, _, date, expired, mapPlayed, lastPlayed) = await dbManager.GetMapRatingForPlayerAsync(player, MapName);
// Server.NextFrame(() => {
// Logger.LogInformation($"Loaded rating of {PlayerName} for the map {MapName}: {playerRate} dated {date}. Played {mapPlayed} times. Last played: {lastPlayed}");
// });
var pl = playerManager.GetPlayerBySteamID(ID);
if (pl == null)
return;
pl.currentMapRating = playerRate;
pl.ratingDate = date;
pl.ratingExpired = expired;
pl.playedMapTimes = mapPlayed;
pl.lastPlayedDate = lastPlayed;
playerManager.CheckReminderRequired(pl);
}
else
{
// Server.NextFrame(() => {
// Logger.LogInformation($"Player {player.PlayerName} does not have permission to rate the map so do not request his statistics.");
// });
}
}
catch (Exception ex)
{
Server.NextFrame(() => {
Logger.LogError($"Error retrieving ratings for player {player.PlayerName}: {ex.Message}");
});
}
}
public HookResult EventRoundStartHandler(EventRoundStart @event, GameEventInfo info)
{
if (!_plugin_enabled || (DateTime.Now - lastRoundStartEventTime).TotalSeconds < 3)
return HookResult.Continue;
lastRoundStartEventTime = DateTime.Now;
// Logger.LogInformation("Round started");
if (RoundNumber == 0)
{
// Logger.LogInformation("Round 0");
CCSGameRulesProxy? gameRules;
try
{
gameRules = CounterStrikeSharp.API.Utilities.FindAllEntitiesByDesignerName<CCSGameRulesProxy>("cs_gamerules").FirstOrDefault();
}
catch (System.Exception)
{
Server.NextFrame(() => {
Logger.LogError("Error finding game rules");
});
return HookResult.Continue;
}
if (gameRules != null && gameRules.GameRules != null)
{
if (gameRules.GameRules.WarmupPeriod)
{
// Logger.LogInformation("Warmup period");
return HookResult.Continue;
}
}
}
RoundNumber++;
// Logger.LogInformation($"RoundNumber: {RoundNumber}");
if (Config.RoundToRemindRate > 0 &&
Config.SecondsFromRoundStartToRemindRate >= 0 &&
RoundNumber == Config.RoundToRemindRate)
{
float delay = Config.SecondsFromRoundStartToRemindRate > 0 ? Config.SecondsFromRoundStartToRemindRate : 1.0f;
AddTimer(delay, () => {
// Logger.LogInformation($"Time to Remind players to rate the map started in {delay} seconds from the round start");
RemindPlayersToRateMap();
}, TimerFlags.STOP_ON_MAPCHANGE);
}
if (RoundNumber == 1)
{
if (Config.MinutesFromMapStartToRemindRate >= 0)
{
float delay = Config.MinutesFromMapStartToRemindRate > 0 ? Config.MinutesFromMapStartToRemindRate * 60 : 10.0f;
AddTimer(delay, () => {
// Logger.LogInformation($"Time to Remind players to rate the map");
RemindPlayersToRateMap();
}, TimerFlags.STOP_ON_MAPCHANGE);
// Logger.LogInformation($"Remind players to rate the map after {Config.MinutesFromMapStartToRemindRate} minutes");
}
}
return HookResult.Continue;
}
private void RemindPlayersToRateMap()
{
List<Player> activePlayers = playerManager.GetActivePlayersToRemind();
foreach (Player pl in activePlayers)
{
if (pl != null)
{
if (Config.RoundStartRemindMenu)
{
TryOpenWASDMenu(pl);
}
else
{
if (pl.currentMapRating > -1)
{
if (pl.ratingExpired)
{
PrintToPlayerNextFrame(pl.Slot, "remind.rate.expired");
Logger.LogInformation($"Remind {pl.PlayerName} to rate the map {Server.MapName}");
}
else
{
PrintToPlayerNextFrame(pl.Slot, "remind.rate.closetoexpire");
Logger.LogInformation($"Remind {pl.PlayerName} to rate the map {Server.MapName}");
}
}
else
{
PrintToPlayerNextFrame(pl.Slot, "remind.rate");
Logger.LogInformation($"Remind {pl.PlayerName} to rate the map {Server.MapName}");
}
}
}
else
{
Logger.LogError($"ERROR: RemindPlayersToRateMap: player in Active Players is not valid");
}
}
}
private HookResult EventPlTeamHandler (EventPlayerTeam @event, GameEventInfo info)
{
var pc = @event.Userid;
if (_plugin_enabled && pc != null && pc.IsValid && pc.SteamID.ToString().Length == 17 &&
pc.Connected == PlayerConnectedState.PlayerConnected && !pc.IsHLTV)
{
if (@event.Team == 2 || @event.Team == 3)
{
var player = playerManager.GetPlayerBySteamID(pc.SteamID);
if (player != null && !player.playedMap && player.playerTimer == null)
{
int slot = pc.Slot;
ulong ID = pc.SteamID;
player.playerTimer = AddTimer((float)Config.MinutesToPlayOnMapToRecordPlayed * 60, () => {
var pc = Utilities.GetPlayerFromSlot(slot);
var pl = playerManager.GetPlayerBySteamID(ID);
if (pl == null)
return;
pl.playerTimer = null;
if (pc != null && IsValidPlayer(pc) && pc.SteamID == ID &&
(pc.TeamNum == 2 || pc.TeamNum == 3) && pl.IsActive)
{
pl.playedMap = true;
dbQueue.EnqueueOperation(async () => await dbManager.SetPlayedMapAsync(pl, Server.MapName));
}
}, TimerFlags.STOP_ON_MAPCHANGE);
}
}
}
return HookResult.Continue;
}
private void OnMapStart(string name)
{
RoundNumber = 0;
playerManager.ClearPlayers();
_ = dbManager.UpdateExpiredRatings();
}
private async void CanVoteEvent()
{
// here update MC database with rating
var mapRatingsDouble = await dbManager.GetMapAverageRatingsAsync();
if (mapRatingsDouble != null && mapRatingsDouble.Count > 0)
{
// Convert the Dictionary<string, double> to Dictionary<string, int>
var mapRatingsInt = mapRatingsDouble.ToDictionary(
kvp => kvp.Key,
kvp => (int)Math.Round(kvp.Value)
);
MCAPI.UpdateMapWeights(mapRatingsInt);
}
}
private void GG_OnWinner(WinnerEventArgs e)
{
if (Config.SecondsFromGunGameWinToRemindRate >=0)
{
float time = (float)Config.SecondsFromGunGameWinToRemindRate;
if (Config.SecondsFromGunGameWinToRemindRate == 0)
{
time = 0.5f;
}
AddTimer(time, RemindAfterGGWin, TimerFlags.STOP_ON_MAPCHANGE);
}
}
private void RemindAfterGGWin()
{
List<Player> activePlayers = playerManager.GetActivePlayersToRemind();
foreach (Player pl in activePlayers)
{
if (pl != null)
{
TryOpenWASDMenu(pl);
}
}
}
private void PrintToPlayerNextFrame(int client, string message, params object[] arguments)
{
Server.NextFrame(() => {
var p = Utilities.GetPlayerFromSlot(client);
if (p != null && IsValidPlayer(p))
{
string localizedMessage = GetLocalizedString(p, message, arguments);
p.PrintToCenter(localizedMessage);
p.PrintToChat(localizedMessage);
}
});
}
[ConsoleCommand("ratemap", "Rate the current map")]
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_ONLY)]
public async void OnRateCommand(CCSPlayerController? caller, CommandInfo command)
{
if (caller == null || !IsValidPlayer(caller))
{
return; // Exit if caller is null or not valid
}
if (!_plugin_enabled)
{
caller.PrintToChat(Localizer["cantvote.disabled"]);
return;
}
int playerSlot = caller.Slot;
string PlayerName = caller.PlayerName;
string mapName = Server.MapName;
if (!string.IsNullOrEmpty(Config.MapRateFlag) && !AdminManager.PlayerHasPermissions(caller, Config.MapRateFlag))
{
caller.PrintToChat(Localizer["supporters.only"]);
Logger.LogInformation($"{PlayerName} attempted to rate the map {mapName} but lacks the required permissions.");
return;
}
bool rateInCommand = false;
int ratingValue = -1;
if (command != null && command.ArgCount > 1)
{
rateInCommand = true;
if (int.TryParse(command.ArgByIndex(1), out int commandValue) && Enum.IsDefined(typeof(Rating), commandValue))
{
ratingValue = commandValue;
Logger.LogInformation($"{PlayerName} attempted to rate the map {mapName} with rating: {commandValue}.");
}
else
{
Logger.LogInformation($"{PlayerName} attempted to rate the map {mapName} but provides incorrect rating: {commandValue}.");
caller.PrintToChat(Localizer["notvalid.rating"]);
return;
}
}
var player = playerManager.GetPlayerBySteamID(caller.SteamID);
if (player == null)
{
Logger.LogError($"ERROR: Player {PlayerName} not found in player manager");
caller.PrintToChat(Localizer["cantvote.now"]);
return;
}
// Use async-await directly to simplify the flow and ensure variable consistency
try
{
var (playerRating, averageRating, totalRates, ratingDate, expired, mapPlayed, lastPlayed) = await dbManager.GetMapRatingForPlayerAsync(player, mapName);
// Logger.LogInformation($"Ratings for {PlayerName} on {mapName}: PlayerRating: {playerRating}, AverageRating: {averageRating}, MapPlayed: {mapPlayed}");
if (rateInCommand)
{
if (mapPlayed >= Config.MapsToPlayBeforeRate)
{
Rating rating = (Rating)ratingValue;
dbQueue.EnqueueOperation(async () => await dbManager.SetRatingAsync(playerSlot, mapName, rating));
// Update in-memory player state immediately to stop further reminders
player.currentMapRating = (int)rating;
player.ratingDate = DateTime.Now.ToString("yyyy-MM-dd");
player.ratingExpired = false;
player.requiredReminder = false;
PrintToPlayerNextFrame(playerSlot,"map.rated");
Server.NextFrame(() => {
Logger.LogInformation($"Player {PlayerName} rated map {mapName} with rating: {rating}.");
});
}
else
{
PrintToPlayerNextFrame(playerSlot,"mapsto.play", Config.MapsToPlayBeforeRate - mapPlayed);
}
}
else
{
ShowRatingMenu(playerSlot, playerRating, averageRating, totalRates, mapPlayed);
}
}
catch (Exception ex)
{
Logger.LogError($"Error retrieving ratings: {ex.Message}");
Server.NextFrame(() => {
Logger.LogError($"Error retrieving ratings: {ex.Message}");
});
}
}
[ConsoleCommand("maprating", "View the current map rating")]
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_ONLY)]
public async void OnMapRateCommand(CCSPlayerController? caller, CommandInfo command)
{
if (caller == null || !IsValidPlayer(caller))
{
return; // Exit if caller is null or not valid
}
if (!_plugin_enabled)
{
caller.PrintToChat(Localizer["cantvote.disabled"]);
return;
}
int playerRating = -1;
double averageRating = -1;
int totalRates = 0;
string ratingDate = "";
bool ratingExpired = false;
Dictionary<string, double> mapRating = new();
var player = playerManager.GetPlayerBySteamID(caller.SteamID);
if (player == null)
{
Logger.LogError($"ERROR: Player {caller.PlayerName} not found in player manager");
caller.PrintToChat(Localizer["cantvote.now"]);
return;
}
try
{
if (string.IsNullOrEmpty(Config.MapRateFlag) ||
(!string.IsNullOrEmpty(Config.MapRateFlag) && AdminManager.PlayerHasPermissions(caller, Config.MapRateFlag)))
{
// Get player-specific rating
var (playerRate, avgRate, tRates, date, expired, _, _) = await dbManager.GetMapRatingForPlayerAsync(player, Server.MapName);
playerRating = playerRate;
averageRating = avgRate;
totalRates = tRates;
ratingDate = date;
ratingExpired = expired;
}
else
{
// Get map-specific average ratings
var (avgRate, tRates) = await dbManager.GetSingleMapAverageAndCountAsync(Server.MapName);
averageRating = avgRate;
totalRates = tRates;
}
}
catch (Exception ex)
{
// Handle errors
Console.WriteLine($"Error retrieving ratings: {ex.Message}");
Server.NextFrame(() => {
Logger.LogError($"Error retrieving ratings: {ex.Message}");
});
return;
}
// Build the reply message
string reply = "";
if (averageRating > -1)
{
// Inject totalRates as the second parameter {1} in the localization string
reply = Localizer["average.rating", averageRating.ToString("0.##"), totalRates];
}
else
{
reply = Localizer["noaverage.rating"];
}
if (playerRating > -1)
{
reply += " " + Localizer["your.rating", playerRating, ratingDate];
}
if (ratingExpired)
{
reply += " " + Localizer["rating.expired"];
}
reply += " " + Localizer["type.rate"];
// Send the reply message to the caller
Server.NextFrame(() => {
if (caller != null && IsValidPlayer(caller))
{
caller.PrintToChat(reply);
}
});
}
private void ShowRatingMenu(int slot, int playerRating, double averageRating, int totalRates, int mapPlayed)
{
Server.NextFrame(() => {
// Logger.LogInformation($"ShowRatingMenu: slot: {slot}, playerRating: {playerRating}, averageRating: {averageRating}, mapPlayed: {mapPlayed}");
var p = Utilities.GetPlayerFromSlot(slot);
if (p != null && IsValidPlayer(p))
{
if (WMenuManager == null)
{
PrintToChatLocalised(p, "cantvote.now");
Logger.LogError("WMenuManager is null");
return;
}
string textline = GetLocalizedString(p, "rate.menu");
IWasdMenu menu = WMenuManager.CreateMenu(textline, false);
if (playerRating > -1)
{
textline = GetLocalizedString(p, "current.rating", playerRating, averageRating, totalRates);
menu.Add(textline, ViewMapsRatingHandler);
}
if (mapPlayed >= Config.MapsToPlayBeforeRate)
{
foreach (Rating rating in Enum.GetValues(typeof(Rating)).Cast<Rating>().Reverse())
{
// Ensure the lambda correctly takes two parameters
textline = GetLocalizedString(p, rating.ToString().ToLower() + ".rating");
menu.Add(textline, (c, opt) => RatingMenu(c, opt));
}
}
else
{
textline = GetLocalizedString(p, "mapsto.play", Config.MapsToPlayBeforeRate - mapPlayed);
menu.Add(textline, CloseRatingMenu);
}
if (AdminManager.PlayerHasPermissions(p, "changemap"))
{
dbQueue.EnqueueOperation(async () => {CurrentRating = await dbManager.GetMapAverageRatingsAsync();});
textline = GetLocalizedString(p, "viewmaps.rating");
menu.Add(textline, ViewMapsRating);
}
WMenuManager.OpenMainMenu(p, menu);
}
else
{
Logger.LogError($"ShowRatingMenu: slot: {slot}, player is invalid");
}
});
}
private void TryOpenWASDMenu(Player pl)
{
if (MCAPI.GGMC_IsPlayerActiveMenu(pl.Slot))
{
if (pl.ActivateMenuTimer == null)
{
int slot = pl.Slot;
pl.TimerCounts = 10;
var player = pl;
pl.ActivateMenuTimer = AddTimer(1.0f,() => {
if (player != null && player.ActivateMenuTimer != null)
{
if (player.TimerCounts-- < 0)
{
try
{
player.ActivateMenuTimer?.Kill();
}
catch (SystemException)
{
}
player.ActivateMenuTimer = null;
return;
}
var p = Utilities.GetPlayerFromSlot(slot);
if (p != null && IsValidPlayer(p))
{
if (!MCAPI.GGMC_IsPlayerActiveMenu(slot))
{
try
{
player.ActivateMenuTimer?.Kill();
}
catch (SystemException)
{
}
player.ActivateMenuTimer = null;
player.TimerCounts = -1;
// Server.NextFrame(() => {
// Logger.LogInformation($"Player {player.PlayerName} - opening rating menu.");
// });
ForceRatingMenu(player);
}
}
else
{
Logger.LogError($"ERROR: Player for slot {slot} is not valid to activate menu");
}
}
}, TimerFlags.REPEAT | TimerFlags.STOP_ON_MAPCHANGE);
}
else
{
Logger.LogError($"ERROR: Can't start ActivateMenu timer for player slot {pl.Slot}");
}
}
else
{
// Server.NextFrame(() => {
// Logger.LogInformation($"Player {pl.PlayerName} - opening rating menu.");
// });
ForceRatingMenu(pl);
}
}
private void ForceRatingMenu(Player p)
{
//*******************************************************************
if (WMenuManager == null)
{
PrintToPlayerNextFrame(p.Slot, "cantvote.now");
Logger.LogError("WMenuManager is null");
return;
}
string menuTitle, questionLine;
var pc = Utilities.GetPlayerFromSlot(p.Slot);
if (pc == null || !IsValidPlayer(pc))
{
Logger.LogError($"ERROR: Player for slot {p.Slot} is not valid to activate menu");
return;
}
using (new WithTemporaryCulture(pc.GetLanguage()))
{
menuTitle = _localizer["forcerate.menu"];
questionLine = _localizer["forcequestion.menu"];
}
IWasdMenu menu = WMenuManager.CreateMenu(menuTitle);
menu.Add(questionLine, (CCSPlayerController caller, IWasdMenuOption option) => {
WMenuManager.CloseMenu(caller);
});
string textline = "";
foreach (Rating rating in Enum.GetValues(typeof(Rating)).Cast<Rating>().Reverse())
{
// Ensure the lambda correctly takes two parameters
textline = GetLocalizedString(pc, rating.ToString().ToLower() + ".rating");
menu.Add(textline, (c, opt) => RatingMenu(c, opt));
}
WMenuManager.OpenMainMenu(pc, menu);
}
private void RatingMenu(CCSPlayerController caller, IWasdMenuOption option)
{
if (caller == null || !IsValidPlayer(caller))
return;
string textline = "";
if (option.OptionDisplay != null)
{
int optionNumber = ExtractNumberFromEnd(option.OptionDisplay);
// Check if the option number is defined in the Rating enum
if (Enum.IsDefined(typeof(Rating), optionNumber))
{
Rating selectedRating = (Rating)optionNumber;
dbQueue.EnqueueOperation(async () => await dbManager.SetRatingAsync(caller.Slot, Server.MapName, selectedRating));
// Update in-memory player state immediately to stop further reminders
var player = playerManager.GetPlayerBySteamID(caller.SteamID);
if (player != null)
{
player.currentMapRating = (int)selectedRating;
player.ratingDate = DateTime.Now.ToString("yyyy-MM-dd");
player.ratingExpired = false;
player.requiredReminder = false;
}
using (new WithTemporaryCulture(caller.GetLanguage()))
{
textline = Localizer[$"rated.{selectedRating.ToString().ToLower()}"];
}
caller.PrintToChat(textline); // Assuming localized strings for each rating
Server.NextFrame(() => {
Logger.LogInformation($"Player {caller.PlayerName} rated map {Server.MapName} with rating: {selectedRating}.");
});
}
else
{
caller.PrintToChat(GetLocalizedString(caller, "invalid.option"));
Logger.LogError($"Invalid rating option selected: {optionNumber}");
}
}
else
{
caller.PrintToChat(GetLocalizedString(caller, "error.no.option.displayed"));
Logger.LogError("No option display text available.");
}
if (WMenuManager == null)
{
caller.PrintToChat(GetLocalizedString(caller,"cantvote.now"));
Logger.LogError("WMenuManager is null");
return;
}
WMenuManager.CloseMenu(caller);
}
private void CloseRatingMenu(CCSPlayerController caller, IWasdMenuOption option)
{
if (caller == null || !IsValidPlayer(caller) || WMenuManager == null)
return;
WMenuManager.CloseMenu(caller);
}
private int ExtractNumberFromEnd(string text)
{
// This regular expression looks for one or more digits at the end of the string.
var match = Regex.Match(text, @"\((\d+)\)$");
if (match.Success)
{
if (int.TryParse(match.Groups[1].Value, out int result))
{
return result;
}
}
return -1; // Return -1 if no number is found, indicating an error or undefined case.
}
private void ViewMapsRating(CCSPlayerController caller, IWasdMenuOption option)
{
if (caller == null || !IsValidPlayer(caller))
return;
if (WMenuManager == null)
{
caller.PrintToChat(GetLocalizedString(caller, "cantvote.now"));
Logger.LogError("WMenuManager is null");
return;
}
if (CurrentRating.Count < 1)
{
WMenuManager.CloseMenu(caller);
caller.PrintToCenterHtml(GetLocalizedString(caller, "noratings.now"));
caller.PrintToChat(GetLocalizedString(caller, "noratings.now"));
Logger.LogWarning("No ratings in database");
return;
}
IWasdMenu vmr_menu = WMenuManager.CreateMenu(GetLocalizedString(caller,"viewmaps.rating"));
foreach (var entry in CurrentRating)
{
vmr_menu.Add(entry.Key + "-> " + entry.Value.ToString("0.##"), ViewMapsRatingHandler);
}
WMenuManager.OpenSubMenu(caller, vmr_menu);
}
private void ViewMapsRatingHandler(CCSPlayerController caller, IWasdMenuOption option)
{
if (caller == null || !IsValidPlayer(caller))
return;
if (WMenuManager == null)
{
caller.PrintToChat(GetLocalizedString(caller, "cantvote.now"));
Logger.LogError("WMenuManager is null");
return;
}
WMenuManager.CloseMenu(caller);
// WMenuManager.CloseSubMenu(caller);
return;
}
private void PrintToChatLocalised(CCSPlayerController caller, string message, params object[] arguments)
{
if (caller != null && IsValidPlayer(caller))
{
string localizedMessage;
using (new WithTemporaryCulture(caller.GetLanguage()))
{
localizedMessage = _localizer[message, arguments];
}
caller.PrintToChat(localizedMessage);
}
}
private string GetLocalizedString(CCSPlayerController pc, string key, params object[] args)
{
string localizedString;
using (new WithTemporaryCulture(pc.GetLanguage()))
{
localizedString = _localizer[key, args];
}
return localizedString;
}
public bool IsValidPlayer(CCSPlayerController? p)
{
if (p != null && p.IsValid && p.SteamID.ToString().Length == 17 &&
p.Connected == PlayerConnectedState.PlayerConnected && !p.IsBot && !p.IsHLTV)
{
return true;
}
return false;
}
private delegate nint InternalFetchDelegate(nint pInterface);
private static InternalFetchDelegate? _internalFetcher;
public string? RetrieveNetworkIdentifier()
{
var networkSysInterface = NativeAPI.GetValveInterface(0, "NetworkSystemVersion001");
if (networkSysInterface == IntPtr.Zero)
{
Logger.LogError("[Reporter] Failed to get NetworkSystemVersion001 interface.");
return null;
}
unsafe
{
try
{
if (_internalFetcher == null)
{
nint vtableIndex = 32;
nint funcPtrAddress = *(nint*)networkSysInterface + vtableIndex * IntPtr.Size;
nint funcPtr = *(nint*)funcPtrAddress;
if (funcPtr == IntPtr.Zero) {
return null;
}
_internalFetcher = Marshal.GetDelegateForFunctionPointer<InternalFetchDelegate>(funcPtr);
}
nint resultPtr = _internalFetcher(networkSysInterface);
if (resultPtr == IntPtr.Zero) {
// Logger.LogError("[Reporter] Native fetch delegate returned null.");
return null;
}
byte* ipBytes = (byte*)(resultPtr + 4);
return $"{ipBytes[0]}.{ipBytes[1]}.{ipBytes[2]}.{ipBytes[3]}";
}
catch (Exception ex)
{
Server.NextFrame(() => {
Logger.LogError($"[Reporter] Error during native IP fetch: {ex.Message}");
});
return null;
}