2026-10-03 12:08:11 +02:00
|
|
|
using Blazored.LocalStorage;
|
2022-12-15 20:03:40 +01:00
|
|
|
|
|
|
|
|
using collAnon.Client.Services;
|
|
|
|
|
|
2026-10-03 15:26:21 +02:00
|
|
|
using decePubClient.Helpers;
|
2022-12-15 20:03:40 +01:00
|
|
|
using decePubClient.Models;
|
|
|
|
|
using decePubClient.Services;
|
|
|
|
|
|
|
|
|
|
using Markdig;
|
|
|
|
|
|
|
|
|
|
using Microsoft.AspNetCore.Authorization;
|
|
|
|
|
using Microsoft.AspNetCore.Components;
|
|
|
|
|
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
|
|
|
|
|
|
2026-10-01 08:09:45 +02:00
|
|
|
using PrivaPub.ClientModels;
|
2022-12-15 20:03:40 +01:00
|
|
|
|
|
|
|
|
using System.Collections.Specialized;
|
|
|
|
|
using System.ComponentModel;
|
|
|
|
|
using System.Globalization;
|
2026-10-03 15:26:21 +02:00
|
|
|
using System.Net;
|
|
|
|
|
using System.Net.Http.Json;
|
2022-12-15 20:03:40 +01:00
|
|
|
using System.Text.Json;
|
|
|
|
|
using System.Web;
|
|
|
|
|
|
|
|
|
|
namespace decePubClient.Extensions
|
|
|
|
|
{
|
|
|
|
|
public static class ExtensionMethods
|
|
|
|
|
{
|
|
|
|
|
#region Navigation Manager
|
|
|
|
|
|
|
|
|
|
public static NameValueCollection QueryString(this NavigationManager navigationManager) =>
|
|
|
|
|
HttpUtility.ParseQueryString(new Uri(navigationManager.Uri).Query);
|
|
|
|
|
|
|
|
|
|
public static string QueryString(this NavigationManager navigationManager, string key) =>
|
|
|
|
|
navigationManager.QueryString()[key];
|
|
|
|
|
|
|
|
|
|
public static T QueryString<T>(this NavigationManager navigationManager, string key)
|
|
|
|
|
{
|
|
|
|
|
var value = navigationManager.QueryString()[key];
|
2026-10-03 15:26:21 +02:00
|
|
|
if (!TypeDescriptor.GetConverter(typeof(T)).IsValid(value))
|
2022-12-15 20:03:40 +01:00
|
|
|
return default;
|
2026-10-03 15:26:21 +02:00
|
|
|
return (T)Convert.ChangeType(value, typeof(T));
|
2022-12-15 20:03:40 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#endregion Navigation Manager
|
|
|
|
|
|
|
|
|
|
#region Setups
|
|
|
|
|
|
2026-10-03 15:26:21 +02:00
|
|
|
/// <summary>The languages with resources (Resources/AllStrings.*.resx); any other browser language gets English.</summary>
|
|
|
|
|
public static readonly string[] SupportedLanguages = ["en", "it"];
|
|
|
|
|
|
|
|
|
|
public static async Task SetDefaultCulture(this WebAssemblyHost host, CancellationToken cancellationToken = default)
|
2022-12-15 20:03:40 +01:00
|
|
|
{
|
2026-10-03 15:26:21 +02:00
|
|
|
var culture = ToCulture(default);
|
2022-12-15 20:03:40 +01:00
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
var storage = host.Services.GetRequiredService<ILocalStorageService>();
|
2026-10-03 15:26:21 +02:00
|
|
|
var publicCache = await storage.GetItemAsync<PublicCacheData>(nameof(PublicCacheData), cancellationToken);
|
2022-12-15 20:03:40 +01:00
|
|
|
if (publicCache is null)
|
|
|
|
|
{
|
2026-10-03 15:26:21 +02:00
|
|
|
var browserLanguage = host.Services.GetRequiredService<AppStatusService>().Language();
|
2022-12-15 20:03:40 +01:00
|
|
|
publicCache = new();
|
2026-10-03 15:26:21 +02:00
|
|
|
publicCache.PageSettings.CurrentLanguageCode =
|
|
|
|
|
SupportedLanguages.FirstOrDefault(language => browserLanguage?.StartsWith(language) ?? false) ?? "en";
|
|
|
|
|
await storage.SetItemAsync(nameof(PublicCacheData), publicCache, cancellationToken);
|
2022-12-15 20:03:40 +01:00
|
|
|
}
|
|
|
|
|
|
2026-10-03 15:26:21 +02:00
|
|
|
culture = ToCulture(publicCache.PageSettings.CurrentLanguageCode);
|
2022-12-15 20:03:40 +01:00
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
Console.WriteLine(ex);
|
|
|
|
|
}
|
2026-10-03 15:26:21 +02:00
|
|
|
|
|
|
|
|
CultureInfo.DefaultThreadCurrentCulture = culture;
|
|
|
|
|
CultureInfo.DefaultThreadCurrentUICulture = culture;
|
2022-12-15 20:03:40 +01:00
|
|
|
}
|
|
|
|
|
|
2026-10-03 15:26:21 +02:00
|
|
|
static CultureInfo ToCulture(string languageCode) => languageCode is "it" ? new("it-IT") : new("en-GB");
|
|
|
|
|
|
2022-12-15 20:03:40 +01:00
|
|
|
#endregion Setups
|
|
|
|
|
|
|
|
|
|
public static string GetLogLevelClass(this string logType) => logType switch
|
|
|
|
|
{
|
2026-10-03 12:08:11 +02:00
|
|
|
"Debug" => "text-base-content/60",
|
|
|
|
|
"Information" => "text-info",
|
|
|
|
|
"Warning" => "text-warning",
|
|
|
|
|
"Error" => "text-error",
|
|
|
|
|
"Fatal" => "text-error font-bold",
|
2022-12-15 20:03:40 +01:00
|
|
|
_ => string.Empty
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
#region Formats
|
|
|
|
|
|
|
|
|
|
public static MarkdownPipeline Pipeline =>
|
|
|
|
|
new MarkdownPipelineBuilder().UseGenericAttributes().Build();
|
|
|
|
|
|
|
|
|
|
public static string ToJson(this object value) =>
|
|
|
|
|
JsonSerializer.Serialize(value);
|
|
|
|
|
|
|
|
|
|
public static string ToBase64PngImage(this string base64Image) =>
|
|
|
|
|
$"data:image/png;base64,{base64Image}";
|
|
|
|
|
|
|
|
|
|
#endregion Formats
|
|
|
|
|
|
|
|
|
|
#region Models
|
|
|
|
|
|
|
|
|
|
public static string ToString(this WebResult webResult, CoalescingStringLocalizer localizer) =>
|
|
|
|
|
localizer["{0} - {1}", webResult.StatusCode, webResult.ErrorMessage];
|
|
|
|
|
|
2026-10-03 15:26:21 +02:00
|
|
|
/// <summary>
|
|
|
|
|
/// Reads a failed response as a WebResult: a failure HttpService made up (FailureHeader) as is, 401/403 and 5xx
|
|
|
|
|
/// as a generic message, validation ProblemDetails as their errors, anything else as the server's WebResult.
|
|
|
|
|
/// A cancelled request (410) becomes SUtility.DefaultTaskCancelledResult.
|
|
|
|
|
/// </summary>
|
|
|
|
|
public static async Task<WebResult> ReadWebResult(this HttpContent content, HttpStatusCode statusCode,
|
|
|
|
|
CoalescingStringLocalizer localizer, CancellationToken cancellationToken = default)
|
|
|
|
|
{
|
|
|
|
|
if (statusCode is HttpStatusCode.Gone)
|
|
|
|
|
return SUtility.DefaultTaskCancelledResult;
|
|
|
|
|
|
|
|
|
|
var result = new WebResult();
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
var json = await content.ReadAsStringAsync(cancellationToken);
|
|
|
|
|
if (content.Headers.Contains(SUtility.FailureHeader))
|
|
|
|
|
return JsonSerializer.Deserialize<WebResult>(json, SUtility.DefaultSerializer);
|
|
|
|
|
|
|
|
|
|
if (statusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
|
|
|
|
|
return result.Invalidate(localizer["You are not authorized to do this."], (int)statusCode, FailureCodes.Unauthorized);
|
|
|
|
|
|
|
|
|
|
if ((int)statusCode > 499)
|
|
|
|
|
return result.Invalidate(localizer["The server reported an internal error (HTTP {0}).", (int)statusCode], (int)statusCode,
|
|
|
|
|
FailureCodes.ServerError);
|
|
|
|
|
|
|
|
|
|
if (json.Contains("\"title\""))
|
|
|
|
|
{
|
|
|
|
|
var validationErrors = JsonSerializer.Deserialize<ValidationErrors>(json, SUtility.DefaultSerializer);
|
|
|
|
|
var lines = validationErrors.Errors.Select(error => $"{error.Key}: {string.Join(", ", error.Value)}").Prepend(validationErrors.Title);
|
|
|
|
|
return result.Invalidate(string.Join('\n', lines), validationErrors.Status);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return JsonSerializer.Deserialize<WebResult>(json, SUtility.DefaultSerializer) ??
|
|
|
|
|
result.Invalidate(localizer["The server sent an invalid response."], (int)statusCode);
|
|
|
|
|
}
|
|
|
|
|
catch (OperationCanceledException)
|
|
|
|
|
{
|
|
|
|
|
return SUtility.DefaultTaskCancelledResult;
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
return result.Invalidate(localizer["The server sent an invalid response."], (int)HttpStatusCode.BadRequest, exception: ex);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>Reads a successful response body; a cancelled read returns SUtility.CancellationDefault.</summary>
|
|
|
|
|
public static async Task<T> DefaultReadFromJsonAsync<T>(this HttpResponseMessage response, CancellationToken cancellationToken = default)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
return await response.Content.ReadFromJsonAsync<T>(SUtility.DefaultSerializer, cancellationToken);
|
|
|
|
|
}
|
|
|
|
|
catch (OperationCanceledException)
|
|
|
|
|
{
|
|
|
|
|
return SUtility.CancellationDefault<T>();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2022-12-15 20:03:40 +01:00
|
|
|
public static string Timeframe(this DateTime creationDate, CoalescingStringLocalizer localizer)
|
|
|
|
|
{
|
|
|
|
|
var timeframe = DateTime.Now - creationDate.ToLocalTime();
|
|
|
|
|
switch ((int)timeframe.TotalHours)
|
|
|
|
|
{
|
|
|
|
|
case >= 24:
|
|
|
|
|
return localizer["{0} day/s", (int)timeframe.TotalDays];
|
|
|
|
|
|
|
|
|
|
case >= 1 and < 24:
|
|
|
|
|
return localizer["{0} hour/s", (int)timeframe.TotalHours];
|
|
|
|
|
|
|
|
|
|
case 0:
|
|
|
|
|
return localizer["{0} minute/s", (int)timeframe.TotalMinutes];
|
|
|
|
|
|
|
|
|
|
default:
|
|
|
|
|
return string.Empty;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static AuthorizationPolicy IsAdminPolicy() =>
|
|
|
|
|
new AuthorizationPolicyBuilder().RequireAuthenticatedUser()
|
2026-10-03 15:26:21 +02:00
|
|
|
.RequireClaim(Policies.IsAdmin, "true")
|
|
|
|
|
.RequireClaim(Policies.IsUser, "true")
|
|
|
|
|
.RequireClaim(Policies.IsModerator, "true")
|
2022-12-15 20:03:40 +01:00
|
|
|
.Build();
|
|
|
|
|
|
|
|
|
|
public static AuthorizationPolicy IsUserPolicy() =>
|
|
|
|
|
new AuthorizationPolicyBuilder().RequireAuthenticatedUser()
|
2026-10-03 15:26:21 +02:00
|
|
|
.RequireClaim(Policies.IsUser, "true")
|
2022-12-15 20:03:40 +01:00
|
|
|
.Build();
|
|
|
|
|
|
|
|
|
|
public static AuthorizationPolicy IsUserModeratorPolicy() =>
|
|
|
|
|
new AuthorizationPolicyBuilder().RequireAuthenticatedUser()
|
2026-10-03 15:26:21 +02:00
|
|
|
.RequireClaim(Policies.IsModerator, "true")
|
2022-12-15 20:03:40 +01:00
|
|
|
.Build();
|
|
|
|
|
|
|
|
|
|
#endregion
|
|
|
|
|
}
|
|
|
|
|
}
|