-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerAdminController.cs
More file actions
1447 lines (1241 loc) · 64.4 KB
/
ServerAdminController.cs
File metadata and controls
1447 lines (1241 loc) · 64.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 Microsoft.ApplicationInsights;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MX.GeoLocation.Api.Client.V1;
using Newtonsoft.Json;
using XtremeIdiots.Portal.Integrations.Forums;
using XtremeIdiots.Portal.Integrations.Servers.Abstractions.Models.V1;
using XtremeIdiots.Portal.Integrations.Servers.Abstractions.Models.V1.Rcon;
using XtremeIdiots.Portal.Integrations.Servers.Api.Client.V1;
using XtremeIdiots.Portal.Repository.Abstractions.Constants.V1;
using XtremeIdiots.Portal.Repository.Abstractions.Models.V1.AdminActions;
using XtremeIdiots.Portal.Repository.Abstractions.Models.V1.GameServers;
using XtremeIdiots.Portal.Repository.Abstractions.Models.V1.Maps;
using XtremeIdiots.Portal.Repository.Abstractions.Models.V1.Players;
using XtremeIdiots.Portal.Repository.Api.Client.V1;
using XtremeIdiots.Portal.Web.Auth.Constants;
using XtremeIdiots.Portal.Web.Extensions;
using XtremeIdiots.Portal.Web.Models;
using XtremeIdiots.Portal.Web.Services;
using XtremeIdiots.Portal.Web.ViewModels;
namespace XtremeIdiots.Portal.Web.Controllers;
/// <summary>
/// Controller for server administration functionality including RCON commands and chat log management
/// </summary>
/// <remarks>
/// Initializes a new instance of the ServerAdminController
/// </remarks>
/// <param name="authorizationService">Service for handling authorization policies</param>
/// <param name="repositoryApiClient">Client for accessing repository data</param>
/// <param name="serversApiClient">Client for server RCON operations</param>
/// <param name="telemetryClient">Client for tracking telemetry events</param>
/// <param name="logger">Logger instance for this controller</param>
/// <param name="configuration">Application configuration</param>
[Authorize(Policy = AuthPolicies.AccessServerAdmin)]
public class ServerAdminController(
IAuthorizationService authorizationService,
IRepositoryApiClient repositoryApiClient,
IServersApiClient serversApiClient,
IGeoLocationApiClient geoLocationClient,
IProxyCheckService proxyCheckService,
IAdminActionTopics adminActionTopics,
TelemetryClient telemetryClient,
ILogger<ServerAdminController> logger,
IConfiguration configuration) : BaseController(telemetryClient, logger, configuration)
{
private readonly string forumBaseUrl = (configuration["XtremeIdiots:Forums:TopicBaseUrl"] ?? "https://www.xtremeidiots.com/forums/topic/").TrimEnd('/') + "/";
private readonly string fallbackAdminId = configuration["XtremeIdiots:Forums:DefaultAdminUserId"] ?? "21145";
private readonly int tempBanDurationDays = int.TryParse(configuration["XtremeIdiots:Forums:DefaultTempBanDays"], out var days) ? days : 7;
/// <summary>
/// Displays the main server administration dashboard with available game servers
/// </summary>
/// <param name="cancellationToken">Cancellation token for the request</param>
/// <returns>View with list of administrable game servers</returns>
[HttpGet]
public async Task<IActionResult> Index(CancellationToken cancellationToken = default)
{
return await ExecuteWithErrorHandlingAsync(async () =>
{
string[] requiredClaims = [UserProfileClaimType.SeniorAdmin, UserProfileClaimType.HeadAdmin, UserProfileClaimType.GameAdmin, UserProfileClaimType.ServerAdmin];
var (gameTypes, gameServerIds) = User.ClaimedGamesAndItemsForViewing(requiredClaims);
var gameServersApiResponse = await repositoryApiClient.GameServers.V1.GetGameServers(
gameTypes, gameServerIds, GameServerFilter.LiveTrackingEnabled, 0, 50,
GameServerOrder.BannerServerListPosition, cancellationToken).ConfigureAwait(false);
if (!gameServersApiResponse.IsSuccess || gameServersApiResponse.Result?.Data?.Items is null)
{
Logger.LogError("Failed to retrieve game servers for server admin dashboard for user {UserId}", User.XtremeIdiotsId());
return RedirectToAction("Display", "Errors", new { id = 500 });
}
var results = gameServersApiResponse.Result.Data.Items.Select(gs => new ServerAdminGameServerViewModel
{
GameServer = gs,
GameServerQueryStatus = new ServerQueryStatusResponseDto(),
GameServerRconStatus = new ServerRconStatusResponseDto()
}).ToList();
Logger.LogInformation("Successfully loaded {Count} game servers for user {UserId} server admin dashboard",
results.Count, User.XtremeIdiotsId());
return View(results);
}, nameof(Index)).ConfigureAwait(false);
}
/// <summary>
/// Helper method to retrieve and authorize access to a game server
/// </summary>
/// <param name="id">Game server ID</param>
/// <param name="action">Action being performed for logging</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Tuple containing potential action result for unauthorized access and game server data</returns>
private async Task<(IActionResult? ActionResult, GameServerDto? GameServer)> GetAuthorizedGameServerAsync(
Guid id,
string action,
CancellationToken cancellationToken = default)
{
var gameServerApiResponse = await repositoryApiClient.GameServers.V1.GetGameServer(id, cancellationToken).ConfigureAwait(false);
if (gameServerApiResponse.IsNotFound || gameServerApiResponse.Result?.Data is null)
{
Logger.LogWarning("Game server {ServerId} not found when {Action}", id, action);
return (NotFound(), null);
}
var gameServerData = gameServerApiResponse.Result.Data;
var authResult = await CheckAuthorizationAsync(
authorizationService,
gameServerData.GameType,
AuthPolicies.ViewLiveRcon,
action,
"GameServer",
$"ServerId:{id},GameType:{gameServerData.GameType}",
gameServerData).ConfigureAwait(false);
return authResult is not null ? (authResult, null) : (null, gameServerData);
}
/// <summary>
/// Displays the RCON interface for a specific game server
/// </summary>
/// <param name="id">Game server ID</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>RCON interface view for the server</returns>
[HttpGet]
public async Task<IActionResult> ViewRcon(Guid id, CancellationToken cancellationToken = default)
{
return await ExecuteWithErrorHandlingAsync(async () =>
{
var (actionResult, gameServerData) = await GetAuthorizedGameServerAsync(id, nameof(ViewRcon), cancellationToken).ConfigureAwait(false);
return actionResult is not null ? actionResult : View(gameServerData);
}, nameof(ViewRcon)).ConfigureAwait(false);
}
/// <summary>
/// Gets enriched RCON player data including profiles, IP geolocation, and risk assessment
/// </summary>
/// <param name="id">Game server ID</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>JSON with enriched player data for DataTables</returns>
[HttpGet]
public async Task<IActionResult> GetRconPlayers(Guid id, CancellationToken cancellationToken = default)
{
return await ExecuteWithErrorHandlingAsync(async () =>
{
var (actionResult, gameServerData) = await GetAuthorizedGameServerAsync(id, nameof(GetRconPlayers), cancellationToken).ConfigureAwait(false);
if (actionResult is not null)
return actionResult;
var getServerStatusResult = await serversApiClient.Rcon.V1.GetServerStatus(id).ConfigureAwait(false);
if (!getServerStatusResult.IsSuccess || getServerStatusResult.Result?.Data?.Players is null)
{
return Json(new { data = Array.Empty<object>() });
}
var rconPlayers = getServerStatusResult.Result.Data.Players;
List<object> enrichedPlayers = [];
foreach (var rconPlayer in rconPlayers)
{
var enrichedPlayer = await EnrichRconPlayerDataAsync(rconPlayer, gameServerData!.GameType, cancellationToken).ConfigureAwait(false);
enrichedPlayers.Add(enrichedPlayer);
}
return Json(new { data = enrichedPlayers });
}, nameof(GetRconPlayers)).ConfigureAwait(false);
}
/// <summary>
/// Enriches RCON player data with profile information, geolocation, and risk assessment
/// </summary>
/// <param name="rconPlayer">The RCON player data from the game server</param>
/// <param name="gameType">The type of game being played</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Enriched player data object with additional context</returns>
private async Task<object> EnrichRconPlayerDataAsync(dynamic rconPlayer, GameType gameType, CancellationToken cancellationToken)
{
PlayerDto? playerProfile = null;
string? countryCode = null;
ProxyCheckResult? proxyCheck = null;
// Try to find existing player profile by GUID
string guid = rconPlayer.Guid?.ToString() ?? string.Empty;
if (!string.IsNullOrWhiteSpace(guid))
{
try
{
// Search for player by GUID using GetPlayers with filter
var playerResponse = await repositoryApiClient.Players.V1.GetPlayers(
gameType, null, guid, 0, 1, PlayersOrder.LastSeenDesc, PlayerEntityOptions.None).ConfigureAwait(false);
if (playerResponse.IsSuccess && playerResponse.Result?.Data?.Items?.Any() == true)
{
playerProfile = playerResponse.Result.Data.Items.First();
}
}
catch (Exception ex)
{
Logger.LogWarning(ex, "Failed to retrieve player profile for GUID {Guid}", guid);
}
}
// Get IP address enrichment data
string ipAddress = rconPlayer.IpAddress?.ToString() ?? string.Empty;
if (!string.IsNullOrWhiteSpace(ipAddress))
{
try
{
// Get geolocation country code
var geoResponse = await geoLocationClient.GeoLookup.V1.GetGeoLocation(ipAddress, cancellationToken).ConfigureAwait(false);
if (geoResponse.IsSuccess && geoResponse.Result?.Data is not null)
{
countryCode = geoResponse.Result.Data.CountryCode;
}
}
catch (Exception ex)
{
Logger.LogDebug(ex, "Failed to retrieve geolocation for IP {IpAddress}", ipAddress);
}
try
{
// Get ProxyCheck risk assessment
proxyCheck = await proxyCheckService.GetIpRiskDataAsync(ipAddress, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
Logger.LogDebug(ex, "Failed to retrieve proxy check data for IP {IpAddress}", ipAddress);
}
}
return new
{
num = rconPlayer.Num,
name = rconPlayer.Name?.ToString() ?? string.Empty,
guid = guid,
ipAddress = ipAddress,
rate = rconPlayer.Rate,
playerId = playerProfile?.PlayerId,
username = playerProfile?.Username,
countryCode,
proxyCheckRiskScore = proxyCheck?.RiskScore ?? 0,
isProxy = proxyCheck?.IsProxy ?? false,
isVpn = proxyCheck?.IsVpn ?? false,
proxyType = proxyCheck?.Type ?? string.Empty
};
}
/// <summary>
/// Gets the server status including current map and player count
/// </summary>
/// <param name="id">Game server ID</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>JSON with server status data</returns>
[HttpGet]
public async Task<IActionResult> GetServerStatus(Guid id, CancellationToken cancellationToken = default)
{
return await ExecuteWithErrorHandlingAsync(async () =>
{
var (actionResult, gameServerData) = await GetAuthorizedGameServerAsync(id, nameof(GetServerStatus), cancellationToken).ConfigureAwait(false);
if (actionResult is not null)
return actionResult;
var getServerStatusResult = await serversApiClient.Rcon.V1.GetServerStatus(id).ConfigureAwait(false);
if (!getServerStatusResult.IsSuccess || getServerStatusResult.Result?.Data is null)
{
return Json(new { success = false, message = "Failed to get server status" });
}
var status = getServerStatusResult.Result.Data;
// Get current map image from repository
string? mapImageUri = null;
string? currentMapName = null;
// Try to get map name from status data (property name may vary)
try
{
// Attempt to get map name from dynamic status object
var statusDynamic = (dynamic)status;
// Try various property names that different games might use
currentMapName = statusDynamic.MapName?.ToString() ?? statusDynamic.Map?.ToString() ?? statusDynamic.mapname?.ToString() ?? statusDynamic.map?.ToString() ?? null;
// Log what properties are available for debugging
if (string.IsNullOrWhiteSpace(currentMapName))
{
var statusJson = JsonConvert.SerializeObject(status);
Logger.LogDebug("Server status for {ServerId}: {Status}", id, statusJson);
}
}
catch (Exception ex)
{
Logger.LogWarning(ex, "Failed to extract map name from server status for {ServerId}", id);
}
if (string.IsNullOrWhiteSpace(currentMapName)) currentMapName = "Unknown";
if (!string.IsNullOrWhiteSpace(currentMapName) &&
currentMapName != "Unknown")
{
var mapsApiResponse = await repositoryApiClient.Maps.V1.GetMaps(
gameServerData!.GameType,
[currentMapName],
null, null, 0, 1, MapsOrder.MapNameAsc, cancellationToken).ConfigureAwait(false);
mapImageUri = mapsApiResponse.Result?.Data?.Items?.FirstOrDefault()?.MapImageUri;
}
var playerCount = status.Players?.Count ?? 0;
return Json(new
{
success = true,
currentMap = currentMapName,
mapImageUri,
playerCount,
maxPlayers = 32, // Default, could be from server config
hostname = gameServerData!.Hostname,
gameType = gameServerData.GameType.ToString()
});
}, nameof(GetServerStatus)).ConfigureAwait(false);
}
/// <summary>
/// Gets the current map information from the server using the new dedicated endpoint
/// </summary>
/// <param name="id">Game server ID</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>JSON with current map information including map name and image URI</returns>
[HttpGet]
public async Task<IActionResult> GetCurrentMap(Guid id, CancellationToken cancellationToken = default)
{
return await ExecuteWithErrorHandlingAsync(async () =>
{
var (actionResult, gameServerData) = await GetAuthorizedGameServerAsync(id, nameof(GetCurrentMap), cancellationToken).ConfigureAwait(false);
if (actionResult is not null)
return actionResult;
var getCurrentMapResult = await serversApiClient.Rcon.V1.GetCurrentMap(id).ConfigureAwait(false);
if (!getCurrentMapResult.IsSuccess || getCurrentMapResult.Result?.Data is null)
{
return Json(new { success = false, message = "Failed to get current map" });
}
var currentMapDto = getCurrentMapResult.Result.Data;
var currentMapName = currentMapDto.MapName;
// Get current map image from repository
string? mapImageUri = null;
if (!string.IsNullOrWhiteSpace(currentMapName))
{
var mapsApiResponse = await repositoryApiClient.Maps.V1.GetMaps(
gameServerData!.GameType,
[currentMapName],
null, null, 0, 1, MapsOrder.MapNameAsc, cancellationToken).ConfigureAwait(false);
mapImageUri = mapsApiResponse.Result?.Data?.Items?.FirstOrDefault()?.MapImageUri;
}
return Json(new
{
success = true,
currentMap = currentMapName,
mapImageUri
});
}, nameof(GetCurrentMap)).ConfigureAwait(false);
}
/// <summary>
/// Gets raw server information from RCON for display in the UI tooltip
/// </summary>
/// <param name="id">Game server ID</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>JSON with raw server info text</returns>
[HttpGet]
public async Task<IActionResult> GetServerInfo(Guid id, CancellationToken cancellationToken = default)
{
return await ExecuteWithErrorHandlingAsync(async () =>
{
var (actionResult, gameServerData) = await GetAuthorizedGameServerAsync(id, nameof(GetServerInfo), cancellationToken).ConfigureAwait(false);
if (actionResult is not null)
return actionResult;
var getServerInfoResult = await serversApiClient.Rcon.V1.GetServerInfo(id).ConfigureAwait(false);
if (!getServerInfoResult.IsSuccess || getServerInfoResult.Result?.Data is null)
{
return Json(new { success = false, message = "Failed to get server info" });
}
var serverInfo = getServerInfoResult.Result.Data;
return Json(new { success = true, serverInfo });
}, nameof(GetServerInfo)).ConfigureAwait(false);
}
/// <summary>
/// Gets raw system information from RCON for display in the UI
/// </summary>
/// <param name="id">Game server ID</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>JSON with raw system info text</returns>
[HttpGet]
public async Task<IActionResult> GetSystemInfo(Guid id, CancellationToken cancellationToken = default)
{
return await ExecuteWithErrorHandlingAsync(async () =>
{
var (actionResult, gameServerData) = await GetAuthorizedGameServerAsync(id, nameof(GetSystemInfo), cancellationToken).ConfigureAwait(false);
if (actionResult is not null)
return actionResult;
var getSystemInfoResult = await serversApiClient.Rcon.V1.GetSystemInfo(id).ConfigureAwait(false);
if (!getSystemInfoResult.IsSuccess || getSystemInfoResult.Result?.Data is null)
{
return Json(new { success = false, message = "Failed to get system info" });
}
var systemInfo = getSystemInfoResult.Result.Data;
return Json(new { success = true, systemInfo });
}, nameof(GetSystemInfo)).ConfigureAwait(false);
}
/// <summary>
/// Gets raw command list from RCON for display in the UI
/// </summary>
/// <param name="id">Game server ID</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>JSON with raw command list text</returns>
[HttpGet]
public async Task<IActionResult> GetCommandList(Guid id, CancellationToken cancellationToken = default)
{
return await ExecuteWithErrorHandlingAsync(async () =>
{
var (actionResult, gameServerData) = await GetAuthorizedGameServerAsync(id, nameof(GetCommandList), cancellationToken).ConfigureAwait(false);
if (actionResult is not null)
return actionResult;
var getCommandListResult = await serversApiClient.Rcon.V1.GetCommandList(id).ConfigureAwait(false);
if (!getCommandListResult.IsSuccess || getCommandListResult.Result?.Data is null)
{
return Json(new { success = false, message = "Failed to get command list" });
}
var commandList = getCommandListResult.Result.Data;
return Json(new { success = true, commandList });
}, nameof(GetCommandList)).ConfigureAwait(false);
}
/// <summary>
/// Sends a 'say' command to broadcast a message to all players on the server
/// </summary>
/// <param name="id">Game server ID</param>
/// <param name="message">Message to broadcast</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>JSON result indicating success or failure</returns>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SendSayCommand(Guid id, string message, CancellationToken cancellationToken = default)
{
return await ExecuteWithErrorHandlingAsync(async () =>
{
var (actionResult, gameServerData) = await GetAuthorizedGameServerAsync(id, nameof(SendSayCommand), cancellationToken).ConfigureAwait(false);
if (actionResult is not null)
return actionResult;
if (string.IsNullOrWhiteSpace(message))
{
return Json(new { success = false, message = "Message cannot be empty" });
}
// Limit message length
message = message.Trim();
if (message.Length > 255)
{
message = message[..255];
}
var sayResult = await serversApiClient.Rcon.V1.Say(id, message).ConfigureAwait(false);
if (!sayResult.IsSuccess)
{
Logger.LogWarning("Failed to send say command to server {ServerId}", id);
return Json(new { success = false, message = "Failed to send message to server" });
}
TrackSuccessTelemetry("SayCommandSent", nameof(SendSayCommand), new Dictionary<string, string>
{
{ "GameServerId", id.ToString() },
{ "MessageLength", message.Length.ToString() }
});
return Json(new { success = true, message = "Message sent to server" });
}, nameof(SendSayCommand)).ConfigureAwait(false);
}
/// <summary>
/// Gets the map rotation for a specific game server
/// </summary>
/// <param name="id">Game server ID</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>JSON with list of maps in rotation with their metadata</returns>
[HttpGet]
public async Task<IActionResult> GetMapRotation(Guid id, CancellationToken cancellationToken = default)
{
return await ExecuteWithErrorHandlingAsync(async () =>
{
var (actionResult, gameServerData) = await GetAuthorizedGameServerAsync(id, nameof(GetMapRotation), cancellationToken).ConfigureAwait(false);
if (actionResult is not null)
return actionResult;
var getServerMapsResult = await serversApiClient.Rcon.V1.GetServerMaps(id).ConfigureAwait(false);
if (!getServerMapsResult.IsSuccess || getServerMapsResult.Result?.Data?.Items is null)
{
Logger.LogWarning("Failed to get map rotation for server {ServerId}", id);
return Json(new { success = false, maps = Array.Empty<object>() });
}
var rconMaps = getServerMapsResult.Result.Data.Items;
// Get map details from repository for images and metadata
var mapNames = rconMaps.Select(m => m.MapName).ToArray();
var mapsApiResponse = await repositoryApiClient.Maps.V1.GetMaps(
gameServerData!.GameType,
mapNames,
null, null, 0, 100, MapsOrder.MapNameAsc, cancellationToken).ConfigureAwait(false);
var mapDetails = mapsApiResponse.Result?.Data?.Items?.ToDictionary(m => m.MapName, m => m)
?? [];
var enrichedMaps = rconMaps.Select(rconMap =>
{
var mapDetail = mapDetails.GetValueOrDefault(rconMap.MapName);
return new
{
mapName = rconMap.MapName,
mapTitle = mapDetail?.MapName ?? rconMap.MapName,
mapImageUri = mapDetail?.MapImageUri,
hasImage = mapDetail?.MapImageUri is not null
};
}).ToList();
return Json(new { success = true, maps = enrichedMaps });
}, nameof(GetMapRotation)).ConfigureAwait(false);
}
/// <summary>
/// Loads a specific map on the game server via RCON command
/// </summary>
/// <param name="id">Game server ID</param>
/// <param name="mapName">Name of the map to load</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>JSON result indicating success or failure</returns>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LoadMap(
Guid id,
string mapName,
CancellationToken cancellationToken = default)
{
return await ExecuteWithErrorHandlingAsync(async () =>
{
var (actionResult, gameServerData) = await GetAuthorizedGameServerAsync(id, nameof(LoadMap), cancellationToken).ConfigureAwait(false);
if (actionResult is not null)
return actionResult;
if (string.IsNullOrWhiteSpace(mapName))
{
Logger.LogWarning("LoadMap called with empty map name for server {ServerId}", id);
return Json(new { success = false, message = "Map name is required" });
}
Logger.LogInformation("Attempting to load map {MapName} on server {ServerId}", mapName, id);
// Call the actual LoadMap RCON command
var loadMapResult = await serversApiClient.Rcon.V1.ChangeMap(id, mapName).ConfigureAwait(false);
if (!loadMapResult.IsSuccess)
{
Logger.LogError("Failed to load map {MapName} on server {ServerId}", mapName, id);
return Json(new { success = false, message = "Failed to load map. Please check server logs for details." });
}
TrackSuccessTelemetry("MapLoaded", nameof(LoadMap), new Dictionary<string, string>
{
{ "ServerId", id.ToString() },
{ "GameType", gameServerData!.GameType.ToString() },
{ "MapName", mapName }
});
Logger.LogInformation(
"Map {MapName} successfully loaded on server {ServerId}",
mapName,
id);
return Json(new { success = true, message = $"Map '{mapName}' is now loading" });
}, nameof(LoadMap)).ConfigureAwait(false);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RestartMap(Guid id, CancellationToken cancellationToken = default)
{
return await ExecuteWithErrorHandlingAsync(async () =>
{
var (actionResult, gameServerData) = await GetAuthorizedGameServerAsync(id, nameof(RestartMap), cancellationToken).ConfigureAwait(false);
if (actionResult is not null)
return actionResult;
var restartResult = await serversApiClient.Rcon.V1.RestartMap(id).ConfigureAwait(false);
if (!restartResult.IsSuccess)
{
Logger.LogError("Failed to restart map on server {ServerId}", id);
return Json(new { success = false, message = "Failed to restart map" });
}
TrackSuccessTelemetry("MapRestarted", nameof(RestartMap), new Dictionary<string, string>
{
{ "ServerId", id.ToString() },
{ "GameType", gameServerData!.GameType.ToString() }
});
return Json(new { success = true, message = "Map restart command sent successfully" });
}, nameof(RestartMap)).ConfigureAwait(false);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> FastRestartMap(Guid id, CancellationToken cancellationToken = default)
{
return await ExecuteWithErrorHandlingAsync(async () =>
{
var (actionResult, gameServerData) = await GetAuthorizedGameServerAsync(id, nameof(FastRestartMap), cancellationToken).ConfigureAwait(false);
if (actionResult is not null)
return actionResult;
var restartResult = await serversApiClient.Rcon.V1.FastRestartMap(id).ConfigureAwait(false);
if (!restartResult.IsSuccess)
{
Logger.LogError("Failed to fast restart map on server {ServerId}", id);
return Json(new { success = false, message = "Failed to fast restart map" });
}
TrackSuccessTelemetry("MapFastRestarted", nameof(FastRestartMap), new Dictionary<string, string>
{
{ "ServerId", id.ToString() },
{ "GameType", gameServerData!.GameType.ToString() }
});
return Json(new { success = true, message = "Fast restart command sent successfully" });
}, nameof(FastRestartMap)).ConfigureAwait(false);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> NextMap(Guid id, CancellationToken cancellationToken = default)
{
return await ExecuteWithErrorHandlingAsync(async () =>
{
var (actionResult, gameServerData) = await GetAuthorizedGameServerAsync(id, nameof(NextMap), cancellationToken).ConfigureAwait(false);
if (actionResult is not null)
return actionResult;
var nextMapResult = await serversApiClient.Rcon.V1.NextMap(id).ConfigureAwait(false);
if (!nextMapResult.IsSuccess)
{
Logger.LogError("Failed to load next map on server {ServerId}", id);
return Json(new { success = false, message = "Failed to load next map" });
}
TrackSuccessTelemetry("NextMapTriggered", nameof(NextMap), new Dictionary<string, string>
{
{ "ServerId", id.ToString() },
{ "GameType", gameServerData!.GameType.ToString() }
});
return Json(new { success = true, message = "Next map command sent successfully" });
}, nameof(NextMap)).ConfigureAwait(false);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RestartServer(Guid id, CancellationToken cancellationToken = default)
{
return await ExecuteWithErrorHandlingAsync(async () =>
{
var (actionResult, gameServerData) = await GetAuthorizedGameServerAsync(id, nameof(RestartServer), cancellationToken).ConfigureAwait(false);
if (actionResult is not null)
return actionResult;
var restartResult = await serversApiClient.Rcon.V1.Restart(id).ConfigureAwait(false);
if (!restartResult.IsSuccess)
{
Logger.LogError("Failed to restart server {ServerId}", id);
return Json(new { success = false, message = "Failed to restart server" });
}
TrackSuccessTelemetry("ServerRestarted", nameof(RestartServer), new Dictionary<string, string>
{
{ "ServerId", id.ToString() },
{ "GameType", gameServerData!.GameType.ToString() }
});
return Json(new { success = true, message = "Server restart command sent successfully" });
}, nameof(RestartServer)).ConfigureAwait(false);
}
/// <summary>
/// Kicks a player from the server via RCON and creates a Kick admin action
/// </summary>
/// <param name="id">Game server ID</param>
/// <param name="playerSlot">Player slot number</param>
/// <param name="playerGuid">Player GUID</param>
/// <param name="playerName">Player name</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>JSON result indicating success or failure</returns>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> KickRconPlayer(Guid id, int playerSlot, string playerGuid, string playerName, CancellationToken cancellationToken = default)
{
return await ExecuteWithErrorHandlingAsync(async () =>
{
var (actionResult, gameServerData) = await GetAuthorizedGameServerAsync(id, nameof(KickRconPlayer), cancellationToken).ConfigureAwait(false);
if (actionResult is not null)
return actionResult;
// Check authorization for creating kick admin actions
var authorizationResource = (gameServerData!.GameType, AdminActionType.Kick);
var authResult = await CheckAuthorizationAsync(
authorizationService,
authorizationResource,
AuthPolicies.CreateAdminAction,
"Kick",
"RconPlayer",
$"GameType:{gameServerData.GameType},ServerId:{id}",
gameServerData).ConfigureAwait(false);
if (authResult is not null)
return Json(new { success = false, error = "Unauthorized", message = "You don't have permission to kick players" });
if (string.IsNullOrWhiteSpace(playerName))
{
Logger.LogWarning("Invalid player data provided by user {UserId} for kick action", User.XtremeIdiotsId());
return Json(new { success = false, error = "InvalidInput", message = "Invalid player data provided" });
}
try
{
// Kick the player via RCON using slot number
var kickResult = await serversApiClient.Rcon.V1.KickPlayer(id, playerSlot).ConfigureAwait(false);
if (!kickResult.IsSuccess)
{
Logger.LogWarning("Failed to kick player {PlayerName} (slot {PlayerSlot}) from server {ServerId}",
playerName, playerSlot, id);
return Json(new { success = false, error = "RconFailed", message = "Failed to kick player from server" });
}
// Create admin action record if we have a GUID
if (!string.IsNullOrWhiteSpace(playerGuid))
{
await CreateAdminActionForRconOperationAsync(
gameServerData.GameType, playerGuid, playerName, AdminActionType.Kick,
$"Player kicked from {gameServerData.Title} via RCON by {User.Username()}",
cancellationToken).ConfigureAwait(false);
}
TrackSuccessTelemetry("RconPlayerKicked", nameof(KickRconPlayer), new Dictionary<string, string>
{
{ "ServerId", id.ToString() },
{ "PlayerSlot", playerSlot.ToString() },
{ "GameType", gameServerData.GameType.ToString() }
});
return Json(new { success = true, message = $"Player {playerName} has been kicked" });
}
catch (Exception ex)
{
Logger.LogError(ex, "Error kicking player {PlayerName} (slot {PlayerSlot}) from server {ServerId}",
playerName, playerSlot, id);
return Json(new { success = false, error = "Exception", message = "An error occurred while kicking the player" });
}
}, nameof(KickRconPlayer)).ConfigureAwait(false);
}
/// <summary>
/// Temporarily bans a player from the server via RCON and creates a TempBan admin action
/// </summary>
/// <param name="id">Game server ID</param>
/// <param name="playerSlot">Player slot number</param>
/// <param name="playerGuid">Player GUID</param>
/// <param name="playerName">Player name</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>JSON result indicating success or failure</returns>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> TempBanRconPlayer(Guid id, int playerSlot, string playerGuid, string playerName, CancellationToken cancellationToken = default)
{
return await ExecuteWithErrorHandlingAsync(async () =>
{
var (actionResult, gameServerData) = await GetAuthorizedGameServerAsync(id, nameof(TempBanRconPlayer), cancellationToken).ConfigureAwait(false);
if (actionResult is not null)
return actionResult;
// Check authorization for creating temp ban admin actions
var authorizationResource = (gameServerData!.GameType, AdminActionType.TempBan);
var authResult = await CheckAuthorizationAsync(
authorizationService,
authorizationResource,
AuthPolicies.CreateAdminAction,
"TempBan",
"RconPlayer",
$"GameType:{gameServerData.GameType},ServerId:{id}",
gameServerData).ConfigureAwait(false);
if (authResult is not null)
return Json(new { success = false, error = "Unauthorized", message = "You don't have permission to temp ban players" });
if (string.IsNullOrWhiteSpace(playerName))
{
Logger.LogWarning("Invalid player data provided by user {UserId} for temp ban action", User.XtremeIdiotsId());
return Json(new { success = false, error = "InvalidInput", message = "Invalid player data provided" });
}
try
{
// Ban the player via RCON using slot number (most servers don't have separate temp ban RCON command)
var banResult = await serversApiClient.Rcon.V1.BanPlayer(id, playerSlot).ConfigureAwait(false);
if (!banResult.IsSuccess)
{
Logger.LogWarning("Failed to temp ban player {PlayerName} (slot {PlayerSlot}) from server {ServerId}",
playerName, playerSlot, id);
return Json(new { success = false, error = "RconFailed", message = "Failed to temp ban player from server" });
}
// Create admin action record with expiry if we have a GUID
if (!string.IsNullOrWhiteSpace(playerGuid))
{
var expiryDate = DateTime.UtcNow.AddDays(tempBanDurationDays);
await CreateAdminActionForRconOperationAsync(
gameServerData.GameType, playerGuid, playerName, AdminActionType.TempBan,
$"Player temp banned from {gameServerData.Title} via RCON by {User.Username()}. Please update with proper reason.",
cancellationToken,
expiryDate).ConfigureAwait(false);
}
TrackSuccessTelemetry("RconPlayerTempBanned", nameof(TempBanRconPlayer), new Dictionary<string, string>
{
{ "ServerId", id.ToString() },
{ "PlayerSlot", playerSlot.ToString() },
{ "GameType", gameServerData.GameType.ToString() }
});
return Json(new { success = true, message = $"Player {playerName} has been temp banned for {tempBanDurationDays} days" });
}
catch (Exception ex)
{
Logger.LogError(ex, "Error temp banning player {PlayerName} (slot {PlayerSlot}) from server {ServerId}",
playerName, playerSlot, id);
return Json(new { success = false, error = "Exception", message = "An error occurred while temp banning the player" });
}
}, nameof(TempBanRconPlayer)).ConfigureAwait(false);
}
/// <summary>
/// Permanently bans a player from the server via RCON and creates a Ban admin action
/// </summary>
/// <param name="id">Game server ID</param>
/// <param name="playerSlot">Player slot number</param>
/// <param name="playerGuid">Player GUID</param>
/// <param name="playerName">Player name</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>JSON result indicating success or failure</returns>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> BanRconPlayer(Guid id, int playerSlot, string playerGuid, string playerName, CancellationToken cancellationToken = default)
{
return await ExecuteWithErrorHandlingAsync(async () =>
{
var (actionResult, gameServerData) = await GetAuthorizedGameServerAsync(id, nameof(BanRconPlayer), cancellationToken).ConfigureAwait(false);
if (actionResult is not null)
return actionResult;
// Check authorization for creating ban admin actions
var authorizationResource = (gameServerData!.GameType, AdminActionType.Ban);
var authResult = await CheckAuthorizationAsync(
authorizationService,
authorizationResource,
AuthPolicies.CreateAdminAction,
"Ban",
"RconPlayer",
$"GameType:{gameServerData.GameType},ServerId:{id}",
gameServerData).ConfigureAwait(false);
if (authResult is not null)
return Json(new { success = false, error = "Unauthorized", message = "You don't have permission to ban players" });
if (string.IsNullOrWhiteSpace(playerName))
{
Logger.LogWarning("Invalid player data provided by user {UserId} for ban action", User.XtremeIdiotsId());
return Json(new { success = false, error = "InvalidInput", message = "Invalid player data provided" });
}
try
{
// Ban the player via RCON using slot number
var banResult = await serversApiClient.Rcon.V1.BanPlayer(id, playerSlot).ConfigureAwait(false);
if (!banResult.IsSuccess)
{
Logger.LogWarning("Failed to ban player {PlayerName} (slot {PlayerSlot}) from server {ServerId}",
playerName, playerSlot, id);
return Json(new { success = false, error = "RconFailed", message = "Failed to ban player from server" });
}
// Create admin action record if we have a GUID
if (!string.IsNullOrWhiteSpace(playerGuid))
{
await CreateAdminActionForRconOperationAsync(
gameServerData.GameType, playerGuid, playerName, AdminActionType.Ban,
$"Player banned from {gameServerData.Title} via RCON by {User.Username()}. Please update with proper reason.",
cancellationToken).ConfigureAwait(false);
}
TrackSuccessTelemetry("RconPlayerBanned", nameof(BanRconPlayer), new Dictionary<string, string>
{
{ "ServerId", id.ToString() },
{ "PlayerSlot", playerSlot.ToString() },
{ "GameType", gameServerData.GameType.ToString() }
});
return Json(new { success = true, message = $"Player {playerName} has been permanently banned" });
}
catch (Exception ex)
{
Logger.LogError(ex, "Error banning player {PlayerName} (slot {PlayerSlot}) from server {ServerId}",
playerName, playerSlot, id);
return Json(new { success = false, error = "Exception", message = "An error occurred while banning the player" });
}
}, nameof(BanRconPlayer)).ConfigureAwait(false);
}
/// <summary>
/// Creates an admin action record for an RCON operation (kick/ban)
/// </summary>
/// <param name="gameType">Game type</param>
/// <param name="playerGuidStr">Player GUID as string</param>
/// <param name="playerName">Player name</param>
/// <param name="actionType">Type of admin action</param>
/// <param name="text">Admin action description</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <param name="expires">Optional expiry date for temp bans</param>
private async Task CreateAdminActionForRconOperationAsync(
GameType gameType,
string playerGuidStr,
string playerName,
AdminActionType actionType,
string text,
CancellationToken cancellationToken,
DateTime? expires = null)
{
try
{
// Try to find existing player profile by searching with GUID
var playerResponse = await repositoryApiClient.Players.V1.GetPlayers(
gameType, null, playerGuidStr, 0, 1, PlayersOrder.LastSeenDesc, PlayerEntityOptions.None).ConfigureAwait(false);
if (!playerResponse.IsSuccess || playerResponse.Result?.Data?.Items?.Any() != true)
{
Logger.LogWarning("Player with GUID {Guid} not found in database, cannot create admin action", playerGuidStr);
return;
}
var playerId = playerResponse.Result.Data.Items.First().PlayerId;
var adminId = User.XtremeIdiotsId();
var forumTopicId = await adminActionTopics.CreateTopicForAdminAction(
actionType,
gameType,
playerId,