Skip to content

Commit

Permalink
moving try catch block.
Browse files Browse the repository at this point in the history
  • Loading branch information
Aleksandar Ovcharov committed Oct 13, 2024
1 parent f6c845a commit d3e27f4
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 34 deletions.
4 changes: 2 additions & 2 deletions GameCMSPlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
public sealed partial class GameCMSPlugin : BasePlugin, IPluginConfig<GameCMSConfig>
{
public override string ModuleName => "GameCMS.ORG";
public override string ModuleVersion => "1.1.0";
public override string ModuleVersion => "1.1.1";
public override string ModuleAuthor => "GameCMS.ORG (Wohaho)";
public override string ModuleDescription => "Plugin that allows you to connect your CS2 Server with the platform. Made with love. Keep it simple - GameCMS.ORG";
public GameCMSConfig Config { get; set; } = new();
Expand Down Expand Up @@ -166,7 +166,7 @@ public void onCommandService(CCSPlayerController? player, CommandInfo command)
return;
}

bool newStatus = status == "enabled" || status == "start";
bool newStatus = status == "enabled" || status == "start" || status == "enable";
bool currentStatus = (bool)property.GetValue(servicesConfig)!;
if (currentStatus == newStatus)
{
Expand Down
82 changes: 50 additions & 32 deletions Services/ServerDataService.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
using System.Net;
using System.Text.Json;
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Plugin;
using CounterStrikeSharp.API.Modules.Cvars;
using CounterStrikeSharp.API.Modules.Utils;
using Microsoft.Extensions.Logging;

namespace GameCMS
{

Expand Down Expand Up @@ -126,7 +126,6 @@ public void Start(bool hotReload, int serverId)

}


public async Task SendServerData(bool includePlayers = true)
{
if (isRequestInProgress || DateTime.UtcNow - lastRequestTime < requestCooldown)
Expand All @@ -137,26 +136,29 @@ public async Task SendServerData(bool includePlayers = true)
isRequestInProgress = true;
lastRequestTime = DateTime.UtcNow;

try

_plugin = (_pluginContext.Plugin as GameCMSPlugin)!;
await Server.NextWorldUpdateAsync(async () =>
{
_plugin = (_pluginContext.Plugin as GameCMSPlugin)!;
await Server.NextWorldUpdateAsync(async () =>
{

try
{
var players = Utilities.GetPlayers()
.Where(x => x.Connected == PlayerConnectedState.PlayerConnected
&& _helper.isValidPlayer(x)
&& !x.IsHLTV
&& !x.IsBot
&& x.TeamNum != (byte)CsTeam.Spectator
&& x.TeamNum != (byte)CsTeam.None
);
.Where(x => x.Connected == PlayerConnectedState.PlayerConnected
&& _helper.isValidPlayer(x)
&& !x.IsHLTV
&& !x.IsBot
&& x.TeamNum != (byte)CsTeam.Spectator
&& x.TeamNum != (byte)CsTeam.None
);

var playerInfos = new List<PlayerInfoEntityServerData>();
if (players.Any() && includePlayers)
{
playerInfos = GetPlayerInfos(players).ToList();
}


float MaxRoundTime = ConVar.Find("mp_roundtime")?.GetPrimitiveValue<float>() ?? 10f;
int MaxRounds = ConVar.Find("mp_maxrounds")?.GetPrimitiveValue<int>() ?? 0;
var serverDataEntity = new ServerDataEntity(
Expand All @@ -175,37 +177,53 @@ await Server.NextWorldUpdateAsync(async () =>

string serverData = JsonSerializer.Serialize(serverDataEntity);
string postUrl = "https://api.gamecms.org/v2/server-data/cs2";
string postToken = _plugin!.Config.ServerApiKey;
string postToken = _plugin.Config.ServerApiKey;

_logger.LogDebug("Sending server data to {0} with token {1}", postUrl, postToken);

var formData = new Dictionary<string, string> { { "data", serverData } };
using var contentData = new FormUrlEncodedContent(formData);
// Use JSON content type
var contentData = new StringContent(serverData, System.Text.Encoding.UTF8, "application/json");

// Set up the HttpClient
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", postToken);

var postResponse = await httpClient.PostAsync(postUrl, contentData);

if (!postResponse.IsSuccessStatusCode)
if (postResponse.StatusCode != HttpStatusCode.OK)
{
string errorResponse = await postResponse.Content.ReadAsStringAsync();
_logger.LogWarning("Error sending data: " + errorResponse);
_logger.LogWarning("Error sending data: StatusCode {0}, Response: {1}", postResponse.StatusCode, errorResponse);
}
});
}
catch (HttpRequestException ex)
{
_logger.LogError("HttpRequestException occurred: {0}", ex.Message);
}
catch (Exception ex)
{
_logger.LogError("Unexpected error occurred: {0}", ex.Message);
}
finally
{
isRequestInProgress = false;
}
else
{
isRequestInProgress = false;
_logger.LogInformation("Data sent successfully.");
}

}
catch (HttpRequestException ex)
{
_logger.LogError("HttpRequestException occurred: {0}", ex.Message);
}
catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException)
{
_logger.LogError("Request timed out: {0}", ex.Message);
}
catch (Exception ex)
{
_logger.LogError("Unexpected error occurred: {0}", ex.Message);
}
});




}





private IEnumerable<PlayerInfoEntityServerData> GetPlayerInfos(IEnumerable<CCSPlayerController> players)
{
return players.Select(player => new PlayerInfoEntityServerData
Expand Down

0 comments on commit d3e27f4

Please sign in to comment.