Skip to content

Commit

Permalink
Add controllers to SDK and switch app to use them
Browse files Browse the repository at this point in the history
  • Loading branch information
mullak99 committed Oct 22, 2023
1 parent c2406aa commit 540ad51
Show file tree
Hide file tree
Showing 29 changed files with 400 additions and 283 deletions.
12 changes: 10 additions & 2 deletions MCTools.API/Logic/ToolsLogic.cs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,9 @@ public async Task<List<AssetMCVersion>> GetJavaMCVersions(bool bypassHighestVers
{
try
{
using var httpResponse = await _httpClient.GetAsync("https://launchermeta.mojang.com/mc/game/version_manifest.json", HttpCompletionOption.ResponseHeadersRead);
using var httpResponse = await _httpClient.GetAsync(
"https://launchermeta.mojang.com/mc/game/version_manifest.json",
HttpCompletionOption.ResponseHeadersRead);
httpResponse.EnsureSuccessStatusCode();

var rawJson = await httpResponse.Content.ReadAsStringAsync();
Expand All @@ -139,7 +141,8 @@ public async Task<List<AssetMCVersion>> GetJavaMCVersions(bool bypassHighestVers
string latestSnapshot = latestSnapshotT != null ? latestSnapshotT.ToString() : "";

List<AssetMCVersion> versions = new();
json.SelectTokens($"$.versions[?(@.type == 'release' || @.id == '{latestSnapshot}' || @.id == '{latestRelease}')]")
json.SelectTokens(
$"$.versions[?(@.type == 'release' || @.id == '{latestSnapshot}' || @.id == '{latestRelease}')]")
.ToList().ForEach(x =>
{
var obj = x.ToObject<AssetMCVersion>();
Expand All @@ -151,6 +154,11 @@ public async Task<List<AssetMCVersion>> GetJavaMCVersions(bool bypassHighestVers
});
return LimitVersions(versions, bypassHighestVersionLimit);
}
catch (HttpRequestException e)
{
_logger.LogError(e, "Unable to make request to Mojang!");
throw new HttpRequestException("Unable to make request to Mojang!", e);
}
catch (Exception e)
{
_logger.LogError(e, "Failed to get Java MC versions");
Expand Down
44 changes: 44 additions & 0 deletions MCTools.SDK/Controllers/ApiClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using MCTools.SDK.Enums.Controllers;

namespace MCTools.SDK.Controllers
{
public class ApiClient : IApiClient
{
private readonly HttpClient _client;
private readonly string _baseAddress;

public ApiClient(HttpClient client, string userAgent, ApiRelease apiRelease = ApiRelease.Release, string overrideBaseAddress = "")
{
_client = client;
_baseAddress = apiRelease switch
{
ApiRelease.Release => "https://mctools-api.mullak99.co.uk",
ApiRelease.Beta => "https://mctools-api-beta.mullak99.co.uk",
_ => overrideBaseAddress.TrimEnd('/')
};
_client.BaseAddress = new Uri(_baseAddress);
_client.DefaultRequestHeaders.Add("User-Agent", userAgent);
_client.DefaultRequestHeaders.Add("Accept", "application/json");
}

public string BuildRequestUri(string requestUri, string apiVersion = "1.0")
=> BuildRequestUriRaw($"api/v{apiVersion}/{requestUri.TrimStart('/')}");

public string BuildRequestUriRaw(string requestUri)
=> $"{_baseAddress.TrimEnd('/')}/{requestUri.TrimStart('/')}";

public HttpClient GetClient()
=> _client;

public string GetBaseAddress()
=> _baseAddress;
}

public interface IApiClient
{
string BuildRequestUri(string requestUri, string apiVersion);
string BuildRequestUriRaw(string requestUri);
HttpClient GetClient();
string GetBaseAddress();
}
}
42 changes: 42 additions & 0 deletions MCTools.SDK/Controllers/BedrockController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using MCTools.SDK.Interfaces.Controllers;
using MCTools.SDK.Models;
using Newtonsoft.Json;

namespace MCTools.SDK.Controllers
{
public class BedrockController : IEditionController
{
private IApiClient _client { get; }
private string _apiVersion { get; }

public BedrockController(IApiClient client, string apiVersion = "1.0")
{
_client = client;
_apiVersion = apiVersion;
}

public async Task<List<MCVersion>> GetVersions()
{
HttpRequestMessage req = new(HttpMethod.Get, _client.BuildRequestUri("bedrock/versions", _apiVersion));
HttpResponseMessage res = await _client.GetClient().SendAsync(req);

if (res.StatusCode != System.Net.HttpStatusCode.OK)
return new();

string rawJson = await res.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<List<MCVersion>>(rawJson) ?? new();
}

public async Task<MCAssets> GetAssets(string version)
{
HttpRequestMessage req = new(HttpMethod.Get, _client.BuildRequestUri($"bedrock/version/{version}", _apiVersion));
HttpResponseMessage res = await _client.GetClient().SendAsync(req);

if (res.StatusCode != System.Net.HttpStatusCode.OK)
return new();

string rawJson = await res.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<MCAssets>(rawJson) ?? new();
}
}
}
32 changes: 32 additions & 0 deletions MCTools.SDK/Controllers/HealthController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using MCTools.SDK.Interfaces.Controllers;
using System.Net;

namespace MCTools.SDK.Controllers
{
public class HealthController : IController
{
private IApiClient _client { get; }

public HealthController(IApiClient client)
{
_client = client;
}

public async Task<HttpStatusCode> GetApiStatus(uint timeoutMs = 2000)
{
using CancellationTokenSource cancellationTokenSource = new(TimeSpan.FromMilliseconds(timeoutMs));
HttpRequestMessage req = new(HttpMethod.Get, _client.BuildRequestUriRaw("health"));

try
{
HttpResponseMessage res = await _client.GetClient().SendAsync(req, cancellationTokenSource.Token);
return res.StatusCode;
}
catch (TaskCanceledException)
{
// The task was canceled due to timeout
return HttpStatusCode.BadGateway;
}
}
}
}
66 changes: 66 additions & 0 deletions MCTools.SDK/Controllers/JavaController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
using MCTools.SDK.Interfaces.Controllers;
using MCTools.SDK.Models;
using Newtonsoft.Json;

namespace MCTools.SDK.Controllers
{
public class JavaController : IEditionController
{
private IApiClient _client { get; }
private string _apiVersion { get; }

public JavaController(IApiClient client, string apiVersion = "1.0")
{
_client = client;
_apiVersion = apiVersion;
}

public async Task<List<MCVersion>> GetVersions()
=> await GetVersions(false);

public async Task<List<MCVersion>> GetVersions(bool bypassVersionLimit)
{
HttpRequestMessage req = new(HttpMethod.Get, _client.BuildRequestUri($"java/versions?bypassVersionLimit={bypassVersionLimit}", _apiVersion));
HttpResponseMessage res = await _client.GetClient().SendAsync(req);

if (res.StatusCode != System.Net.HttpStatusCode.OK)
return new();

string rawJson = await res.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<List<MCVersion>>(rawJson) ?? new();
}

public async Task<MCAssets> GetAssets(string version)
{
HttpRequestMessage req = new(HttpMethod.Get, _client.BuildRequestUri($"java/version/{version}", _apiVersion));
HttpResponseMessage res = await _client.GetClient().SendAsync(req);

if (res.StatusCode != System.Net.HttpStatusCode.OK)
return new();

string rawJson = await res.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<MCAssets>(rawJson) ?? new();
}

public async Task<string> GetJar(string version)
{
HttpRequestMessage req = new(HttpMethod.Get, _client.BuildRequestUri($"java/version/{version}/jar", _apiVersion));
HttpResponseMessage res = await _client.GetClient().SendAsync(req);

if (res.StatusCode == System.Net.HttpStatusCode.OK)
return await res.Content.ReadAsStringAsync();
return string.Empty;
}

public async Task<bool> GetOverlaySupport(string version)
{
HttpRequestMessage req = new(HttpMethod.Get, _client.BuildRequestUri($"java/version/{version}/supports-overlays", _apiVersion));
HttpResponseMessage res = await _client.GetClient().SendAsync(req);

if (res.StatusCode != System.Net.HttpStatusCode.OK)
return true;

return !bool.TryParse(await res.Content.ReadAsStringAsync(), out bool result) || result;
}
}
}
41 changes: 41 additions & 0 deletions MCTools.SDK/Controllers/TelemetryController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System.Text;
using MCTools.SDK.Interfaces.Controllers;
using MCTools.SDK.Models.Telemetry;
using Newtonsoft.Json;

namespace MCTools.SDK.Controllers
{
public class TelemetryController : IController
{
private IApiClient _client { get; }
private string _apiVersion { get; }

public TelemetryController(IApiClient client, string apiVersion = "1.0")
{
_client = client;
_apiVersion = apiVersion;
}

public async Task AddAppLaunch(AppInfo appInfo)
{
HttpRequestMessage req = new(HttpMethod.Post, _client.BuildRequestUri("telemetry/launch", _apiVersion));
req.Content = new StringContent(JsonConvert.SerializeObject(appInfo), Encoding.UTF8, "application/json");
HttpResponseMessage res = await _client.GetClient().SendAsync(req);

if (res.StatusCode != System.Net.HttpStatusCode.OK)
Console.WriteLine($"Unable to communicate with the API! Response: {await res.Content.ReadAsStringAsync()}");
}

public async Task<List<ApiMessage>> GetStatusMessages()
{
HttpRequestMessage req = new(HttpMethod.Get, _client.BuildRequestUri("telemetry/launch", _apiVersion));
HttpResponseMessage res = await _client.GetClient().SendAsync(req);

if (res.StatusCode != System.Net.HttpStatusCode.OK)
return new();

string rawJson = await res.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<List<ApiMessage>>(rawJson) ?? new();
}
}
}
9 changes: 9 additions & 0 deletions MCTools.SDK/Enums/Controllers/ApiRelease.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace MCTools.SDK.Enums.Controllers
{
public enum ApiRelease
{
None = 0,
Release = 1,
Beta = 2
}
}
6 changes: 6 additions & 0 deletions MCTools.SDK/Interfaces/Controllers/IController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace MCTools.SDK.Interfaces.Controllers
{
public interface IController
{
}
}
11 changes: 11 additions & 0 deletions MCTools.SDK/Interfaces/Controllers/IEditionController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using MCTools.SDK.Models;

namespace MCTools.SDK.Interfaces.Controllers
{
public interface IEditionController : IController
{
Task<List<MCVersion>> GetVersions();

Task<MCAssets> GetAssets(string version);
}
}
2 changes: 1 addition & 1 deletion MCTools.SDK/MCTools.SDK.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
</PropertyGroup>

<PropertyGroup>
<VersionPrefix>1.0.1</VersionPrefix>
<VersionPrefix>1.1.0</VersionPrefix>
</PropertyGroup>

<ItemGroup>
Expand Down
6 changes: 3 additions & 3 deletions MCTools.SDK/Models/MCVersion.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
{
public class MCVersion
{
public string Id { get; set; }
public string Type { get; set; }
public string Url { get; set; }
public string Id { get; set; } = string.Empty;
public string Type { get; set; } = string.Empty;
public string Url { get; set; } = string.Empty;
public DateTime Time { get; set; }
public DateTime ReleaseTime { get; set; }

Expand Down
17 changes: 11 additions & 6 deletions MCTools/Components/VersionComparison.razor
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
@using MCTools.Enums
@using MCTools.Controllers
@using MCTools.SDK.Controllers
@using MCTools.SDK.Models
@using MudBlazor
@inject ISnackbar Snackbar

<MudItem xs="4">
Expand Down Expand Up @@ -30,7 +31,8 @@
</MudItem>

@code {
[Parameter] public ApiController ApiController { get; set; }
[Parameter] public JavaController JavaController { get; set; }
[Parameter] public BedrockController BedrockController { get; set; }
[Parameter] public EventCallback<(MCVersion From, MCVersion To)> VersionChanged { get; set; }
[Parameter] public EventCallback<MCEdition> EditionChanged { get; set; }
[Parameter] public bool IsProcessing { get; set; }
Expand All @@ -50,7 +52,10 @@
private bool DisableVersionSelector => DisableControls || DisableVersions;

protected override async Task OnInitializedAsync()
=> await SelectedEditionChanged(SelectedEdition);
{
DisableBedrock = DisableBedrock || BedrockController == null;
await SelectedEditionChanged(SelectedEdition);
}

public void SetDefaultVersionSelection()
{
Expand All @@ -74,7 +79,7 @@

public async Task SelectedEditionChanged(MCEdition edition)
{
if (edition != SelectedEdition || MinecraftVersions.Count == 0)
if (edition != SelectedEdition || MinecraftVersions.Count == 0 && !(DisableBedrock && edition == MCEdition.Bedrock))
{
try
{
Expand All @@ -83,8 +88,8 @@
MinecraftVersions = new List<MCVersion>(); // Reset list
MinecraftVersions = edition == MCEdition.Java
? await ApiController.GetJavaVersions(MainLayout.ExpandedVersionSelector)
: await ApiController.GetBedrockVersions();
? await JavaController.GetVersions(MainLayout.ExpandedVersionSelector)
: await BedrockController.GetVersions();

SetDefaultVersionSelection();
}
Expand Down
Loading

0 comments on commit 540ad51

Please sign in to comment.