mod: impl config for api url
All checks were successful
Release Mod / Build (push) Successful in 25s

This commit is contained in:
Lee 2024-08-07 08:26:12 +01:00
parent 9355368f54
commit 8e3a46f8bc
7 changed files with 77 additions and 60 deletions

View File

@ -1,10 +1,45 @@
using System;
using ScoreTracker.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace ScoreTracker.API
{
internal class AuthHelper
{
public bool IsLoggedIn;
public string FailReason = "";
/// <summary>
/// Ensure the user is logged in
/// </summary>
/// <returns>the task</returns>
public async Task EnsureLoggedIn()
{
if (Authentication.IsSignedIn() && await Authentication.ValidateAuthToken())
{
return; // Already logged in with a valid token
}
await Authentication.LoginUser(
token => {
IsLoggedIn = true;
Request.PersistHeaders(new Dictionary<string, string>
{
{ "Authorization", $"Bearer {token}" }
});
},
reason =>
{
FailReason = reason; // Store the reason for failure
Request.HttpClient.DefaultRequestHeaders.Clear(); // Clear headers
}
);
}
}
internal class Authentication
{
private static bool _signedIn = false;
@ -54,7 +89,7 @@ namespace ScoreTracker.API
}
Plugin.Log.Info("Logging in...");
var request = await Request.PostJsonAsync($"{Consts.ApiUrl}/auth/login", new Dictionary<object, object> {
var request = await Request.PostJsonAsync($"{PluginConfig.Instance.ApiUrl}/auth/login", new Dictionary<object, object> {
{ "ticket", ticket }
}, false);
if (request.IsSuccessStatusCode)
@ -88,7 +123,7 @@ namespace ScoreTracker.API
return false;
}
var request = await Request.PostJsonAsync($"{Consts.ApiUrl}/auth/validate", new Dictionary<object, object> {
var request = await Request.PostJsonAsync($"{PluginConfig.Instance.ApiUrl}/auth/validate", new Dictionary<object, object> {
{ "token", _authToken }
}, false);

View File

@ -9,36 +9,7 @@ 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
}
);
}
}
internal static readonly HttpClient HttpClient = new HttpClient();
/// <summary>
/// Persist the given headers for all future requests
@ -46,10 +17,10 @@ namespace ScoreTracker.API
/// <param name="headers">the headers to persist</param>
public static void PersistHeaders(Dictionary<string, string> headers)
{
client.DefaultRequestHeaders.Clear(); // Clear existing headers
HttpClient.DefaultRequestHeaders.Clear(); // Clear existing headers
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
HttpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
@ -75,7 +46,7 @@ namespace ScoreTracker.API
var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
// Send the POST request
var response = await client.PostAsync(url, content);
var response = await HttpClient.PostAsync(url, content);
return response;
}
}

View File

@ -0,0 +1,16 @@
using IPA.Config.Stores;
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(GeneratedStore.AssemblyVisibilityTarget)]
namespace ScoreTracker.Configuration
{
internal class PluginConfig
{
public static PluginConfig Instance { get; set; }
/*
* The URL of the API to use
*/
public virtual string ApiUrl { get; set; } = "https://beatsaber.fascinated.cc/api";
}
}

View File

@ -1,7 +0,0 @@
namespace ScoreTracker
{
internal class Consts
{
public static string ApiUrl = "https://beatsaber.fascinated.cc/api";
}
}

View File

@ -3,9 +3,6 @@
<Project>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<WarningLevel>4</WarningLevel>
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
<DisableCopyToPlugins>true</DisableCopyToPlugins>
<DisableZipRelease>true</DisableZipRelease>
</PropertyGroup>
<PropertyGroup Condition="'$(RUNNING_IN_CI)' == 'true'">
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>

View File

@ -1,13 +1,13 @@
using Zenject;
namespace ScoreTracker.Core
namespace ScoreTracker.Installers
{
internal class AppInstaller : Installer
{
public override void InstallBindings()
{
Plugin.Container = Container;
}
}
}

View File

@ -1,30 +1,35 @@
using IPA;
using IPALogger = IPA.Logging.Logger;
using SiraUtil.Zenject;
using IPA.Loader;
using Zenject;
using ScoreTracker.Core;
using System.Threading.Tasks;
using ScoreTracker.API;
using System.Collections.Generic;
using IPA.Config.Stores;
using IPA.Config;
using ScoreTracker.Configuration;
using ScoreTracker.Installers;
namespace ScoreTracker
{
[Plugin(RuntimeOptions.SingleStartInit)]
[Plugin(RuntimeOptions.DynamicInit)]
[NoEnableDisable]
public class Plugin
{
internal static Plugin Instance { get; private set; }
internal static IPALogger Log { get; private set; }
internal static DiContainer Container; // Workaround to access the Zenject container in SceneLoaded
[Init]
public Plugin(IPALogger logger, PluginMetadata metadata, Zenjector zenjector)
public Plugin(IPALogger logger, Zenjector zenjector, Config config)
{
Instance = this;
Log = logger; // Setup the logger
// Install our Zenject bindings
// Setup Zenject
zenjector.UseLogger(logger);
zenjector.UseMetadataBinder<Plugin>();
zenjector.Install<AppInstaller>(Location.App);
// Setup the config
PluginConfig.Instance = config.Generated<PluginConfig>();
}
[OnStart]
@ -32,11 +37,11 @@ namespace ScoreTracker
{
Log.Info("OnApplicationStart");
Task.Run(async () =>
// Ensure the user is logged in
Task.Factory.StartNew(async () =>
{
await Request.PostJsonAsync("http://localhost:7500/test", new Dictionary<object, object> {
{ "boobies", "yes" }
});
var authHelper = new AuthHelper();
await authHelper.EnsureLoggedIn();
});
}