Refactor LoginPage to MVVM
This commit is contained in:
@@ -1,8 +1,9 @@
|
||||
using Jugenddienst_Stunden.Interfaces;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Net.Http.Json;
|
||||
using Jugenddienst_Stunden.Interfaces;
|
||||
using ZXing.Aztec.Internal;
|
||||
|
||||
namespace Jugenddienst_Stunden.Infrastructure;
|
||||
|
||||
@@ -12,51 +13,68 @@ internal sealed class ApiClient : IApiClient {
|
||||
private readonly ApiOptions _options;
|
||||
private readonly IAppSettings _settings;
|
||||
|
||||
public ApiClient(HttpClient http, ApiOptions options, ITokenProvider tokenProvider, IAppSettings settings) {
|
||||
_http = http;
|
||||
_options = options;
|
||||
_settings = settings;
|
||||
public ApiClient(HttpClient http, ApiOptions options, ITokenProvider tokenProvider, IAppSettings settings) {
|
||||
_http = http;
|
||||
_options = options;
|
||||
_settings = settings;
|
||||
|
||||
_http.Timeout = options.Timeout;
|
||||
if (!_http.DefaultRequestHeaders.Accept.Any())
|
||||
_http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
// Timeout nur einmalig beim Erstellen setzen – spätere Änderungen an HttpClient.Timeout
|
||||
// nach der ersten Verwendung führen zu InvalidOperationException.
|
||||
if (_http.Timeout != options.Timeout)
|
||||
_http.Timeout = options.Timeout;
|
||||
// Standardmäßig JSON akzeptieren; doppelte Einträge vermeiden
|
||||
if (!_http.DefaultRequestHeaders.Accept.Any(h => h.MediaType?.Equals("application/json", StringComparison.OrdinalIgnoreCase) == true))
|
||||
_http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
var token = tokenProvider.GetToken();
|
||||
if (!string.IsNullOrWhiteSpace(token))
|
||||
_http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
// KEINE globalen Header/Properties mehr dynamisch setzen. Authorization wird pro Request gesetzt.
|
||||
|
||||
_json = new JsonSerializerOptions {
|
||||
PropertyNameCaseInsensitive = true,
|
||||
WriteIndented = false,
|
||||
DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull
|
||||
};
|
||||
_json = new JsonSerializerOptions {
|
||||
PropertyNameCaseInsensitive = true,
|
||||
WriteIndented = false,
|
||||
DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull
|
||||
};
|
||||
|
||||
// Globale Converter: erlauben numerische Felder auch als Strings (z.B. user.id)
|
||||
_json.Converters.Add(new Jugenddienst_Stunden.Models.JsonFlexibleInt32Converter());
|
||||
_json.Converters.Add(new Jugenddienst_Stunden.Models.JsonFlexibleNullableInt32Converter());
|
||||
|
||||
// Stelle sicher, dass die BaseAddress sofort aus den aktuellen Settings (Preferences) gesetzt wird
|
||||
// und nicht erst beim ersten Request. Dadurch steht die ApiUrl ab Initialisierung zur Verfügung.
|
||||
EnsureBaseAddress();
|
||||
}
|
||||
// WICHTIG: HttpClient.BaseAddress NICHT dynamisch setzen oder ändern – das verursacht Exceptions,
|
||||
// sobald bereits Requests gestartet wurden. Wir bauen stattdessen absolute URIs pro Request.
|
||||
}
|
||||
|
||||
public Task<T> GetAsync<T>(string path, IDictionary<string, string?>? query = null, CancellationToken ct = default)
|
||||
=> SendAsync<T>(HttpMethod.Get, path, null, query, ct);
|
||||
|
||||
public async Task<T> SendAsync<T>(HttpMethod method, string path, object? body = null,
|
||||
IDictionary<string, string?>? query = null, CancellationToken ct = default) {
|
||||
// Vor jedem Request sicherstellen, dass die (ggf. geänderte) BaseAddress gesetzt ist
|
||||
EnsureBaseAddress();
|
||||
var uri = BuildUri(path, query);
|
||||
using var req = new HttpRequestMessage(method, uri) {
|
||||
Content = body is null ? null : JsonContent.Create(body, options: _json)
|
||||
};
|
||||
public async Task<T> SendAsync<T>(HttpMethod method, string path, object? body = null,
|
||||
IDictionary<string, string?>? query = null, CancellationToken ct = default) {
|
||||
// Absolute URI aus aktuellem Settings‑BaseUrl bauen, ohne HttpClient.BaseAddress zu nutzen.
|
||||
var uri = BuildAbsoluteUri(_settings.ApiUrl, path, query);
|
||||
using var req = new HttpRequestMessage(method, uri);
|
||||
// Authorization PRO REQUEST setzen (immer, wenn Token vorhanden ist)
|
||||
// Hinweis: Das QR-Token kann RFC-unzulässige Zeichen (z. B. '|') enthalten.
|
||||
// AuthenticationHeaderValue würde solche Werte ablehnen. Daher ohne Validierung setzen.
|
||||
var currentToken = _settings.ApiKey;
|
||||
if (!string.IsNullOrWhiteSpace(currentToken)) {
|
||||
// Vorherige Header (falls vorhanden) entfernen, um Duplikate zu vermeiden
|
||||
req.Headers.Remove("Authorization");
|
||||
req.Headers.TryAddWithoutValidation("Authorization", $"Bearer {currentToken}");
|
||||
}
|
||||
if (body is HttpContent httpContent) {
|
||||
req.Content = httpContent;
|
||||
} else if (body is not null) {
|
||||
req.Content = JsonContent.Create(body, options: _json);
|
||||
}
|
||||
|
||||
// Sicherstellen, dass Accept: application/json auch auf Request-Ebene vorhanden ist (z. B. für LoginWithToken GET)
|
||||
if (!req.Headers.Accept.Any(h => h.MediaType?.Equals("application/json", StringComparison.OrdinalIgnoreCase) == true)) {
|
||||
req.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
}
|
||||
|
||||
using var res = await _http.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false);
|
||||
var text = await res.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||||
|
||||
//if (!res.IsSuccessStatusCode)
|
||||
// throw ApiException.From(res.StatusCode, TryGetMessage(text), text);
|
||||
if (!res.IsSuccessStatusCode)
|
||||
throw ApiException.From(res.StatusCode, TryGetMessage(text), text);
|
||||
|
||||
if (res.StatusCode != System.Net.HttpStatusCode.OK) {
|
||||
// Verhalten wie in BaseFunc: bei Fehlerstatus -> "message" aus Body lesen und mit dessen Inhalt eine Exception werfen.
|
||||
@@ -91,22 +109,7 @@ internal sealed class ApiClient : IApiClient {
|
||||
public Task DeleteAsync(string path, IDictionary<string, string?>? query = null, CancellationToken ct = default)
|
||||
=> SendAsync<object>(HttpMethod.Delete, path, null, query, ct);
|
||||
|
||||
private void EnsureBaseAddress() {
|
||||
var baseUrl = _settings.ApiUrl;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(baseUrl)) {
|
||||
throw new InvalidOperationException(
|
||||
"ApiUrl ist leer. Bitte zuerst eine gültige Server-URL setzen (Preferences key 'apiUrl'), " +
|
||||
"z.B. im Login/Setup, bevor API-Aufrufe stattfinden."
|
||||
);
|
||||
}
|
||||
|
||||
// nur setzen, wenn nötig (damit spätere Änderungen nach Login greifen)
|
||||
if (_http.BaseAddress is null || !Uri.Equals(_http.BaseAddress, new Uri(baseUrl, UriKind.Absolute))) {
|
||||
_http.BaseAddress = new Uri(baseUrl, UriKind.Absolute);
|
||||
_http.Timeout = _options.Timeout;
|
||||
}
|
||||
}
|
||||
// Entfernt: EnsureBaseAddress – wir ändern BaseAddress nicht mehr dynamisch.
|
||||
|
||||
private static string TryGetMessage(string text) {
|
||||
try {
|
||||
@@ -119,15 +122,29 @@ internal sealed class ApiClient : IApiClient {
|
||||
return text;
|
||||
}
|
||||
|
||||
private static Uri BuildUri(string path, IDictionary<string, string?>? query) {
|
||||
if (query is null || query.Count == 0)
|
||||
return new Uri(path, UriKind.Relative);
|
||||
private static Uri BuildAbsoluteUri(string baseUrl, string path, IDictionary<string, string?>? query) {
|
||||
if (string.IsNullOrWhiteSpace(baseUrl))
|
||||
throw new InvalidOperationException(
|
||||
"ApiUrl ist leer. Bitte zuerst eine gültige Server-URL setzen (Preferences key 'apiUrl').");
|
||||
|
||||
var sb = new StringBuilder(path);
|
||||
sb.Append(path.Contains('?') ? '&' : '?');
|
||||
sb.Append(string.Join('&', query
|
||||
.Where(kv => kv.Value is not null)
|
||||
.Select(kv => $"{Uri.EscapeDataString(kv.Key)}={Uri.EscapeDataString(kv.Value!)}")));
|
||||
return new Uri(sb.ToString(), UriKind.Relative);
|
||||
}
|
||||
// Basis muss absolut sein (z. B. https://host/appapi/)
|
||||
var baseUri = new Uri(baseUrl, UriKind.Absolute);
|
||||
|
||||
// Pfad relativ zur Basis aufbauen
|
||||
string relativePath = path ?? string.Empty;
|
||||
if (query is not null && query.Count > 0) {
|
||||
var sb = new StringBuilder(relativePath);
|
||||
sb.Append(relativePath.Contains('?') ? '&' : '?');
|
||||
sb.Append(string.Join('&', query
|
||||
.Where(kv => kv.Value is not null)
|
||||
.Select(kv => $"{Uri.EscapeDataString(kv.Key)}={Uri.EscapeDataString(kv.Value!)}")));
|
||||
relativePath = sb.ToString();
|
||||
}
|
||||
|
||||
// Wenn path bereits absolut ist, direkt verwenden
|
||||
if (Uri.TryCreate(relativePath, UriKind.Absolute, out var absoluteFromPath))
|
||||
return absoluteFromPath;
|
||||
|
||||
return new Uri(baseUri, relativePath);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user