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;
|
2026-10-04 11:03:14 +02:00
|
|
|
using decePubClient.Models.Mastodon;
|
2022-12-15 20:03:40 +01:00
|
|
|
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;
|
2026-10-04 11:03:14 +02:00
|
|
|
using System.Text.RegularExpressions;
|
2022-12-15 20:03:40 +01:00
|
|
|
using System.Web;
|
|
|
|
|
|
|
|
|
|
namespace decePubClient.Extensions
|
|
|
|
|
{
|
2026-10-04 11:03:14 +02:00
|
|
|
public static partial class ExtensionMethods
|
2022-12-15 20:03:40 +01:00
|
|
|
{
|
|
|
|
|
#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);
|
|
|
|
|
|
2026-10-04 11:03:14 +02:00
|
|
|
if (TryReadMastodonError(json) is { } mastodonError)
|
|
|
|
|
return result.Invalidate(mastodonError, (int)statusCode);
|
|
|
|
|
|
2026-10-03 15:26:21 +02:00
|
|
|
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);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-04 11:03:14 +02:00
|
|
|
/// <summary>The message of a Mastodon API or /oauth error ({"error": ..., "error_description": ...}), or null.</summary>
|
|
|
|
|
static string TryReadMastodonError(string json)
|
|
|
|
|
{
|
|
|
|
|
if (!json.Contains("\"error\"") || json.Contains("\"errorMessage\""))
|
|
|
|
|
return null;
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
var error = JsonSerializer.Deserialize<MastodonError>(json, SUtility.MastodonSerializer);
|
|
|
|
|
return error?.ErrorDescription ?? error?.Error;
|
|
|
|
|
}
|
|
|
|
|
catch (JsonException)
|
|
|
|
|
{
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Reads a successful Mastodon API body (snake_case); a cancelled read, or a body that does not fit T (written to the
|
|
|
|
|
/// browser console), returns SUtility.CancellationDefault.
|
|
|
|
|
/// </summary>
|
|
|
|
|
public static async Task<T> MastodonReadFromJsonAsync<T>(this HttpResponseMessage response, CancellationToken cancellationToken = default)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
return await response.Content.ReadFromJsonAsync<T>(SUtility.MastodonSerializer, cancellationToken);
|
|
|
|
|
}
|
|
|
|
|
catch (OperationCanceledException)
|
|
|
|
|
{
|
|
|
|
|
return SUtility.CancellationDefault<T>();
|
|
|
|
|
}
|
|
|
|
|
catch (JsonException ex)
|
|
|
|
|
{
|
|
|
|
|
Console.Error.WriteLine($"{nameof(MastodonReadFromJsonAsync)}<{typeof(T).Name}> {response.RequestMessage?.RequestUri}: {ex.Message}");
|
|
|
|
|
return SUtility.CancellationDefault<T>();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// The paging cursors of a Mastodon list: max_id from the Link header's next (older items), min_id from its prev
|
|
|
|
|
/// (newer items). Either is null when the header does not name it.
|
|
|
|
|
/// </summary>
|
|
|
|
|
public static (string MaxId, string MinId) PageCursors(this HttpResponseMessage response)
|
|
|
|
|
{
|
|
|
|
|
if (!response.Headers.TryGetValues("Link", out var values))
|
|
|
|
|
return (null, null);
|
|
|
|
|
string maxId = null, minId = null;
|
|
|
|
|
foreach (Match link in LinkHeader().Matches(string.Join(',', values)))
|
|
|
|
|
{
|
|
|
|
|
var query = HttpUtility.ParseQueryString(new Uri(link.Groups[1].Value, UriKind.Absolute).Query);
|
|
|
|
|
if (link.Groups[2].Value == "next")
|
|
|
|
|
maxId = query["max_id"];
|
|
|
|
|
else if (link.Groups[2].Value == "prev")
|
|
|
|
|
minId = query["min_id"] ?? query["since_id"];
|
|
|
|
|
}
|
|
|
|
|
return (maxId, minId);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
[GeneratedRegex("<([^>]+)>\\s*;\\s*rel=\"([a-z]+)\"")]
|
|
|
|
|
private static partial Regex LinkHeader();
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Reads a successful /clientapi body; a cancelled read, or a body that does not fit T (written to the browser
|
|
|
|
|
/// console), returns SUtility.CancellationDefault.
|
|
|
|
|
/// </summary>
|
2026-10-03 15:26:21 +02:00
|
|
|
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>();
|
|
|
|
|
}
|
2026-10-04 11:03:14 +02:00
|
|
|
catch (JsonException ex)
|
|
|
|
|
{
|
|
|
|
|
Console.Error.WriteLine($"{nameof(DefaultReadFromJsonAsync)}<{typeof(T).Name}> {response.RequestMessage?.RequestUri}: {ex.Message}");
|
|
|
|
|
return SUtility.CancellationDefault<T>();
|
|
|
|
|
}
|
2026-10-03 15:26:21 +02:00
|
|
|
}
|
|
|
|
|
|
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
|
|
|
|
|
}
|
|
|
|
|
}
|