Skip to content

Commit

Permalink
Refactor API client
Browse files Browse the repository at this point in the history
  • Loading branch information
NoahStolk committed Oct 7, 2023
1 parent 45d0bdd commit 5e0e5ea
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 49 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ While the project provides many ways to practice and modify the game, it does **

Most of these features have been discussed with the community and the developer of Devil Daggers (Sorath), some of which have been done in collaboration.

(Note: This code was originally part of the [DevilDaggersInfo](https://github.com/NoahStolk/DevilDaggersInfo) repository (now ddinfo-web). It was moved to a separate repository on October 7th, 2023.)
(Note: This code was originally part of the [DevilDaggersInfo](https://github.com/NoahStolk/ddinfo-web) repository (now ddinfo-web). It was moved to a separate repository on October 7th, 2023.)

## Features

Expand Down
5 changes: 4 additions & 1 deletion src/DevilDaggersInfo.Tools.sln.DotSettings
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/UserDictionary/Words/=ddinfo/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Spawnset/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Sorath/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Spawnset/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=spawnsets/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Stolk/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,56 @@
using DevilDaggersInfo.Web.ApiSpec.Tools.ProcessMemory;
using DevilDaggersInfo.Web.ApiSpec.Tools.Spawnsets;
using DevilDaggersInfo.Web.ApiSpec.Tools.Updates;
using System.Net;
using System.Net.Http.Json;

namespace DevilDaggersInfo.Tools.Networking;

public partial class AppApiHttpClient
public class ApiHttpClient
{
private readonly HttpClient _client;

public ApiHttpClient(HttpClient client)
{
_client = client;
}

private async Task<HttpResponseMessage> SendRequest(HttpMethod httpMethod, string url, JsonContent? body = null)
{
using HttpRequestMessage request = new();
request.RequestUri = new(url, UriKind.Relative);
request.Method = httpMethod;
request.Content = body;

return await _client.SendAsync(request);
}

private async Task<T> SendGetRequest<T>(string url)
{
using HttpResponseMessage response = await SendRequest(HttpMethod.Get, url);
if (response.StatusCode != HttpStatusCode.OK)
throw new HttpRequestException(await response.Content.ReadAsStringAsync(), null, response.StatusCode);

return await response.Content.ReadFromJsonAsync<T>() ?? throw new InvalidDataException($"Deserialization error in {url} for JSON '{response.Content}'.");
}

private static string BuildUrlWithQuery(string baseUrl, Dictionary<string, object?> queryParameters)
{
if (queryParameters.Count == 0)
return baseUrl;

string queryParameterString = string.Join('&', queryParameters.Select(kvp => $"{kvp.Key}={kvp.Value}"));
return $"{baseUrl.TrimEnd('/')}?{queryParameterString}";
}

public async Task<GetCustomEntryReplayBuffer> GetCustomEntryReplayBufferById(int id)
{
return await SendGetRequest<GetCustomEntryReplayBuffer>($"api/app/custom-entries/{id}/replay-buffer");
}

public async Task<HttpResponseMessage> SubmitScore(AddUploadRequest uploadRequest)
{
return await SendRequest(new HttpMethod("POST"), "api/app/custom-entries/submit", JsonContent.Create(uploadRequest));
return await SendRequest(HttpMethod.Post, "api/app/custom-entries/submit", JsonContent.Create(uploadRequest));
}

public async Task<List<GetCustomLeaderboardForOverview>> GetCustomLeaderboards(int selectedPlayerId)
Expand Down Expand Up @@ -48,7 +84,7 @@ public async Task<HttpResponseMessage> CustomLeaderboardExistsBySpawnsetHash(byt
{
{ nameof(hash), Uri.EscapeDataString(Convert.ToBase64String(hash)) },
};
return await SendRequest(new HttpMethod("HEAD"), BuildUrlWithQuery("api/app/custom-leaderboards/exists", queryParameters));
return await SendRequest(HttpMethod.Head, BuildUrlWithQuery("api/app/custom-leaderboards/exists", queryParameters));
}

public async Task<List<GetCustomLeaderboardAllowedCategory>> GetCustomLeaderboardAllowedCategories()
Expand Down
42 changes: 0 additions & 42 deletions src/DevilDaggersInfo.Tools/Networking/AppApiHttpClient.cs

This file was deleted.

4 changes: 2 additions & 2 deletions src/DevilDaggersInfo.Tools/Networking/AsyncHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ static AsyncHandler()
_clientHandler.ServerCertificateCustomValidationCallback = (_, _, _, _) => true;
}

public static AppApiHttpClient Client { get; } = new(new(_clientHandler) { BaseAddress = new("https://localhost:5001/") });
public static ApiHttpClient Client { get; } = new(new(_clientHandler) { BaseAddress = new("https://localhost:5001/") });
#else
public static AppApiHttpClient Client { get; } = new(new() { BaseAddress = new("https://devildaggers.info") });
public static ApiHttpClient Client { get; } = new(new() { BaseAddress = new("https://devildaggers.info") });
#endif

public static void Run<TResult>(Action<TResult?> callback, Func<Task<TResult>> call)
Expand Down

0 comments on commit 5e0e5ea

Please sign in to comment.