Build / Build (push) Successful in 51s
Starts the completion program (SocialPub docs/ROADMAP.md, "Owner decisions on finishing everything", 2026-10-17). - The localizer's namespace is decePubClient.Services; collAnon is gone from the repo. - Dead code: PagesBase, VConstants, SettingsOptions, ViewLanguage, unused APIs routes, InstanceService.Self, RequestStats.LastOf/AverageMs, PostAnon/DeleteTotallyAnon, unused AppStatusService methods and their main.js helpers (the app badge stays for Web Push), ExtensionMethods/SUtility leftovers (Markdig and BlazorZXingJs packages go), unused PublicCacheData/PageSettings/AppConfiguration fields, commented-out code. - The client log in IndexedDB, which nothing ever read, goes with the whole IndexedDB layer (DnetIndexedDb, IStorage): logs go to the browser console; main.js deletes the old "data" database once. - The solution names the real ClientModels project. Unused vendor assets (fontawesome, solid, open-iconic, rxjs) go. - robots.txt disallows everything; manifest.json and index.html say decePub; the service worker's cache name follows each publish's assets version, so old caches are purged. - MessageType is Visibility (member names kept: they are resx keys); ExpandMessage.razor is Thread.razor (same route). - i18n: dead keys removed, Italian "camera" is "punto di vista", DInputBase/DCalendar validation messages come from ErrorMessages, DataTransfer's spinner has its label. - CLAUDE.md follows: client storage, JS interop, PWA, the D fields' messages. Verified: dotnet build decePubClient.csproj and decePubClient.sln -c Release (0 errors, no new warnings); a Pasture publish served by the pasture's decepub peer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WpVCoDeM1qUTRp4fXQdfof
213 lines
7.8 KiB
C#
213 lines
7.8 KiB
C#
using Blazored.LocalStorage;
|
|
|
|
using decePubClient.Helpers;
|
|
using decePubClient.Models;
|
|
using decePubClient.Models.Mastodon;
|
|
using decePubClient.Services;
|
|
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
|
|
|
|
using PrivaPub.ClientModels;
|
|
|
|
using System.Globalization;
|
|
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using System.Text.Json;
|
|
using System.Text.RegularExpressions;
|
|
using System.Web;
|
|
|
|
namespace decePubClient.Extensions
|
|
{
|
|
public static partial class ExtensionMethods
|
|
{
|
|
#region Setups
|
|
|
|
/// <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)
|
|
{
|
|
var culture = ToCulture(default);
|
|
try
|
|
{
|
|
var storage = host.Services.GetRequiredService<ILocalStorageService>();
|
|
var publicCache = await storage.GetItemAsync<PublicCacheData>(nameof(PublicCacheData), cancellationToken);
|
|
if (publicCache is null)
|
|
{
|
|
var browserLanguage = host.Services.GetRequiredService<AppStatusService>().Language();
|
|
publicCache = new();
|
|
publicCache.PageSettings.CurrentLanguageCode =
|
|
SupportedLanguages.FirstOrDefault(language => browserLanguage?.StartsWith(language) ?? false) ?? "en";
|
|
await storage.SetItemAsync(nameof(PublicCacheData), publicCache, cancellationToken);
|
|
}
|
|
|
|
culture = ToCulture(publicCache.PageSettings.CurrentLanguageCode);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine(ex);
|
|
}
|
|
|
|
CultureInfo.DefaultThreadCurrentCulture = culture;
|
|
CultureInfo.DefaultThreadCurrentUICulture = culture;
|
|
}
|
|
|
|
static CultureInfo ToCulture(string languageCode) => languageCode is "it" ? new("it-IT") : new("en-GB");
|
|
|
|
#endregion Setups
|
|
|
|
#region Models
|
|
|
|
public static string ToString(this WebResult webResult, CoalescingStringLocalizer localizer) =>
|
|
localizer["{0} - {1}", webResult.StatusCode, webResult.ErrorMessage];
|
|
|
|
/// <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 (TryReadMastodonError(json) is { } mastodonError)
|
|
return result.Invalidate(mastodonError, (int)statusCode);
|
|
|
|
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>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>
|
|
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>();
|
|
}
|
|
catch (JsonException ex)
|
|
{
|
|
Console.Error.WriteLine($"{nameof(DefaultReadFromJsonAsync)}<{typeof(T).Name}> {response.RequestMessage?.RequestUri}: {ex.Message}");
|
|
return SUtility.CancellationDefault<T>();
|
|
}
|
|
}
|
|
|
|
public static AuthorizationPolicy IsAdminPolicy() =>
|
|
new AuthorizationPolicyBuilder().RequireAuthenticatedUser()
|
|
.RequireClaim(Policies.IsAdmin, "true")
|
|
.RequireClaim(Policies.IsUser, "true")
|
|
.RequireClaim(Policies.IsModerator, "true")
|
|
.Build();
|
|
|
|
public static AuthorizationPolicy IsUserPolicy() =>
|
|
new AuthorizationPolicyBuilder().RequireAuthenticatedUser()
|
|
.RequireClaim(Policies.IsUser, "true")
|
|
.Build();
|
|
|
|
public static AuthorizationPolicy IsUserModeratorPolicy() =>
|
|
new AuthorizationPolicyBuilder().RequireAuthenticatedUser()
|
|
.RequireClaim(Policies.IsModerator, "true")
|
|
.Build();
|
|
|
|
#endregion
|
|
}
|
|
} |