This repository has been archived on 2024-10-29. You can view files and clone it, but cannot push or open issues or pull requests.
beatsaber-scoretracker/Mod/API/Request.cs

83 lines
2.8 KiB
C#
Raw Normal View History

2024-08-07 04:19:39 +00:00
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace ScoreTracker.API
{
internal class Request
{
private static readonly HttpClient client = new HttpClient();
private class AuthHelper
{
public bool IsLoggedIn;
public string FailReason = "";
public async Task EnsureLoggedIn()
{
if (Authentication.IsSignedIn() && await Authentication.ValidateAuthToken())
{
return; // Already logged in with a valid token
}
await Authentication.LoginUser(
token => {
IsLoggedIn = true;
PersistHeaders(new Dictionary<string, string>
{
{ "Authorization", $"Bearer {token}" }
});
},
reason =>
{
FailReason = reason; // Store the reason for failure
client.DefaultRequestHeaders.Clear(); // Clear headers
}
);
}
}
/// <summary>
/// Persist the given headers for all future requests
/// </summary>
/// <param name="headers">the headers to persist</param>
public static void PersistHeaders(Dictionary<string, string> headers)
{
client.DefaultRequestHeaders.Clear(); // Clear existing headers
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
/// <summary>
/// Create a POST request to the given URL with the given data
/// </summary>
/// <param name="url">the url to post to</param>
/// <param name="data">the data to post</param>
/// <param name="checkAuth">whether to check for authentication</param>
/// <returns>the task</returns>
public static async Task<HttpResponseMessage> PostJsonAsync(string url, Dictionary<object, object> json, bool checkAuth = true)
{
if (checkAuth)
{
var authHelper = new AuthHelper();
await authHelper.EnsureLoggedIn();
if (!authHelper.IsLoggedIn)
{
throw new Exception($"Failed to log in: {authHelper.FailReason}");
}
}
var jsonString = JsonConvert.SerializeObject(json, Formatting.None);
var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
// Send the POST request
var response = await client.PostAsync(url, content);
return response;
}
}
}