- tweak: change auth api

This commit is contained in:
2024-12-28 08:29:01 +03:00
parent bdb8915932
commit 87dd1d7c30
10 changed files with 110 additions and 69 deletions

View File

@@ -17,7 +17,7 @@ public static class CurrentConVar
"https://hub.spacestation14.com/api/servers" "https://hub.spacestation14.com/api/servers"
]); ]);
public static readonly ConVar<string[]> AuthServers = ConVarBuilder.Build<string[]>("launcher.authServers", [ public static readonly ConVar<string[]> AuthServers = ConVarBuilder.Build<string[]>("launcher.authServers", [
"https://auth.spacestation14.com/api/auth" "https://auth.spacestation14.com/"
]); ]);
public static readonly ConVar<AuthLoginPassword[]> AuthProfiles = ConVarBuilder.Build<AuthLoginPassword[]>("auth.profiles", []); public static readonly ConVar<AuthLoginPassword[]> AuthProfiles = ConVarBuilder.Build<AuthLoginPassword[]>("auth.profiles", []);

View File

@@ -35,7 +35,7 @@ public class FileApi : IReadWriteFileApi
using var stream = File.OpenWrite(currPath); using var stream = File.OpenWrite(currPath);
input.CopyTo(stream); input.CopyTo(stream);
stream.Flush(true); stream.Flush();
stream.Close(); stream.Close();
return true; return true;
} }

View File

@@ -22,7 +22,7 @@ public class RobustUrl
public override string ToString() public override string ToString()
{ {
return HttpUri.ToString(); return Uri.ToString();
} }
public static implicit operator Uri(RobustUrl url) public static implicit operator Uri(RobustUrl url)

View File

@@ -33,9 +33,9 @@ public partial class AuthService : ObservableObject
var login = authLoginPassword.Login; var login = authLoginPassword.Login;
var password = authLoginPassword.Password; var password = authLoginPassword.Password;
_debugService.Debug($"Auth to {authServer}/authenticate {login}"); _debugService.Debug($"Auth to {authServer}api/auth/authenticate {login}");
var authUrl = new Uri($"{authServer}/authenticate"); var authUrl = new Uri($"{authServer}api/auth/authenticate");
var result = var result =
await _restService.PostAsync<AuthenticateResponse, AuthenticateRequest>( await _restService.PostAsync<AuthenticateResponse, AuthenticateRequest>(
@@ -57,7 +57,7 @@ public partial class AuthService : ObservableObject
{ {
if (SelectedAuth is null) return false; if (SelectedAuth is null) return false;
var authUrl = new Uri($"{SelectedAuth.AuthLoginPassword.AuthServer}/ping"); var authUrl = new Uri($"{SelectedAuth.AuthLoginPassword.AuthServer}api/auth/ping");
using var requestMessage = new HttpRequestMessage(HttpMethod.Get, authUrl); using var requestMessage = new HttpRequestMessage(HttpMethod.Get, authUrl);
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("SS14Auth", SelectedAuth.Token.Token); requestMessage.Headers.Authorization = new AuthenticationHeaderValue("SS14Auth", SelectedAuth.Token.Token);

View File

@@ -2,8 +2,6 @@ using System;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.IO; using System.IO;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
using Nebula.Launcher.FileApis;
namespace Nebula.Launcher.Services; namespace Nebula.Launcher.Services;
@@ -13,9 +11,9 @@ public class ConVar<T>
public Type Type => typeof(T); public Type Type => typeof(T);
public T? DefaultValue { get; } public T? DefaultValue { get; }
public ConVar(string name, T? defaultValue) public ConVar(string name, T? defaultValue = default)
{ {
Name = name; Name = name ?? throw new ArgumentNullException(nameof(name));
DefaultValue = defaultValue; DefaultValue = defaultValue;
} }
} }
@@ -24,6 +22,9 @@ public static class ConVarBuilder
{ {
public static ConVar<T> Build<T>(string name, T? defaultValue = default) public static ConVar<T> Build<T>(string name, T? defaultValue = default)
{ {
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException("ConVar name cannot be null or whitespace.", nameof(name));
return new ConVar<T>(name, defaultValue); return new ConVar<T>(name, defaultValue);
} }
} }
@@ -36,78 +37,83 @@ public class ConfigurationService
public ConfigurationService(FileService fileService, DebugService debugService) public ConfigurationService(FileService fileService, DebugService debugService)
{ {
_fileService = fileService; _fileService = fileService ?? throw new ArgumentNullException(nameof(fileService));
_debugService = debugService; _debugService = debugService ?? throw new ArgumentNullException(nameof(debugService));
} }
public T? GetConfigValue<T>(ConVar<T> conVar) public T? GetConfigValue<T>(ConVar<T> conVar)
{ {
if(!_fileService.ConfigurationApi.TryOpen(GetFileName(conVar), out var stream) || ArgumentNullException.ThrowIfNull(conVar);
!ReadStream<T>(stream, out var obj))
return conVar.DefaultValue;
_debugService.Log("Loading config file: " + conVar.Name);
return obj;
}
public void SetConfigValue<T>(ConVar<T> conVar, object value)
{
if(conVar.Type != value.GetType())
{
_debugService.Error("Error config file " + conVar.Name + ": Type is not equals " + value.GetType() + " " + conVar.Type);
return;
}
_debugService.Log("Saving config file: " + conVar.Name);
WriteStream(conVar, value);
}
private bool ReadStream<T>(Stream stream,[NotNullWhen(true)] out T? obj)
{
obj = default;
try try
{ {
obj = JsonSerializer.Deserialize<T>(stream); if (_fileService.ConfigurationApi.TryOpen(GetFileName(conVar), out var stream))
return obj != null; {
using (stream)
{
var obj = JsonSerializer.Deserialize<T>(stream);
if (obj != null)
{
_debugService.Log($"Successfully loaded config: {conVar.Name}");
return obj;
}
}
}
} }
catch (Exception e) catch (Exception e)
{ {
_debugService.Error(e); _debugService.Error($"Error loading config for {conVar.Name}: {e.Message}");
return false;
} }
_debugService.Log($"Using default value for config: {conVar.Name}");
return conVar.DefaultValue;
} }
private void WriteStream<T>(ConVar<T> conVar, object value) public void SetConfigValue<T>(ConVar<T> conVar, T value)
{ {
using var stream = new MemoryStream(); ArgumentNullException.ThrowIfNull(conVar);
if (value == null) throw new ArgumentNullException(nameof(value));
if (!conVar.Type.IsInstanceOfType(value))
{
_debugService.Error($"Type mismatch for config {conVar.Name}. Expected {conVar.Type}, got {value.GetType()}.");
return;
}
try try
{ {
using var st = new StreamWriter(stream); _debugService.Log($"Saving config: {conVar.Name}");
var ser = JsonSerializer.Serialize(value); var serializedData = JsonSerializer.Serialize(value);
st.Write(ser);
st.Flush(); using var stream = new MemoryStream();
stream.Seek(0, SeekOrigin.Begin); using (var writer = new StreamWriter(stream))
{
writer.Write(serializedData);
writer.Flush();
stream.Seek(0, SeekOrigin.Begin);
}
_fileService.ConfigurationApi.Save(GetFileName(conVar), stream); _fileService.ConfigurationApi.Save(GetFileName(conVar), stream);
} }
catch (Exception e) catch (Exception e)
{ {
_debugService.Error(e); _debugService.Error($"Error saving config for {conVar.Name}: {e.Message}");
} }
} }
private string GetFileName<T>(ConVar<T> conVar) private static string GetFileName<T>(ConVar<T> conVar)
{ {
return conVar.Name + ".json"; return $"{conVar.Name}.json";
} }
} }
public static class ConfigExt public static class ConfigExtensions
{ {
public static bool TryGetConfigValue<T>(this ConfigurationService configurationService, ConVar<T> conVar, [NotNullWhen(true)] out T? value)
public static bool TryGetConfigValue<T>(this ConfigurationService configurationService,ConVar<T> conVar, [NotNullWhen(true)] out T? value)
{ {
ArgumentNullException.ThrowIfNull(configurationService);
ArgumentNullException.ThrowIfNull(conVar);
value = configurationService.GetConfigValue(conVar); value = configurationService.GetConfigValue(conVar);
return value != null; return value != null;
} }

View File

@@ -8,6 +8,7 @@ using System.Text;
using System.Text.Json; using System.Text.Json;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Nebula.Launcher.Utils;
namespace Nebula.Launcher.Services; namespace Nebula.Launcher.Services;
@@ -152,16 +153,3 @@ public class RawResult
return result.Result; return result.Result;
} }
} }
public static class HttpExt
{
public static readonly JsonSerializerOptions JsonWebOptions = new(JsonSerializerDefaults.Web);
public static async Task<T> AsJson<T>(this HttpContent content) where T : notnull
{
var str = await content.ReadAsStringAsync();
return JsonSerializer.Deserialize<T>(str, JsonWebOptions) ??
throw new JsonException("AsJson: did not expect null response");
}
}

View File

@@ -112,7 +112,7 @@ public class RunnerService: IRedialApi
args.Add("--ss14-address"); args.Add("--ss14-address");
args.Add(url.ToString()); args.Add(url.ToString());
_debugService.Debug("Connect to " + url.ToString()); _debugService.Debug("Connect to " + url.ToString() + " " + account.AuthLoginPassword.AuthServer);
await Run(args.ToArray(), buildInfo, this, cancelTokenSource.Token); await Run(args.ToArray(), buildInfo, this, cancelTokenSource.Token);
} }

View File

@@ -0,0 +1,39 @@
using System.Diagnostics;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Threading.Tasks;
namespace Nebula.Launcher.Utils;
public static class Helper
{
public static readonly JsonSerializerOptions JsonWebOptions = new(JsonSerializerDefaults.Web);
public static void OpenBrowser(string url)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Process.Start(new ProcessStartInfo("cmd", $"/c start {url}"));
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Process.Start("xdg-open", url);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Process.Start("open", url);
}
else
{
}
}
public static async Task<T> AsJson<T>(this HttpContent content) where T : notnull
{
var str = await content.ReadAsStringAsync();
return JsonSerializer.Deserialize<T>(str, JsonWebOptions) ??
throw new JsonException("AsJson: did not expect null response");
}
}

View File

@@ -7,6 +7,7 @@ using CommunityToolkit.Mvvm.Input;
using JetBrains.Annotations; using JetBrains.Annotations;
using Nebula.Launcher.Models; using Nebula.Launcher.Models;
using Nebula.Launcher.Services; using Nebula.Launcher.Services;
using Nebula.Launcher.Utils;
using Nebula.Launcher.ViewHelper; using Nebula.Launcher.ViewHelper;
using Nebula.Launcher.Views; using Nebula.Launcher.Views;
@@ -105,6 +106,11 @@ public partial class MainViewModel : ViewModelBase
Popup = true; Popup = true;
} }
public void OpenLink()
{
Helper.OpenBrowser("https://cinka.ru/nebula-launcher/");
}
private void OnPopupRequired(PopupViewModelBase? viewModelBase) private void OnPopupRequired(PopupViewModelBase? viewModelBase)
{ {
if (viewModelBase is null) if (viewModelBase is null)

View File

@@ -85,8 +85,10 @@
Padding="5"> Padding="5">
<Label FontSize="10" Foreground="#777777"> <Label FontSize="10" Foreground="#777777">
<Panel> <Panel>
<TextBlock HorizontalAlignment="Left" VerticalAlignment="Center">cinka.ru</TextBlock> <Button Command="{Binding OpenLink}" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="0" Padding="0" CornerRadius="0" Background="#00000000">
<TextBlock HorizontalAlignment="Right" VerticalAlignment="Center">v0.01</TextBlock> <TextBlock HorizontalAlignment="Left" VerticalAlignment="Center">https://cinka.ru/nebula-launcher/</TextBlock>
</Button>
<TextBlock HorizontalAlignment="Right" VerticalAlignment="Center">prototype-product-v0.01</TextBlock>
</Panel> </Panel>
</Label> </Label>
</Border> </Border>