Adopt b2b.next's client patterns: services, page state, feedback
Ported from the owner's b2b.next and adapted from MudBlazor to the daisyUI
components:
- LocalizableComponentBase provides CascadingState, Navigation, Toast,
IsLoading/IsDefaultDisabled, WhenOnline/StartOnlinePolling, and after-render
jobs that actually run.
- CascadingState starts with initialised state and polls the online status
with a PeriodicTimer. It reports errors through ILoggingService plus a toast,
and disposes what it holds.
- New pieces:
- ToastService + ToastHost, the snackbar, with AddResponseError/Success/
Warning/Exception in SUtility;
- ErrorViewer, which shows the validation messages plus AdditionalError(s);
- LoggingService, which writes to the console and the IndexedDB client log.
- HttpService is rebuilt and registered:
- auth levels Get/Post/Delete, *Anon and *TotallyAnon;
- retry with backoff;
- classified failures (FailureCodes) instead of exceptions;
- HTTP 410 on cancel;
- the "default" client.
ReadWebResult and DefaultReadFromJsonAsync read its responses.
- ClientJsonContext is source-generated, and SUtility.DefaultSerializer and
Blazored.LocalStorage use it.
- WebResult gains a C# 14 IsInvalid extension property.
The code follows the imported rules:
- Every service and async helper takes a CancellationToken last.
- Primary constructors replace constructor-plus-fields.
- MessagesService and IStorage return Task<WebResult> / Task<List<T>>.
MessagesService is still mock, building its results in memory; the seed
feed and thread moved to Faker.
- Index and ExpandMessage follow the page pattern: an offline guard with
WhenOnline, LoadData, and early returns with toasts on the results they used
to ignore. ExpandMessage reloads on route change and shows "not found"
instead of a null message.
- Model and state collections are [], and the fake identity defaults moved
out of the models.
- Components:
- no ?. chains over initialised state;
- [Inject] instead of @inject;
- IsDefaultDisabled on the actions;
- autocomplete on every text input;
- Localizer[key, args] instead of string.Format;
- the localizer no longer leaks its inner _pLocalizer.
- Settings → General gains a language picker (English/Italiano), and
SetDefaultCulture limits the culture to those two.
Bugs fixed along the way:
- A compose with untouched (null) content passed the empty check.
- File errors were joined with <br/> and rendered as markup.
- ClientLogs.ErrorMessage() threw on warnings.
- CoalescingStringLocalizer[key, args] showed a raw "{0}" for missing keys.
- AppStatusService exposed a call to a JS function that doesn't exist.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LsXgEaXee4GCU1hwYgPJXw
This commit is contained in:
1 parent
ca060f25fb
commit
95428430c0
55 files changed
+1844
-1337
No files matched your search
@@ -4,20 +4,12 @@ using Microsoft.JSInterop;
|
||||
|
||||
namespace decePubClient.Services;
|
||||
|
||||
public class AppStatusService
|
||||
public class AppStatusService(IJSRuntime jsRuntime)
|
||||
{
|
||||
readonly IJSRuntime JsRuntime;
|
||||
readonly IJSInProcessRuntime JsSyncRuntime;
|
||||
readonly IJSInProcessRuntime JsSyncRuntime = (IJSInProcessRuntime)jsRuntime;
|
||||
|
||||
public AppStatusService(IJSRuntime JSRuntime)
|
||||
{
|
||||
JsRuntime = JSRuntime;
|
||||
JsSyncRuntime = (IJSInProcessRuntime)JSRuntime;
|
||||
}
|
||||
|
||||
public async ValueTask<bool> IsOnline() => await JsSyncRuntime.InvokeAsync<bool>("isOnline");
|
||||
|
||||
public bool InputCaptureSupported() => JsSyncRuntime.Invoke<bool>("inputCaptureSupported");
|
||||
public async ValueTask<bool> IsOnline(CancellationToken cancellationToken = default) =>
|
||||
await jsRuntime.InvokeAsync<bool>("isOnline", cancellationToken);
|
||||
|
||||
public bool IsServiceWorkerAvailable() => JsSyncRuntime.Invoke<bool>("isServiceWorkerAvailable");
|
||||
|
||||
@@ -31,15 +23,11 @@ public class AppStatusService
|
||||
|
||||
public void ClearAppBadge() => JsSyncRuntime.InvokeVoid("clearAppBadge");
|
||||
|
||||
public async ValueTask ClearCache()
|
||||
{
|
||||
await JsRuntime.InvokeVoidAsync("clearCache");
|
||||
}
|
||||
public async ValueTask ClearCache(CancellationToken cancellationToken = default) =>
|
||||
await jsRuntime.InvokeVoidAsync("clearCache", cancellationToken);
|
||||
|
||||
public async ValueTask ClearLocalStorage()
|
||||
{
|
||||
await JsRuntime.InvokeVoidAsync("clearLocalStorage");
|
||||
}
|
||||
public async ValueTask ClearLocalStorage(CancellationToken cancellationToken = default) =>
|
||||
await jsRuntime.InvokeVoidAsync("clearLocalStorage", cancellationToken);
|
||||
|
||||
public void ReloadPage()
|
||||
{
|
||||
@@ -55,7 +43,9 @@ public class AppStatusService
|
||||
|
||||
public bool CanShare() => JsSyncRuntime.Invoke<bool>("canShareStuff");
|
||||
|
||||
public async ValueTask ShareTextUrl(string title, string text, Uri uri) => await JsRuntime.InvokeVoidAsync("shareTextUrl", title, text, uri.ToString());
|
||||
public async ValueTask ShareTextUrl(string title, string text, Uri uri, CancellationToken cancellationToken = default) =>
|
||||
await jsRuntime.InvokeVoidAsync("shareTextUrl", cancellationToken, title, text, uri.ToString());
|
||||
|
||||
public async ValueTask ShareText(string title, string text) => await JsRuntime.InvokeVoidAsync("shareText", title, text);
|
||||
public async ValueTask ShareText(string title, string text, CancellationToken cancellationToken = default) =>
|
||||
await jsRuntime.InvokeVoidAsync("shareText", cancellationToken, title, text);
|
||||
}
|
||||
@@ -6,50 +6,59 @@ using PrivaPub.ClientModels.Resources;
|
||||
|
||||
namespace collAnon.Client.Services
|
||||
{
|
||||
public sealed class CoalescingStringLocalizer
|
||||
/// <summary>
|
||||
/// The app's localizer: looks a key up in Resources/AllStrings, then in PrivaPub.ClientModels' FieldsNameResource and
|
||||
/// ErrorsResource, and falls back to the key itself (formatted with the arguments), so a missing key shows its
|
||||
/// English text instead of failing.
|
||||
/// </summary>
|
||||
public sealed class CoalescingStringLocalizer(IStringLocalizer<AllStrings> baseLocalizer, IStringLocalizer<FieldsNameResource> fieldsLocalizer,
|
||||
IStringLocalizer<ErrorsResource> errorsLocalizer)
|
||||
{
|
||||
public readonly IStringLocalizer<AllStrings> _pLocalizer;
|
||||
readonly IStringLocalizer<FieldsNameResource> _fLocalizer;
|
||||
readonly IStringLocalizer<ErrorsResource> _eLocalizer;
|
||||
public IStringLocalizer Base => baseLocalizer;
|
||||
public IStringLocalizer Fields => fieldsLocalizer;
|
||||
public IStringLocalizer Errors => errorsLocalizer;
|
||||
|
||||
public CoalescingStringLocalizer(
|
||||
IStringLocalizer<AllStrings> pLocalizer,
|
||||
IStringLocalizer<FieldsNameResource> fLocalizer,
|
||||
IStringLocalizer<ErrorsResource> eLocalizer) =>
|
||||
(_pLocalizer, _fLocalizer, _eLocalizer) =
|
||||
(pLocalizer, fLocalizer, eLocalizer);
|
||||
|
||||
internal LocalizedString this[string name]
|
||||
public LocalizedString this[string name]
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_pLocalizer[name].ResourceNotFound)
|
||||
if (_fLocalizer[name].ResourceNotFound)
|
||||
if (_eLocalizer[name].ResourceNotFound)
|
||||
return new(name, name, false);
|
||||
else
|
||||
return _eLocalizer[name];
|
||||
else
|
||||
return _fLocalizer[name];
|
||||
else
|
||||
return _pLocalizer[name];
|
||||
try
|
||||
{
|
||||
if (!baseLocalizer[name].ResourceNotFound)
|
||||
return baseLocalizer[name];
|
||||
if (!fieldsLocalizer[name].ResourceNotFound)
|
||||
return fieldsLocalizer[name];
|
||||
if (!errorsLocalizer[name].ResourceNotFound)
|
||||
return errorsLocalizer[name];
|
||||
return new(name, name, true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine(ex.ToString());
|
||||
return new(name, name, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal LocalizedString this[string name, params object[] arguments]
|
||||
public LocalizedString this[string name, params object[] arguments]
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_pLocalizer[name].ResourceNotFound)
|
||||
if (_fLocalizer[name].ResourceNotFound)
|
||||
if (_eLocalizer[name].ResourceNotFound)
|
||||
return new(name, name, false);
|
||||
else
|
||||
return _eLocalizer[name, arguments];
|
||||
else
|
||||
return _fLocalizer[name, arguments];
|
||||
else
|
||||
return _pLocalizer[name, arguments];
|
||||
try
|
||||
{
|
||||
if (!baseLocalizer[name].ResourceNotFound)
|
||||
return baseLocalizer[name, arguments];
|
||||
if (!fieldsLocalizer[name].ResourceNotFound)
|
||||
return fieldsLocalizer[name, arguments];
|
||||
if (!errorsLocalizer[name].ResourceNotFound)
|
||||
return errorsLocalizer[name, arguments];
|
||||
return new(name, string.Format(name, arguments), true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine(ex.ToString());
|
||||
return new(name, name, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+182
-161
@@ -1,196 +1,217 @@
|
||||
using Blazored.LocalStorage;
|
||||
using System.Globalization;
|
||||
using System.Net.Http.Json;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
|
||||
using collAnon.Client.Services;
|
||||
|
||||
using decePubClient.Helpers;
|
||||
using decePubClient.Models;
|
||||
|
||||
namespace decePubClient.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Requests to the PrivaPub API through the "default" HttpClient (AppConfiguration.ApiBaseAddress), at three
|
||||
/// authentication levels: Get/Post/Delete need a valid token and sign out on 401, *Anon add the token when there is
|
||||
/// one, *TotallyAnon never send it. Nothing throws: a failure comes back as a response carrying an invalid WebResult
|
||||
/// (SUtility.ClassifiedFailure, read with ExtensionMethods.ReadWebResult), a cancelled request as HTTP 410.
|
||||
/// With retryOnError, 408/429/502/503/504 and transport errors are retried after 1, 2, 4, 8, 16 and 29 seconds, then
|
||||
/// every 60, plus jitter, for at most 10 minutes.
|
||||
/// </summary>
|
||||
public interface IHttpService
|
||||
{
|
||||
Task<HttpResponseMessage> Get(string uri, object payload = default, string[] queryParams = default);
|
||||
Task<HttpResponseMessage> Get(string uri, string[] queryParams = default, bool retryOnError = false, CancellationToken cancellationToken = default);
|
||||
|
||||
Task<HttpResponseMessage> GetAnon(string uri, object payload = default, string[] queryParams = default);
|
||||
Task<HttpResponseMessage> GetAnon(string uri, string[] queryParams = default, bool retryOnError = false, CancellationToken cancellationToken = default);
|
||||
|
||||
Task<HttpResponseMessage> Post(string uri, object payload = default);
|
||||
Task<HttpResponseMessage> GetTotallyAnon(string uri, string[] queryParams = default, bool retryOnError = false,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
Task<HttpResponseMessage> PostAnon(string uri, object payload = default);
|
||||
Task<HttpResponseMessage> Post(string uri, object payload = default, bool retryOnError = false, CancellationToken cancellationToken = default);
|
||||
|
||||
Task<HttpResponseMessage> Delete(string uri, string[] queryParams = default, object payload = default);
|
||||
Task<HttpResponseMessage> PostAnon(string uri, object payload = default, bool retryOnError = false, CancellationToken cancellationToken = default);
|
||||
|
||||
Task<HttpResponseMessage> PostTotallyAnon(string uri, object payload = default, bool retryOnError = false,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
Task<HttpResponseMessage> Delete(string uri, string[] queryParams = default, object payload = default, bool retryOnError = false,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
Task<HttpResponseMessage> DeleteTotallyAnon(string uri, string[] queryParams = default, object payload = default, bool retryOnError = false,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
public class HttpService : IHttpService
|
||||
public class HttpService(IHttpClientFactory httpClientFactory, TokenAuthStateProvider authStateProvider, AppStatusService statusService,
|
||||
ILoggingService logger, CoalescingStringLocalizer localizer) : IHttpService
|
||||
{
|
||||
readonly IHttpClientFactory HttpClientFactory;
|
||||
readonly TokenAuthStateProvider AuthStateProvider;
|
||||
readonly ILogger<HttpService> Logger;
|
||||
readonly ILocalStorageService Storage;
|
||||
readonly IStorage DbStorage;
|
||||
static readonly int[] RetryRampUpDelaysMs = [1_000, 2_000, 4_000, 8_000, 16_000, 29_000];
|
||||
const int RetryIndefiniteDelayMs = 60_000;
|
||||
static readonly TimeSpan RetryDeadline = TimeSpan.FromMinutes(10);
|
||||
static readonly int[] RetryableStatusCodes = [408, 429, 502, 503, 504];
|
||||
|
||||
public HttpService(
|
||||
IHttpClientFactory httpClientFactory,
|
||||
TokenAuthStateProvider authStateProvider,
|
||||
ILogger<HttpService> logger,
|
||||
ILocalStorageService storage,
|
||||
IStorage dbStorage)
|
||||
{
|
||||
HttpClientFactory = httpClientFactory;
|
||||
AuthStateProvider = authStateProvider;
|
||||
Logger = logger;
|
||||
Storage = storage;
|
||||
DbStorage = dbStorage;
|
||||
}
|
||||
readonly HttpClient httpClient = httpClientFactory.CreateClient("default");
|
||||
|
||||
public async Task<HttpResponseMessage> Get(string uri, object payload = default, string[] queryParams = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
uri = $"{CultureInfo.DefaultThreadCurrentCulture.TwoLetterISOLanguageName}/{uri}";
|
||||
var request = default(HttpRequestMessage);
|
||||
if (queryParams != null)
|
||||
request = new(HttpMethod.Get, string.Join('?', uri, string.Join('&', queryParams)));
|
||||
else
|
||||
request = new(HttpMethod.Get, uri);
|
||||
if (payload != null)
|
||||
request.Content = JsonContent.Create(payload);
|
||||
return await SendRequest(request);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(Get)}:{uri}");
|
||||
await DbStorage.AddLog(ex, $"{nameof(Get)}:{uri}");
|
||||
return new(HttpStatusCode.ServiceUnavailable);
|
||||
}
|
||||
}
|
||||
public Task<HttpResponseMessage> Get(string uri, string[] queryParams = default, bool retryOnError = false, CancellationToken cancellationToken = default) =>
|
||||
Send(nameof(Get), () => BuildRequest(HttpMethod.Get, uri, queryParams: queryParams), SendAuthRequest, retryOnError, cancellationToken);
|
||||
|
||||
public async Task<HttpResponseMessage> Post(string uri, object payload = default)
|
||||
public Task<HttpResponseMessage> GetAnon(string uri, string[] queryParams = default, bool retryOnError = false, CancellationToken cancellationToken = default) =>
|
||||
Send(nameof(GetAnon), () => BuildRequest(HttpMethod.Get, uri, queryParams: queryParams), SendAuthIfAvailableRequest, retryOnError,
|
||||
cancellationToken);
|
||||
|
||||
public Task<HttpResponseMessage> GetTotallyAnon(string uri, string[] queryParams = default, bool retryOnError = false,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
Send(nameof(GetTotallyAnon), () => BuildRequest(HttpMethod.Get, uri, queryParams: queryParams), httpClient.SendAsync, retryOnError,
|
||||
cancellationToken);
|
||||
|
||||
public Task<HttpResponseMessage> Post(string uri, object payload = default, bool retryOnError = false, CancellationToken cancellationToken = default) =>
|
||||
Send(nameof(Post), () => BuildRequest(HttpMethod.Post, uri, payload, forceContent: true), SendAuthRequest, retryOnError, cancellationToken);
|
||||
|
||||
public Task<HttpResponseMessage> PostAnon(string uri, object payload = default, bool retryOnError = false, CancellationToken cancellationToken = default) =>
|
||||
Send(nameof(PostAnon), () => BuildRequest(HttpMethod.Post, uri, payload, forceContent: true), SendAuthIfAvailableRequest, retryOnError,
|
||||
cancellationToken);
|
||||
|
||||
public Task<HttpResponseMessage> PostTotallyAnon(string uri, object payload = default, bool retryOnError = false,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
Send(nameof(PostTotallyAnon), () => BuildRequest(HttpMethod.Post, uri, payload, forceContent: true), httpClient.SendAsync, retryOnError,
|
||||
cancellationToken);
|
||||
|
||||
public Task<HttpResponseMessage> Delete(string uri, string[] queryParams = default, object payload = default, bool retryOnError = false,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
Send(nameof(Delete), () => BuildRequest(HttpMethod.Delete, uri, payload, queryParams), SendAuthRequest, retryOnError, cancellationToken);
|
||||
|
||||
public Task<HttpResponseMessage> DeleteTotallyAnon(string uri, string[] queryParams = default, object payload = default, bool retryOnError = false,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
Send(nameof(DeleteTotallyAnon), () => BuildRequest(HttpMethod.Delete, uri, payload, queryParams), httpClient.SendAsync, retryOnError,
|
||||
cancellationToken);
|
||||
|
||||
async Task<HttpResponseMessage> Send(string caller, Func<HttpRequestMessage> requestFactory,
|
||||
Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> send, bool retryOnError, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
var deadline = DateTime.UtcNow + RetryDeadline;
|
||||
var attempt = 0;
|
||||
while (true)
|
||||
{
|
||||
uri = $"{CultureInfo.DefaultThreadCurrentCulture.TwoLetterISOLanguageName}/{uri}";
|
||||
var request = new HttpRequestMessage(HttpMethod.Post, uri)
|
||||
// A request message can be sent once, so every attempt builds its own.
|
||||
var request = requestFactory();
|
||||
var where = $"{nameof(HttpService)}.{caller}:{request.RequestUri?.OriginalString}";
|
||||
var failure = default(string);
|
||||
var transportException = default(Exception);
|
||||
try
|
||||
{
|
||||
Content = JsonContent.Create(payload)
|
||||
};
|
||||
return await SendRequest(request);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(Post)}:{uri}");
|
||||
await DbStorage.AddLog(ex, $"{nameof(Post)}:{uri}");
|
||||
return new(HttpStatusCode.ServiceUnavailable);
|
||||
}
|
||||
}
|
||||
var response = await send(request, cancellationToken);
|
||||
var status = (int)response.StatusCode;
|
||||
if (!retryOnError || !RetryableStatusCodes.Contains(status))
|
||||
return status > 499 ? ServerError(response) : response;
|
||||
|
||||
public async Task<HttpResponseMessage> GetAnon(string uri, object payload = default, string[] queryParams = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
uri = $"{CultureInfo.DefaultThreadCurrentCulture.TwoLetterISOLanguageName}/{uri}";
|
||||
var request = default(HttpRequestMessage);
|
||||
if (queryParams != null)
|
||||
request = new(HttpMethod.Get, string.Join('?', uri, string.Join('&', queryParams)));
|
||||
else
|
||||
request = new(HttpMethod.Get, uri);
|
||||
if (payload != null)
|
||||
request.Content = JsonContent.Create(payload);
|
||||
return await SendAnonRequest(request);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(GetAnon)}:{uri}");
|
||||
await DbStorage.AddLog(ex, $"{nameof(GetAnon)}:{uri}");
|
||||
return new(HttpStatusCode.ServiceUnavailable);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<HttpResponseMessage> PostAnon(string uri, object payload = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
uri = $"{CultureInfo.DefaultThreadCurrentCulture.TwoLetterISOLanguageName}/{uri}";
|
||||
var request = new HttpRequestMessage(HttpMethod.Post, uri)
|
||||
failure = $"HTTP {status}";
|
||||
response.Dispose();
|
||||
}
|
||||
catch (Exception) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
Content = JsonContent.Create(payload)
|
||||
};
|
||||
return await SendAnonRequest(request);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(PostAnon)}:{uri}");
|
||||
await DbStorage.AddLog(ex, $"{nameof(PostAnon)}:{uri}");
|
||||
return new(HttpStatusCode.ServiceUnavailable);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<HttpResponseMessage> Delete(string uri, string[] queryParams = default, object payload = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
uri = $"{CultureInfo.DefaultThreadCurrentCulture.TwoLetterISOLanguageName}/{uri}";
|
||||
var request = default(HttpRequestMessage);
|
||||
if (queryParams != null)
|
||||
request = new(HttpMethod.Delete, string.Join('?', uri, string.Join('&', queryParams)));
|
||||
else
|
||||
request = new(HttpMethod.Delete, uri);
|
||||
if (payload != null)
|
||||
request.Content = JsonContent.Create(payload);
|
||||
return await SendRequest(request);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(Delete)}:{uri}");
|
||||
await DbStorage.AddLog(ex, $"{nameof(Delete)}:{uri}");
|
||||
return new(HttpStatusCode.ServiceUnavailable);
|
||||
}
|
||||
}
|
||||
|
||||
// helper methods
|
||||
async Task<HttpResponseMessage> SendRequest(HttpRequestMessage request)
|
||||
{
|
||||
try
|
||||
{
|
||||
var authData = await Storage.GetItemAsync<AuthData>(nameof(AuthData));
|
||||
var isApiUrl = !request.RequestUri?.IsAbsoluteUri;
|
||||
if (isApiUrl.HasValue && isApiUrl.Value)
|
||||
request.Headers.Authorization = new("Bearer", authData.Token);
|
||||
|
||||
var response = await HttpClientFactory.CreateClient().SendAsync(request);
|
||||
if (response.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
|
||||
return SUtility.DefaultTaskCancelled();
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException)
|
||||
{
|
||||
Logger.LogWarning($"{nameof(SendRequest)}:401/403:{request.RequestUri?.OriginalString}:{await response.Content.ReadAsStringAsync()}");
|
||||
await DbStorage.AddLog($"{nameof(SendRequest)}:401/403:{request.RequestUri?.OriginalString}:{await response.Content.ReadAsStringAsync()}", $"{nameof(SendRequest)}:{request.RequestUri?.OriginalString}");
|
||||
await AuthStateProvider.LogoutAsync();
|
||||
if (!retryOnError)
|
||||
{
|
||||
await logger.ProcessError(ex, where, cancellationToken);
|
||||
return await DescribeUnreachable(ex, 1, cancellationToken);
|
||||
}
|
||||
|
||||
failure = ex.Message;
|
||||
transportException = ex;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await logger.ProcessError(ex, where, cancellationToken);
|
||||
return SUtility.ClassifiedFailure(FailureCodes.ClientError,
|
||||
localizer["The request could not be prepared. Reload the page and try again."], HttpStatusCode.ServiceUnavailable);
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(SendRequest)}:{request.RequestUri?.OriginalString}");
|
||||
await DbStorage.AddLog(ex, $"{nameof(SendRequest)}:{request.RequestUri?.OriginalString}");
|
||||
return new(HttpStatusCode.ServiceUnavailable);
|
||||
var delay = attempt < RetryRampUpDelaysMs.Length ? RetryRampUpDelaysMs[attempt] : RetryIndefiniteDelayMs;
|
||||
delay += Random.Shared.Next(0, delay / 4);
|
||||
if (deadline - DateTime.UtcNow <= TimeSpan.FromMilliseconds(delay))
|
||||
{
|
||||
await logger.ProcessError($"Gave up after {attempt + 1} attempts. {failure}", where, cancellationToken);
|
||||
if (transportException is not null)
|
||||
return await DescribeUnreachable(transportException, attempt + 1, cancellationToken);
|
||||
return SUtility.ClassifiedFailure(FailureCodes.RetriesExhausted,
|
||||
localizer["The server is still not answering after {0} attempts. Try again later.", attempt + 1], HttpStatusCode.ServiceUnavailable);
|
||||
}
|
||||
|
||||
await logger.ProcessWarning($"Attempt {attempt + 1} failed, retrying in {delay}ms. {failure}", where, cancellationToken);
|
||||
try
|
||||
{
|
||||
await Task.Delay(delay, cancellationToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return SUtility.DefaultTaskCancelled();
|
||||
}
|
||||
|
||||
attempt++;
|
||||
}
|
||||
}
|
||||
|
||||
async Task<HttpResponseMessage> SendAnonRequest(HttpRequestMessage request)
|
||||
HttpResponseMessage ServerError(HttpResponseMessage response)
|
||||
{
|
||||
try
|
||||
var status = response.StatusCode;
|
||||
response.Dispose();
|
||||
return SUtility.ClassifiedFailure(FailureCodes.ServerError, localizer["The server reported an internal error (HTTP {0}).", (int)status], status);
|
||||
}
|
||||
|
||||
/// <summary>Why a request got no answer: the device is offline, it timed out, retries ran out, or the server is unreachable.</summary>
|
||||
async Task<HttpResponseMessage> DescribeUnreachable(Exception exception, int attempts, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!await statusService.IsOnline(cancellationToken))
|
||||
return SUtility.ClassifiedFailure(FailureCodes.DeviceOffline,
|
||||
localizer["This device is offline. Check the connection and try again."], HttpStatusCode.ServiceUnavailable);
|
||||
|
||||
if (exception is TaskCanceledException { InnerException: TimeoutException })
|
||||
return SUtility.ClassifiedFailure(FailureCodes.Timeout,
|
||||
localizer["The server took too long to answer. Try again later."], HttpStatusCode.ServiceUnavailable);
|
||||
|
||||
if (attempts > 1)
|
||||
return SUtility.ClassifiedFailure(FailureCodes.RetriesExhausted,
|
||||
localizer["The server is still not answering after {0} attempts. Try again later.", attempts], HttpStatusCode.ServiceUnavailable);
|
||||
|
||||
return SUtility.ClassifiedFailure(FailureCodes.ApiUnreachable,
|
||||
localizer["The server can't be reached. Try again later."], HttpStatusCode.ServiceUnavailable);
|
||||
}
|
||||
|
||||
async Task<HttpResponseMessage> SendAuthRequest(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
var token = await authStateProvider.GetToken(cancellationToken);
|
||||
if (token is null)
|
||||
{
|
||||
var authData = await Storage.GetItemAsync<AuthData>(nameof(AuthData));
|
||||
if (!string.IsNullOrEmpty(authData?.Token))
|
||||
request.Headers.Authorization = new("Bearer", authData.Token);
|
||||
|
||||
var response = await HttpClientFactory.CreateClient().SendAsync(request);
|
||||
logger.Process($"NO_TOKEN:{request.RequestUri?.OriginalString}", nameof(SendAuthRequest), LogLevel.Warning);
|
||||
return SUtility.DefaultUnauthorized(localizer["Your session has expired. Sign in again."]);
|
||||
}
|
||||
|
||||
request.Headers.Authorization = new("Bearer", token);
|
||||
var response = await httpClient.SendAsync(request, cancellationToken);
|
||||
if (response.StatusCode is not HttpStatusCode.Unauthorized)
|
||||
return response;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, $"{nameof(SendAnonRequest)}:{request.RequestUri?.OriginalString}");
|
||||
await DbStorage.AddLog(ex, $"{nameof(SendAnonRequest)}:{request.RequestUri?.OriginalString}");
|
||||
return new(HttpStatusCode.ServiceUnavailable);
|
||||
}
|
||||
|
||||
response.Dispose();
|
||||
await authStateProvider.LogoutAsync(cancellationToken: cancellationToken);
|
||||
return SUtility.DefaultUnauthorized(localizer["Your session has expired. Sign in again."]);
|
||||
}
|
||||
|
||||
async Task<HttpResponseMessage> SendAuthIfAvailableRequest(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
var token = await authStateProvider.GetToken(cancellationToken);
|
||||
if (token is not null)
|
||||
request.Headers.Authorization = new("Bearer", token);
|
||||
return await httpClient.SendAsync(request, cancellationToken);
|
||||
}
|
||||
|
||||
static HttpRequestMessage BuildRequest(HttpMethod method, string uri, object payload = default, string[] queryParams = default,
|
||||
bool forceContent = false)
|
||||
{
|
||||
var target = queryParams is { Length: > 0 } ? $"{uri}?{string.Join('&', queryParams)}" : uri;
|
||||
var request = new HttpRequestMessage(method, target);
|
||||
if (payload is not null || forceContent)
|
||||
request.Content = JsonContent.Create(payload, payload?.GetType() ?? typeof(object), options: SUtility.DefaultSerializer);
|
||||
return request;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
namespace decePubClient.Services;
|
||||
|
||||
public interface ILoggingService
|
||||
{
|
||||
ValueTask ProcessError(Exception exception, string where, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask ProcessError(string message, string where, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask ProcessWarning(string message, string where, CancellationToken cancellationToken = default);
|
||||
|
||||
void Process(string message, string where = default, LogLevel level = LogLevel.Information);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes to the browser console through ILogger and keeps errors and warnings in the IndexedDB client log, so they
|
||||
/// survive a reload. Never throws: logging must not break the code that is reporting a failure.
|
||||
/// </summary>
|
||||
public class LoggingService(IStorage storage, ILogger<LoggingService> logger) : ILoggingService
|
||||
{
|
||||
public void Process(string message, string where = default, LogLevel level = LogLevel.Information) =>
|
||||
logger.Log(level, "[{Where}] {Message}", where ?? "N/A", message);
|
||||
|
||||
public async ValueTask ProcessError(Exception exception, string where, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
logger.LogError(exception, "[{Where}]", where);
|
||||
await storage.AddLog(exception, where, cancellationToken);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, $"{nameof(LoggingService)}.{nameof(ProcessError)}");
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask ProcessError(string message, string where, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
logger.LogError("[{Where}] {Message}", where, message);
|
||||
await storage.AddLog(message, where, cancellationToken);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, $"{nameof(LoggingService)}.{nameof(ProcessError)}");
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask ProcessWarning(string message, string where, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
logger.LogWarning("[{Where}] {Message}", where, message);
|
||||
await storage.AddLog(message, where, cancellationToken);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, $"{nameof(LoggingService)}.{nameof(ProcessWarning)}");
|
||||
}
|
||||
}
|
||||
}
|
||||
+125
-327
@@ -1,389 +1,187 @@
|
||||
using decePubClient.Helpers;
|
||||
using decePubClient.Helpers;
|
||||
using decePubClient.Models;
|
||||
using decePubClient.Models.Types;
|
||||
using Markdig;
|
||||
|
||||
using PrivaPub.ClientModels;
|
||||
|
||||
namespace decePubClient.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// The IndexedDB database "data" (schema in GenericExtensions.AddIndexedDb): messages and the client log. Lists
|
||||
/// come back empty on failure, mutations as an invalid WebResult; nothing throws. Failures are logged with ILogger
|
||||
/// only, because ILoggingService writes its log through this class.
|
||||
/// </summary>
|
||||
public interface IStorage
|
||||
{
|
||||
ValueTask<List<Message>> GetMessages();
|
||||
ValueTask<Message> GetMessage(string messageId);
|
||||
ValueTask<string> AddMessages(List<Message> messages);
|
||||
ValueTask<string> UpdateMessages(List<Message> messages);
|
||||
ValueTask<string> RemoveMessage(string messageId);
|
||||
Task<List<Message>> GetMessages(CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<ICollection<ClientLogs>> GetClientLogs();
|
||||
ValueTask AddLog(Exception exception, string where);
|
||||
ValueTask AddLog(string message, string where);
|
||||
Task<Message> GetMessage(string messageId, CancellationToken cancellationToken = default);
|
||||
|
||||
ValueTask<bool> RemoveAll(bool includeClientLogs = false);
|
||||
Task<WebResult> AddMessages(List<Message> messages, CancellationToken cancellationToken = default);
|
||||
|
||||
Task<WebResult> UpdateMessages(List<Message> messages, CancellationToken cancellationToken = default);
|
||||
|
||||
Task<WebResult> RemoveMessage(string messageId, CancellationToken cancellationToken = default);
|
||||
|
||||
Task<List<ClientLogs>> GetClientLogs(CancellationToken cancellationToken = default);
|
||||
|
||||
Task AddLog(Exception exception, string where, CancellationToken cancellationToken = default);
|
||||
|
||||
Task AddLog(string message, string where, CancellationToken cancellationToken = default);
|
||||
|
||||
Task<WebResult> RemoveAll(bool includeClientLogs = false, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
public class Storage : IStorage
|
||||
public class Storage(IndexedDb db, ILogger<Storage> logger) : IStorage
|
||||
{
|
||||
readonly IndexedDb _db;
|
||||
readonly ILogger<Storage> _logger;
|
||||
/// <summary>The client log keeps at most this many entries; past it the oldest half is dropped.</summary>
|
||||
const int MaxLogs = 100;
|
||||
|
||||
public Storage(IndexedDb indexedDb, ILogger<Storage> logger)
|
||||
#region Messages
|
||||
|
||||
public async Task<Message> GetMessage(string messageId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
_db = indexedDb;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
#region Messagges
|
||||
|
||||
public async ValueTask<Message> GetMessage(string messageId)
|
||||
{
|
||||
await _db.OpenIndexedDb();
|
||||
var message = await _db.GetByKey<string, Message>(nameof(Message), messageId);
|
||||
|
||||
if (message is null)
|
||||
try
|
||||
{
|
||||
var messages = await GetMessages();
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
await db.OpenIndexedDb();
|
||||
var message = await db.GetByKey<string, Message>(nameof(Message), messageId);
|
||||
if (message is not null)
|
||||
return message;
|
||||
|
||||
var messages = await GetMessages(cancellationToken);
|
||||
return messages.FirstOrDefault(m => m.MessageId == messageId);
|
||||
}
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
public async ValueTask<List<Message>> GetMessages()
|
||||
{
|
||||
await _db.OpenIndexedDb();
|
||||
var messages = await _db.GetAll<Message>(nameof(Message)) ?? new();
|
||||
|
||||
|
||||
if (messages.Count == 0)
|
||||
catch (Exception ex)
|
||||
{
|
||||
messages.Add(new()
|
||||
{
|
||||
RootMessageId = default,
|
||||
MessageId = "992167EE-8947-4823-B1E2-B4E1019B6974",
|
||||
User = Faker.GetRandomUser(),
|
||||
MessageType = (MessageType)Random.Shared.Next(0, 4),
|
||||
Title = default,
|
||||
Content = "test di messaggio normale senza titolo",
|
||||
Medias = new(),
|
||||
CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
|
||||
IsFavourite = Random.Shared.Next() % 2 == 0,
|
||||
BoostsCounter = Random.Shared.Next(0, 100),
|
||||
IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
|
||||
});
|
||||
messages.Add(new()
|
||||
{
|
||||
RootMessageId = default,
|
||||
MessageId = "C5307644-4EA8-4B5F-A240-7CFE4DE34741",
|
||||
User = Faker.GetRandomUser(),
|
||||
MessageType = (MessageType)Random.Shared.Next(0, 4),
|
||||
Title = "sopra la panca la capra canta",
|
||||
Content = Markdown.ToHtml("test di messaggio con titolo"),
|
||||
Medias = new(),
|
||||
CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
|
||||
IsFavourite = Random.Shared.Next() % 2 == 0,
|
||||
BoostsCounter = Random.Shared.Next(0, 100),
|
||||
IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
|
||||
});
|
||||
messages.Add(new()
|
||||
{
|
||||
RootMessageId = default,
|
||||
MessageId = "E473D562-D210-4453-93DA-157D4B90B0D8",
|
||||
User = Faker.GetRandomUser(),
|
||||
MessageType = (MessageType)Random.Shared.Next(0, 4),
|
||||
Title = default,
|
||||
Content = "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd test di messaggio con overflow del testo",
|
||||
Medias = new(),
|
||||
CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
|
||||
IsFavourite = Random.Shared.Next() % 2 == 0,
|
||||
BoostsCounter = Random.Shared.Next(0, 100),
|
||||
IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
|
||||
});
|
||||
messages.Add(new()
|
||||
{
|
||||
RootMessageId = default,
|
||||
MessageId = "adf89dc6-0484-430e-a7c9-fcb1179b0c28",
|
||||
User = Faker.GetRandomUser(),
|
||||
MessageType = (MessageType)Random.Shared.Next(0, 4),
|
||||
Title = default,
|
||||
Content = "test video",
|
||||
Medias = new()
|
||||
{
|
||||
new()
|
||||
{
|
||||
FileName = "8252d175e714db88beb8ee0349dbac90405d3d5148e96e0cfd7de3b0876dbb1b.mp4",
|
||||
Url = "https://ihatebeinga.live/media/8252d175e714db88beb8ee0349dbac90405d3d5148e96e0cfd7de3b0876dbb1b.mp4",
|
||||
AltText = "https://ihatebeinga.live/media/8252d175e714db88beb8ee0349dbac90405d3d5148e96e0cfd7de3b0876dbb1b.mp4",
|
||||
ContentType = "video/mp4"
|
||||
}
|
||||
},
|
||||
CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
|
||||
IsFavourite = Random.Shared.Next() % 2 == 0,
|
||||
BoostsCounter = Random.Shared.Next(0, 100),
|
||||
IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
|
||||
});
|
||||
messages.Add(new()
|
||||
{
|
||||
RootMessageId = default,
|
||||
MessageId = "96025b43-5235-44e9-a3fa-98df31edfbfb",
|
||||
User = Faker.GetRandomUser(),
|
||||
MessageType = (MessageType)Random.Shared.Next(0, 4),
|
||||
Title = default,
|
||||
Content = "test immagine",
|
||||
Medias = new()
|
||||
{
|
||||
new()
|
||||
{
|
||||
FileName = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
|
||||
Url = "https://ihatebeinga.live/media/51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
|
||||
AltText = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
|
||||
ContentType = "image/jpg"
|
||||
}
|
||||
},
|
||||
CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
|
||||
IsFavourite = Random.Shared.Next() % 2 == 0,
|
||||
BoostsCounter = Random.Shared.Next(0, 100),
|
||||
IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
|
||||
});
|
||||
messages.Add(new()
|
||||
{
|
||||
RootMessageId = default,
|
||||
MessageId = "277ca76b-aaad-4aa6-95fb-25f59e2fddf9",
|
||||
User = Faker.GetRandomUser(),
|
||||
MessageType = (MessageType)Random.Shared.Next(0, 4),
|
||||
Title = default,
|
||||
Content = "test audio",
|
||||
Medias = new()
|
||||
{
|
||||
new()
|
||||
{
|
||||
FileName = "09bfb06d0096975f.mp3",
|
||||
Url = "https://cdn.masto.host/mastodonuno/media_attachments/files/107/798/288/501/917/857/original/09bfb06d0096975f.mp3",
|
||||
AltText = "09bfb06d0096975f.mp3",
|
||||
ContentType = "audio/mp3"
|
||||
}
|
||||
},
|
||||
CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
|
||||
IsFavourite = Random.Shared.Next() % 2 == 0,
|
||||
BoostsCounter = Random.Shared.Next(0, 100),
|
||||
IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
|
||||
});
|
||||
messages.Add(new()
|
||||
{
|
||||
BoostingUser = Faker.GetRandomBoostingUser(),
|
||||
RootMessageId = default,
|
||||
MessageId = "de64e520-a7d3-4f31-b5a9-ba236f3b146c",
|
||||
User = Faker.GetRandomUser(),
|
||||
MessageType = (MessageType)Random.Shared.Next(0, 4),
|
||||
Title = default,
|
||||
Content = "test immagini",
|
||||
Medias = new()
|
||||
{
|
||||
new()
|
||||
{
|
||||
FileName = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
|
||||
Url = "https://ihatebeinga.live/media/51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
|
||||
AltText = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
|
||||
ContentType = "image/jpg"
|
||||
},
|
||||
new()
|
||||
{
|
||||
FileName = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
|
||||
Url = "https://ihatebeinga.live/media/51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
|
||||
AltText = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
|
||||
ContentType = "image/jpg"
|
||||
},
|
||||
new()
|
||||
{
|
||||
FileName = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
|
||||
Url = "https://ihatebeinga.live/media/51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
|
||||
AltText = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
|
||||
ContentType = "image/jpg"
|
||||
}
|
||||
},
|
||||
CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
|
||||
IsFavourite = Random.Shared.Next() % 2 == 0,
|
||||
BoostsCounter = Random.Shared.Next(0,100),
|
||||
IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
|
||||
});
|
||||
messages.Add(new()
|
||||
{
|
||||
RootMessageId = default,
|
||||
MessageId = "de64e520-a7d3-4f31-b5a9-ba236f3b146c",
|
||||
User = Faker.GetRandomUser(),
|
||||
MessageType = (MessageType)Random.Shared.Next(0, 4),
|
||||
Title = default,
|
||||
Content = "test immagini",
|
||||
Medias = new()
|
||||
{
|
||||
new()
|
||||
{
|
||||
FileName = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
|
||||
Url = "https://ihatebeinga.live/media/51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
|
||||
AltText = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
|
||||
ContentType = "image/jpg"
|
||||
},
|
||||
new()
|
||||
{
|
||||
FileName = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
|
||||
Url = "https://ihatebeinga.live/media/51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
|
||||
AltText = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
|
||||
ContentType = "image/jpg"
|
||||
},
|
||||
new()
|
||||
{
|
||||
FileName = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
|
||||
Url = "https://ihatebeinga.live/media/51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
|
||||
AltText = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
|
||||
ContentType = "image/jpg"
|
||||
}
|
||||
},
|
||||
CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
|
||||
IsFavourite = Random.Shared.Next() % 2 == 0,
|
||||
BoostsCounter = Random.Shared.Next(0,100),
|
||||
IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
|
||||
});
|
||||
logger.LogError(ex, $"{nameof(Storage)}.{nameof(GetMessage)}");
|
||||
return default;
|
||||
}
|
||||
|
||||
messages = messages.OrderByDescending(m => m.CreatedAt).ToList();
|
||||
|
||||
return messages;
|
||||
}
|
||||
|
||||
public async ValueTask<string> AddMessages(List<Message> messages)
|
||||
/// <summary>The stored messages, newest first; while none are stored, the mock feed (Faker.SeedMessages).</summary>
|
||||
public async Task<List<Message>> GetMessages(CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _db.OpenIndexedDb();
|
||||
var result = await _db.AddItems(nameof(Message), messages);
|
||||
_logger.LogInformation(result);
|
||||
return result;
|
||||
try
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
await db.OpenIndexedDb();
|
||||
var messages = await db.GetAll<Message>(nameof(Message)) ?? [];
|
||||
if (messages.Count == 0)
|
||||
messages = Faker.SeedMessages();
|
||||
|
||||
return [.. messages.OrderByDescending(m => m.CreatedAt)];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, $"{nameof(Storage)}.{nameof(GetMessages)}");
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask<string> UpdateMessages(List<Message> messages)
|
||||
{
|
||||
await _db.OpenIndexedDb();
|
||||
var result = await _db.UpdateItems(nameof(Message), messages);
|
||||
_logger.LogInformation(result);
|
||||
return result;
|
||||
public Task<WebResult> AddMessages(List<Message> messages, CancellationToken cancellationToken = default) =>
|
||||
Run(nameof(AddMessages), async () => await db.AddItems(nameof(Message), messages), cancellationToken);
|
||||
|
||||
}
|
||||
public Task<WebResult> UpdateMessages(List<Message> messages, CancellationToken cancellationToken = default) =>
|
||||
Run(nameof(UpdateMessages), async () => await db.UpdateItems(nameof(Message), messages), cancellationToken);
|
||||
|
||||
public async ValueTask<string> RemoveMessage(string messageId)
|
||||
{
|
||||
await _db.OpenIndexedDb();
|
||||
var result = await _db.DeleteByKey(nameof(Message), messageId);
|
||||
_logger.LogInformation(result);
|
||||
return result;
|
||||
}
|
||||
public Task<WebResult> RemoveMessage(string messageId, CancellationToken cancellationToken = default) =>
|
||||
Run(nameof(RemoveMessage), async () => await db.DeleteByKey(nameof(Message), messageId), cancellationToken);
|
||||
|
||||
#endregion
|
||||
|
||||
#region Logs
|
||||
|
||||
public async ValueTask<ICollection<ClientLogs>> GetClientLogs()
|
||||
public async Task<List<ClientLogs>> GetClientLogs(CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogInformation($"opening on {nameof(GetClientLogs)}");
|
||||
await _db.OpenIndexedDb();
|
||||
return (await _db.GetAll<ClientLogs>(nameof(ClientLogs))).OrderByDescending(cl => cl.TimeStamp).ToArray();
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
await db.OpenIndexedDb();
|
||||
var logs = await db.GetAll<ClientLogs>(nameof(ClientLogs)) ?? [];
|
||||
return [.. logs.OrderByDescending(log => log.TimeStamp)];
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, ex.Message);
|
||||
return new List<ClientLogs>();
|
||||
logger.LogError(ex, $"{nameof(Storage)}.{nameof(GetClientLogs)}");
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask AddLog(Exception exception, string where)
|
||||
public Task AddLog(Exception exception, string where, CancellationToken cancellationToken = default) =>
|
||||
AddLog(new ClientLogs
|
||||
{
|
||||
Where = where,
|
||||
Exception = new()
|
||||
{
|
||||
Type = exception.GetType().ToString(),
|
||||
HelpLink = exception.HelpLink,
|
||||
HResult = exception.HResult.ToString(),
|
||||
InnerExceptionMessage = exception.InnerException?.Message,
|
||||
Message = exception.Message,
|
||||
Source = exception.Source,
|
||||
StackTrace = exception.StackTrace,
|
||||
TargetSiteName = exception.TargetSite?.Name
|
||||
}
|
||||
}, cancellationToken);
|
||||
|
||||
public Task AddLog(string message, string where, CancellationToken cancellationToken = default) =>
|
||||
AddLog(new ClientLogs { Where = where, WarningMessage = message }, cancellationToken);
|
||||
|
||||
/// <summary>Numbers the entry after the newest one and trims the log; never throws.</summary>
|
||||
async Task AddLog(ClientLogs log, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _db.OpenIndexedDb();
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
await db.OpenIndexedDb();
|
||||
|
||||
var maxKey = await _db.GetMaxKey<long>(nameof(ClientLogs));
|
||||
var minKey = await _db.GetMinKey<long>(nameof(ClientLogs));
|
||||
var maxKey = await db.GetMaxKey<long>(nameof(ClientLogs));
|
||||
var minKey = await db.GetMinKey<long>(nameof(ClientLogs));
|
||||
if (maxKey - minKey >= MaxLogs)
|
||||
for (var key = minKey; key < minKey + MaxLogs / 2; key++)
|
||||
_ = await db.DeleteByKey(nameof(ClientLogs), key);
|
||||
|
||||
if (minKey - maxKey <= -100)
|
||||
for (var i = minKey; i < minKey + 50; i++)
|
||||
_ = await _db.DeleteByKey(nameof(ClientLogs), i);
|
||||
|
||||
maxKey += 1;
|
||||
var result = await _db.AddItems<ClientLogs>(nameof(ClientLogs), new()
|
||||
{
|
||||
new()
|
||||
{
|
||||
Id = maxKey,
|
||||
Where = where,
|
||||
Exception = new()
|
||||
{
|
||||
Type = exception.GetType().ToString(),
|
||||
HelpLink = exception.HelpLink,
|
||||
HResult = exception.HResult.ToString(),
|
||||
InnerExceptionMessage = exception.InnerException?.Message,
|
||||
Message = exception.Message,
|
||||
Source = exception.Source,
|
||||
StackTrace = exception.StackTrace,
|
||||
TargetSiteName = exception.TargetSite?.Name
|
||||
}
|
||||
}
|
||||
});
|
||||
_logger.LogDebug($"{nameof(AddLog)}() add logs result = {result}");
|
||||
log.Id = maxKey + 1;
|
||||
var result = await db.AddItems<ClientLogs>(nameof(ClientLogs), [log]);
|
||||
logger.LogDebug($"{nameof(AddLog)}() add logs result = {result}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async ValueTask AddLog(string message, string where)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _db.OpenIndexedDb();
|
||||
|
||||
var maxKey = await _db.GetMaxKey<long>(nameof(ClientLogs));
|
||||
var minKey = await _db.GetMinKey<long>(nameof(ClientLogs));
|
||||
|
||||
if (minKey - maxKey <= -100)
|
||||
for (var i = minKey; i < minKey + 50; i++)
|
||||
_ = await _db.DeleteByKey(nameof(ClientLogs), i);
|
||||
|
||||
maxKey += 1;
|
||||
var result = await _db.AddItems<ClientLogs>(nameof(ClientLogs), new()
|
||||
{
|
||||
new()
|
||||
{
|
||||
Id = maxKey,
|
||||
Where = where,
|
||||
Exception = null,
|
||||
WarningMessage = message
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, ex.Message);
|
||||
logger.LogError(ex, $"{nameof(Storage)}.{nameof(AddLog)}");
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
public async ValueTask<bool> RemoveAll(bool includeClientLogs = false)
|
||||
public Task<WebResult> RemoveAll(bool includeClientLogs = false, CancellationToken cancellationToken = default) =>
|
||||
Run(nameof(RemoveAll), async () =>
|
||||
{
|
||||
var result = await db.DeleteAll(nameof(Message));
|
||||
if (includeClientLogs)
|
||||
result = await db.DeleteAll(nameof(ClientLogs));
|
||||
return result;
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>Runs a write and turns its outcome into a WebResult.</summary>
|
||||
async Task<WebResult> Run(string caller, Func<Task<string>> write, CancellationToken cancellationToken)
|
||||
{
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
_logger.LogInformation($"opening on {nameof(RemoveAll)}");
|
||||
await _db.OpenIndexedDb();
|
||||
_ = await _db.DeleteAll(nameof(Message));
|
||||
if (includeClientLogs)
|
||||
_ = await _db.DeleteAll(nameof(ClientLogs));
|
||||
|
||||
return true;
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
await db.OpenIndexedDb();
|
||||
logger.LogInformation("{Caller}: {Result}", caller, await write());
|
||||
return result;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return SUtility.DefaultTaskCancelledResult;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, ex.Message);
|
||||
return default;
|
||||
logger.LogError(ex, $"{nameof(Storage)}.{caller}");
|
||||
return result.Invalidate(ex.Message, exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,10 @@
|
||||
using DnetIndexedDb;
|
||||
using DnetIndexedDb;
|
||||
|
||||
using Microsoft.JSInterop;
|
||||
|
||||
namespace decePubClient.Services
|
||||
{
|
||||
public class IndexedDb : IndexedDbInterop
|
||||
public class IndexedDb(IJSRuntime jsRuntime, IndexedDbOptions<IndexedDb> options) : IndexedDbInterop(jsRuntime, options)
|
||||
{
|
||||
public IndexedDb(IJSRuntime jsRuntime, IndexedDbOptions<IndexedDb> options)
|
||||
: base(jsRuntime, options)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
+79
-65
@@ -1,74 +1,88 @@
|
||||
using decePubClient.Models;
|
||||
using collAnon.Client.Services;
|
||||
|
||||
using decePubClient.Extensions;
|
||||
using decePubClient.Models;
|
||||
using decePubClient.Models.Types;
|
||||
|
||||
using PrivaPub.ClientModels;
|
||||
|
||||
namespace decePubClient.Services
|
||||
{
|
||||
public class MessagesService
|
||||
/// <summary>
|
||||
/// Message actions. Still a mock: the app isn't wired to PrivaPub yet, so each method builds its result in memory.
|
||||
/// The signatures are the real ones (a Task<WebResult> whose Data is the updated entity), so wiring means
|
||||
/// calling httpService against PrivaPub's /clientapi/post/* routes inside the same try/catch, reading failures with
|
||||
/// ReadWebResult and the body with DefaultReadFromJsonAsync, as b2b.next's StoreService does.
|
||||
/// </summary>
|
||||
public class MessagesService(ILoggingService logger, CoalescingStringLocalizer localizer)
|
||||
{
|
||||
readonly IStorage storage;
|
||||
readonly HttpClient http;
|
||||
/// <summary>Posts a message or, with RootMessageId set, a reply; Data is the new Message.</summary>
|
||||
public Task<WebResult> SubmitMessage(MessageForm messageForm, User author, CancellationToken cancellationToken = default) =>
|
||||
Run(nameof(SubmitMessage), () => (object)new Message
|
||||
{
|
||||
RootMessageId = messageForm.RootMessageId,
|
||||
MessageId = Guid.NewGuid().ToString(),
|
||||
Content = messageForm.Content?.ParseContent(messageForm.ContentType),
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
MessageType = messageForm.MessageType,
|
||||
Medias = [.. messageForm.Media.Select(m => new Media
|
||||
{
|
||||
FileName = m.FileName,
|
||||
AltText = m.AltText,
|
||||
ContentType = m.ContentType,
|
||||
Url = m.Base64Preview,
|
||||
Blob = m.Blob
|
||||
})],
|
||||
Title = messageForm.Title,
|
||||
User = author.ToMessageUser()
|
||||
}, cancellationToken);
|
||||
|
||||
public MessagesService(IHttpClientFactory clientFactory, IStorage storage)
|
||||
/// <summary>Opens a reply of the given scope to a message; Data is the message.</summary>
|
||||
public Task<WebResult> ReplyMessage(Message messageToReply, MessageType messageType = MessageType.Public, CancellationToken cancellationToken = default) =>
|
||||
Run(nameof(ReplyMessage), () => messageToReply, cancellationToken);
|
||||
|
||||
/// <summary>Boosts the message, or takes the boost back; Data is the message with its counter updated.</summary>
|
||||
public Task<WebResult> BoostUnboostMessage(Message message, CancellationToken cancellationToken = default) =>
|
||||
Run(nameof(BoostUnboostMessage), () =>
|
||||
{
|
||||
message.BoostsCounter += message.IsBoostedByCurrentUser ? -1 : 1;
|
||||
message.IsBoostedByCurrentUser = !message.IsBoostedByCurrentUser;
|
||||
return message;
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>Adds the message to the favourites, or removes it; Data is the updated message.</summary>
|
||||
public Task<WebResult> FavouriteUnfavouriteMessage(Message message, CancellationToken cancellationToken = default) =>
|
||||
Run(nameof(FavouriteUnfavouriteMessage), () =>
|
||||
{
|
||||
message.IsFavourite = !message.IsFavourite;
|
||||
return message;
|
||||
}, cancellationToken);
|
||||
|
||||
public Task<WebResult> DeleteMessage(Message message, CancellationToken cancellationToken = default) =>
|
||||
Run(nameof(DeleteMessage), () => message, cancellationToken);
|
||||
|
||||
public Task<WebResult> BlockUserFromMessage(MessageUser messageUser, CancellationToken cancellationToken = default) =>
|
||||
Run(nameof(BlockUserFromMessage), () => messageUser, cancellationToken);
|
||||
|
||||
public Task<WebResult> SilenceUserFromMessage(MessageUser messageUser, CancellationToken cancellationToken = default) =>
|
||||
Run(nameof(SilenceUserFromMessage), () => messageUser, cancellationToken);
|
||||
|
||||
/// <summary>The mock's stand-in for an API call: the same success/failure handling, with the outcome built locally.</summary>
|
||||
async Task<WebResult> Run(string caller, Func<object> action, CancellationToken cancellationToken)
|
||||
{
|
||||
this.storage = storage;
|
||||
http = clientFactory.CreateClient("default");
|
||||
}
|
||||
|
||||
//Covers also direct message
|
||||
public async Task<Message> SubmitMessage(MessageForm messageForm)
|
||||
{
|
||||
//TODO
|
||||
|
||||
await Task.Run(() => {});
|
||||
return new();
|
||||
}
|
||||
|
||||
//Covers also direct message
|
||||
public async Task<Message> ReplyMessage(Message messageToReply, MessageType messageType = MessageType.Public)
|
||||
{
|
||||
//TODO
|
||||
|
||||
await Task.Run(() => {});
|
||||
return messageToReply;
|
||||
}
|
||||
|
||||
public async Task<Message> BoostUnboostMessage(Message messageToReply)
|
||||
{
|
||||
//TODO
|
||||
|
||||
await Task.Run(() => {});
|
||||
return messageToReply;
|
||||
}
|
||||
|
||||
public async Task<Message> FavouriteUnfavouriteMessage(Message messageToReply)
|
||||
{
|
||||
//TODO
|
||||
|
||||
await Task.Run(() => {});
|
||||
return messageToReply;
|
||||
}
|
||||
|
||||
public async Task<Message> DeleteMessage(Message messageToReply)
|
||||
{
|
||||
//TODO
|
||||
|
||||
await Task.Run(() => {});
|
||||
return messageToReply;
|
||||
}
|
||||
|
||||
public async Task<MessageUser> BlockUserFromMessage(MessageUser messageUser)
|
||||
{
|
||||
//TODO
|
||||
await Task.Run(() => {});
|
||||
return messageUser;
|
||||
}
|
||||
|
||||
public async Task<MessageUser> SilenceUserFromMessage(MessageUser messageUser)
|
||||
{
|
||||
//TODO
|
||||
|
||||
await Task.Run(() => {});
|
||||
return messageUser;
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
await Task.Yield();
|
||||
result.Data = action();
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await logger.ProcessError(ex, $"{nameof(MessagesService)}.{caller}", cancellationToken);
|
||||
return result.Invalidate(localizer["The action could not be completed."], exception: ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
namespace decePubClient.Services;
|
||||
|
||||
public enum ToastSeverity
|
||||
{
|
||||
Info,
|
||||
Success,
|
||||
Warning,
|
||||
Error
|
||||
}
|
||||
|
||||
public sealed record ToastMessage(Guid Id, ToastSeverity Severity, string Text);
|
||||
|
||||
/// <summary>
|
||||
/// The app's snackbar: components add messages (usually through the SUtility extensions AddResponseError,
|
||||
/// AddResponseSuccess, AddWarning, AddException) and Components/ToastHost.razor, placed once in MainLayout, shows them.
|
||||
/// A message already on screen isn't added twice, and at most MaxMessages stay, oldest dropped first.
|
||||
/// </summary>
|
||||
public class ToastService
|
||||
{
|
||||
const int MaxMessages = 12;
|
||||
|
||||
readonly List<ToastMessage> messages = [];
|
||||
|
||||
public event Action Changed;
|
||||
|
||||
public IReadOnlyList<ToastMessage> Messages => messages;
|
||||
|
||||
/// <summary>Shows a message; with closeAfter it closes itself, otherwise it stays until the user closes it.</summary>
|
||||
public void Add(ToastSeverity severity, string text, TimeSpan? closeAfter = null)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text) || messages.Any(m => m.Severity == severity && m.Text == text))
|
||||
return;
|
||||
|
||||
var message = new ToastMessage(Guid.NewGuid(), severity, text);
|
||||
messages.Add(message);
|
||||
if (messages.Count > MaxMessages)
|
||||
messages.RemoveAt(0);
|
||||
Changed?.Invoke();
|
||||
|
||||
if (closeAfter is { } delay)
|
||||
_ = CloseLater(message.Id, delay);
|
||||
}
|
||||
|
||||
public void Close(Guid id)
|
||||
{
|
||||
if (messages.RemoveAll(m => m.Id == id) > 0)
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
async Task CloseLater(Guid id, TimeSpan delay, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await Task.Delay(delay, cancellationToken);
|
||||
Close(id);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using Blazored.LocalStorage;
|
||||
using decePubClient.Helpers;
|
||||
using decePubClient.Models;
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
using System.Security.Claims;
|
||||
@@ -6,22 +7,9 @@ using System.Text.Json;
|
||||
|
||||
namespace decePubClient.Services
|
||||
{
|
||||
public class TokenAuthStateProvider : AuthenticationStateProvider
|
||||
public class TokenAuthStateProvider(ILocalStorageService storage, IStorage dbStorage, ILogger<TokenAuthStateProvider> logger)
|
||||
: AuthenticationStateProvider
|
||||
{
|
||||
readonly ILocalStorageService Storage;
|
||||
readonly IStorage DbStorage;
|
||||
readonly ILogger<TokenAuthStateProvider> Logger;
|
||||
AuthData AuthData { get; set; }
|
||||
|
||||
public TokenAuthStateProvider(ILocalStorageService storage,
|
||||
IStorage dbStorage,
|
||||
ILogger<TokenAuthStateProvider> logger)
|
||||
{
|
||||
Storage = storage;
|
||||
DbStorage = dbStorage;
|
||||
Logger = logger;
|
||||
}
|
||||
|
||||
public void SetToken(/*string token, long expirationTicks = default*/)
|
||||
{
|
||||
//AuthData = await Storage.GetItemAsync<AuthData>(nameof(AuthData));
|
||||
@@ -41,41 +29,40 @@ namespace decePubClient.Services
|
||||
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
|
||||
}
|
||||
|
||||
public async ValueTask<bool> IsAuthenticatedAsync()
|
||||
/// <summary>The stored token while it is still valid, otherwise null.</summary>
|
||||
public async Task<string> GetToken(CancellationToken cancellationToken = default)
|
||||
{
|
||||
AuthData = await Storage.GetItemAsync<AuthData>(nameof(AuthData));
|
||||
if (AuthData is null)
|
||||
{
|
||||
AuthData = new();
|
||||
await Storage.SetItemAsync(nameof(AuthData), AuthData);
|
||||
}
|
||||
return AuthData.Token != null &&
|
||||
AuthData.TokenExpiration.HasValue &&
|
||||
AuthData.TokenExpiration.Value > DateTime.UtcNow.Ticks;
|
||||
var authData = await storage.GetItemAsync<AuthData>(nameof(AuthData), cancellationToken);
|
||||
if (string.IsNullOrEmpty(authData?.Token) || authData.TokenExpiration is not { } expiration || expiration <= DateTime.UtcNow.Ticks)
|
||||
return null;
|
||||
return authData.Token;
|
||||
}
|
||||
|
||||
public async Task LogoutAsync(bool deleteDb = false)
|
||||
public async Task<bool> IsAuthenticatedAsync(CancellationToken cancellationToken = default) =>
|
||||
await GetToken(cancellationToken) is not null;
|
||||
|
||||
public async Task LogoutAsync(bool deleteDb = false, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Logger.LogInformation($"set null({nameof(LogoutAsync)})");
|
||||
logger.LogInformation($"set null({nameof(LogoutAsync)})");
|
||||
//await Storage.RemoveItemAsync(nameof(PrivateCacheData));
|
||||
await Storage.RemoveItemAsync(nameof(AuthData));
|
||||
await storage.RemoveItemAsync(nameof(AuthData), cancellationToken);
|
||||
if (deleteDb)
|
||||
await DbStorage.RemoveAll(includeClientLogs: true);
|
||||
await dbStorage.RemoveAll(includeClientLogs: true, cancellationToken: cancellationToken);
|
||||
|
||||
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
|
||||
}
|
||||
|
||||
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
|
||||
{
|
||||
AuthData = await Storage.GetItemAsync<AuthData>(nameof(AuthData));
|
||||
if (string.IsNullOrEmpty(AuthData?.Token))
|
||||
var authData = await storage.GetItemAsync<AuthData>(nameof(AuthData));
|
||||
if (string.IsNullOrEmpty(authData?.Token))
|
||||
{
|
||||
Logger.LogInformation($"set null({nameof(GetAuthenticationStateAsync)})");
|
||||
logger.LogInformation($"set null({nameof(GetAuthenticationStateAsync)})");
|
||||
return new(new());
|
||||
}
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new(ClaimTypes.UserData, JsonSerializer.Serialize(AuthData.User))
|
||||
new(ClaimTypes.UserData, JsonSerializer.Serialize(authData.User, SUtility.DefaultSerializer))
|
||||
};
|
||||
|
||||
//claims.Add(new(Policies.IsUser, (AuthData.User.Policies.Contains(Policies.IsUser)).ToString().ToLower()));
|
||||
|
||||
Reference in new issue
Block a user