Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Battle metrics Update #43

Merged
merged 9 commits into from
Sep 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions DiscordPlayerCountBot/Attributes/AttributeHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System.Linq;

namespace DiscordPlayerCountBot.Attributes
{
public static class AttributeHelper
{
public static string GetNameFromAttribute(object obj)
{
var nameAttribute = obj.GetType().GetCustomAttributes(true).Where(attribute => attribute.GetType() == typeof(NameAttribute)).Cast<NameAttribute>().FirstOrDefault();
var label = nameAttribute?.Name ?? obj.GetType().Name;
return label;
}
}
}
2 changes: 1 addition & 1 deletion DiscordPlayerCountBot/Attributes/NameAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace DiscordPlayerCountBot.Attributes
{
[AttributeUsage(AttributeTargets.Property)]
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class)]
public class NameAttribute : Attribute
{
public string Name { get; set; }
Expand Down
33 changes: 3 additions & 30 deletions DiscordPlayerCountBot/Bot/Bot.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Discord;
using Discord.WebSocket;
using DiscordPlayerCountBot;
using DiscordPlayerCountBot.Enum;
using DiscordPlayerCountBot.Http;
using DiscordPlayerCountBot.Providers;
Expand Down Expand Up @@ -51,17 +52,11 @@ public async Task StartAsync()
{
if (Information.Address.Contains("hostname") || Information.Address.Contains("localhost"))
{
string[] splitAddr = Information.Address.Split(":");
string address = await GetHostAddress();
string port = splitAddr[1].ToLower();
Information.Address = address + ":" + port;
Information.Address = await AddressHelper.ResolveAddress(Information.Address);
}

Logger.Info($"[Bot] - Loaded {Information.Name} at address and port: {Information.Address}, {Information.ProviderType}");

await DiscordClient.LoginAsync(TokenType.Bot, Information.Token);
await DiscordClient.SetGameAsync($"Starting: {Information.Address}");
await DiscordClient.StartAsync();
await DiscordClient.LoginAndStartAsync(Information.Token, Information.Address);
}

public async Task StopAsync()
Expand Down Expand Up @@ -123,27 +118,5 @@ public async Task UpdateAsync()
}
}
}

public async Task<string> GetHostAddress()
{
string publicIPAddress = string.Empty;
var httpClient = new HttpExecuter(new HttpClient());


try
{
var ipAddress = await httpClient.GET<object, string>("http://ifconfig.me");

if (string.IsNullOrEmpty(ipAddress))
throw new ApplicationException("IP Address cannot be null. Host failed to resolve address.");

return ipAddress;
}
catch (WebException ex)
{
Logger.Error($"[Bot] - Error Reaching ifconfig.me: {ex.Status}", ex);
throw ex;
}
}
}
}
2 changes: 1 addition & 1 deletion DiscordPlayerCountBot/Bot/BotInformation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public class BotInformation
public string Address { get; set; }

[JsonProperty]
public string? Token { get; set; }
public string Token { get; set; }

[JsonProperty]
public int Status { get; set; }
Expand Down
2 changes: 1 addition & 1 deletion DiscordPlayerCountBot/Data/Minecraft/MinecraftServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class MinecraftServer
public MinecraftMotd Motd { get; set; }

[JsonProperty("players")]
public MinecraftPlayerInfo Players { get; set; }
public MinecraftPlayerInfo? Players { get; set; }

[JsonProperty("version")]
public string? Version { get; set; }
Expand Down
16 changes: 16 additions & 0 deletions DiscordPlayerCountBot/DiscordClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using Discord;
using Discord.WebSocket;
using System.Threading.Tasks;

namespace DiscordPlayerCountBot
{
public static class DiscordClient
{
public static async Task LoginAndStartAsync(this DiscordSocketClient client, string token, string address)
{
await client.LoginAsync(TokenType.Bot, token);
await client.SetGameAsync($"Starting: {address}");
await client.StartAsync();
}
}
}
35 changes: 35 additions & 0 deletions DiscordPlayerCountBot/Http/AddressHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using log4net.Repository.Hierarchy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualBasic;

namespace DiscordPlayerCountBot.Http
{
public static class AddressHelper
{
public static async Task<string> GetHostAddress()
{
var publicIPAddress = string.Empty;
var httpClient = new HttpExecuter();
var ipAddress = await httpClient.GET<object, string>("http://ifconfig.me");

if (string.IsNullOrEmpty(ipAddress))
throw new ApplicationException("IP Address cannot be null. Host failed to resolve address.");

return ipAddress;
}

public static async Task<string> ResolveAddress(string address)
{
var splitAddr = address.Split(":");
var resolvedAddress = await GetHostAddress();
var port = splitAddr[1];
return resolvedAddress + ":" + port;
}
}
}
4 changes: 2 additions & 2 deletions DiscordPlayerCountBot/Http/HttpExecuter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ public class HttpExecuter : IHttpExecuter, IDisposable
{
public readonly HttpClient HttpClient;

public HttpExecuter(HttpClient httpClient)
public HttpExecuter()
{
HttpClient = httpClient;
HttpClient = new HttpClient();
}

public void Dispose()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net;
using System.Threading.Tasks;
using log4net;
using PlayerCountBot;
using DiscordPlayerCountBot.Attributes;

namespace DiscordPlayerCountBot.Providers.Base
{
Expand All @@ -11,21 +14,79 @@ public abstract class ServerInformationProvider : IServerInformationProvider
public bool WasLastExecutionAFailure { get; set; } = false;
public Exception? LastException { get; set; }
protected ILog Logger { get; set; }
public readonly string Label;

public ServerInformationProvider()
{
Logger = LogManager.GetLogger(GetType());
Label = AttributeHelper.GetNameFromAttribute(this);
}

public abstract Task<GenericServerInformation?> GetServerInformation(BotInformation information, Dictionary<string, string> applicationVariables);
protected void HandleLastException(BotInformation information)
{
if (WasLastExecutionAFailure)
{
Logger.Info($"[{GetType().Name}] - Bot for Address: {information.Address} successfully fetched data after failure.");

Logger.Info($"[{Label}] - Bot named: {information.Name} at address: {information.Address} successfully fetched data after failure.");
LastException = null;
WasLastExecutionAFailure = false;
}
}

protected void HandleException(Exception e)
{
if (e.Message == LastException?.Message)
return;

WasLastExecutionAFailure = true;
LastException = e;

if (e is TaskCanceledException canceledException)
{
Logger.Error($"[{Label}] - Update task was canceled likely because of system timeout.");
return;
}

if (e is KeyNotFoundException keyNotFoundException)
{
Logger.Error($"[{Label}] - SteamAPIKey is missing from Application variable configuration.");
return;
}

if (e is HttpRequestException requestException)
{
Logger.Error($"[{Label}] - The {Label} has failed to respond. {requestException.StatusCode}");
return;
}

if (e is WebException webException)
{
if (webException.Status == WebExceptionStatus.Timeout)
{
Logger.Error($"[{Label}] - Speaking with {Label} has timed out.");
return;
}
else if (webException.Status == WebExceptionStatus.ConnectFailure)
{
Logger.Error($"[{Label}] - Could not connect to {Label}.");
return;
}
else
{
Logger.Error($"[{Label}] - There was an error speaking with your {Label} server.", e);
return;
}
}

if (e is ApplicationException applicationException)
{
Logger.Error($"[{Label}] - {applicationException.Message}");
return;
}

Logger.Error($"[{Label}] - There was an error speaking with {Label}.", e);
throw e;
}
}
}
51 changes: 4 additions & 47 deletions DiscordPlayerCountBot/Providers/BattleMetricsProvider.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using DiscordPlayerCountBot.Attributes;
using DiscordPlayerCountBot.Providers.Base;
using DiscordPlayerCountBot.Services;
using PlayerCountBot;

namespace DiscordPlayerCountBot.Providers
{
[Name("BattleMetrics")]
public class BattleMetricsProvider : ServerInformationProvider
{
public async override Task<GenericServerInformation?> GetServerInformation(BotInformation information, Dictionary<string, string> applicationVariables)
Expand Down Expand Up @@ -36,51 +36,8 @@ public class BattleMetricsProvider : ServerInformationProvider
}
catch (Exception e)
{
if (e.Message == LastException?.Message)
return null;

WasLastExecutionAFailure = true;
LastException = e;

if (e is KeyNotFoundException keyNotFoundException)
{
Logger.Error($"[BattleMetricsProvider] - BattleMetricKey is missing from Application variable configuration.");
return null;
}

if (e is HttpRequestException requestException)
{
Logger.Error($"[BattleMetricsProvider] - The BattleMetric host has failed to respond.");
return null;
}

if (e is WebException webException)
{
if (webException.Status == WebExceptionStatus.Timeout)
{
Logger.Error($"[BattleMetricsProvider] - Speaking with BattleMetric has timed out.");
return null;
}
else if (webException.Status == WebExceptionStatus.ConnectFailure)
{
Logger.Error($"[BattleMetricsProvider] - Could not connect to BattleMetric.");
return null;
}
else
{
Logger.Error($"[BattleMetricsProvider] - There was an error speaking with your BattleMetric server.", e);
return null;
}
}

if (e is ApplicationException applicationException)
{
Logger.Error($"[BattleMetricsProvider] - {applicationException.Message}");
return null;
}

Logger.Error($"[BattleMetricsProvider] - There was an error speaking with BattleMetric.", e);
throw;
HandleException(e);
return null;
}
}
}
Expand Down
45 changes: 4 additions & 41 deletions DiscordPlayerCountBot/Providers/CFXProvider.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using DiscordPlayerCountBot.Attributes;
using DiscordPlayerCountBot.Providers.Base;
using DiscordPlayerCountBot.Services;
using PlayerCountBot;

namespace DiscordPlayerCountBot.Providers
{
[Name("CFX")]
public class CFXProvider : ServerInformationProvider
{
public async override Task<GenericServerInformation?> GetServerInformation(BotInformation information, Dictionary<string, string> applicationVariables)
Expand Down Expand Up @@ -39,45 +39,8 @@ public class CFXProvider : ServerInformationProvider
}
catch (Exception e)
{
if (e.Message == LastException?.Message)
return null;

WasLastExecutionAFailure = true;
LastException = e;

if (e is HttpRequestException requestException)
{
Logger.Error($"[CFXProvider] - The CFX host has failed to respond. {requestException.StatusCode}");
return null;
}

if (e is WebException webException)
{
if (webException.Status == WebExceptionStatus.Timeout)
{
Logger.Error($"[CFXProvider] - Speaking with CFX has timed out.");
return null;
}
else if (webException.Status == WebExceptionStatus.ConnectFailure)
{
Logger.Error($"[CFXProvider] - Could not connect to CFX.");
return null;
}
else
{
Logger.Error($"[CFXProvider] - There was an error speaking with your CFX server.", e);
return null;
}
}

if (e is ApplicationException applicationException)
{
Logger.Error($"[CFXProvider] - {applicationException.Message}");
return null;
}

Logger.Error($"[CFXProvider] - There was an error speaking with CFX.", e);
throw;
HandleException(e);
return null;
}
}
}
Expand Down
Loading