From 4f74c0ac12fa6544139d148152c44332d574f939 Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:08:54 -0300 Subject: [PATCH 01/66] feat(web): scaffold Queueify.Web, Core on net10.0, ADR-0010 Co-Authored-By: Claude Sonnet 5.5 --- Queueify.Core/Queueify.Core.csproj | 9 +- Queueify.Web.Tests/Queueify.Web.Tests.csproj | 24 ++ Queueify.Web.Tests/SmokeTests.cs | 13 + ...omponentsEndpointRouteBuilderExtensions.cs | 152 ++++++++ .../Account/IdentityNoOpEmailSender.cs | 20 + .../Account/IdentityRedirectManager.cs | 55 +++ ...RevalidatingAuthenticationStateProvider.cs | 47 +++ .../Account/Pages/AccessDenied.razor | 8 + .../Account/Pages/ConfirmEmail.razor | 49 +++ .../Account/Pages/ConfirmEmailChange.razor | 69 ++++ .../Account/Pages/ExternalLogin.razor | 217 +++++++++++ .../Account/Pages/ForgotPassword.razor | 74 ++++ .../Pages/ForgotPasswordConfirmation.razor | 8 + .../Account/Pages/InvalidPasswordReset.razor | 8 + .../Account/Pages/InvalidUser.razor | 7 + .../Components/Account/Pages/Lockout.razor | 8 + .../Components/Account/Pages/Login.razor | 164 ++++++++ .../Account/Pages/LoginWith2fa.razor | 103 ++++++ .../Account/Pages/LoginWithRecoveryCode.razor | 87 +++++ .../Account/Pages/Manage/ChangePassword.razor | 109 ++++++ .../Pages/Manage/DeletePersonalData.razor | 97 +++++ .../Account/Pages/Manage/Disable2fa.razor | 74 ++++ .../Account/Pages/Manage/Email.razor | 143 +++++++ .../Pages/Manage/EnableAuthenticator.razor | 184 +++++++++ .../Account/Pages/Manage/ExternalLogins.razor | 162 ++++++++ .../Pages/Manage/GenerateRecoveryCodes.razor | 78 ++++ .../Account/Pages/Manage/Index.razor | 91 +++++ .../Account/Pages/Manage/Passkeys.razor | 182 +++++++++ .../Account/Pages/Manage/PersonalData.razor | 42 +++ .../Account/Pages/Manage/RenamePasskey.razor | 95 +++++ .../Pages/Manage/ResetAuthenticator.razor | 57 +++ .../Account/Pages/Manage/SetPassword.razor | 99 +++++ .../Manage/TwoFactorAuthentication.razor | 106 ++++++ .../Account/Pages/Manage/_Imports.razor | 2 + .../Components/Account/Pages/Register.razor | 152 ++++++++ .../Account/Pages/RegisterConfirmation.razor | 69 ++++ .../Pages/ResendEmailConfirmation.razor | 73 ++++ .../Account/Pages/ResetPassword.razor | 108 ++++++ .../Pages/ResetPasswordConfirmation.razor | 7 + .../Components/Account/Pages/_Imports.razor | 2 + .../Components/Account/PasskeyInputModel.cs | 7 + .../Components/Account/PasskeyOperation.cs | 7 + .../Account/Shared/ExternalLoginPicker.razor | 43 +++ .../Account/Shared/ManageLayout.razor | 17 + .../Account/Shared/ManageNavMenu.razor | 40 ++ .../Account/Shared/PasskeySubmit.razor | 40 ++ .../Account/Shared/PasskeySubmit.razor.js | 123 ++++++ .../Account/Shared/RedirectToLogin.razor | 8 + .../Account/Shared/ShowRecoveryCodes.razor | 28 ++ .../Account/Shared/StatusMessage.razor | 29 ++ Queueify.Web/Components/App.razor | 24 ++ .../Components/Layout/MainLayout.razor | 23 ++ .../Components/Layout/MainLayout.razor.css | 98 +++++ Queueify.Web/Components/Layout/NavMenu.razor | 92 +++++ .../Components/Layout/NavMenu.razor.css | 125 +++++++ .../Components/Layout/ReconnectModal.razor | 31 ++ .../Layout/ReconnectModal.razor.css | 157 ++++++++ .../Components/Layout/ReconnectModal.razor.js | 63 ++++ Queueify.Web/Components/Pages/Auth.razor | 13 + Queueify.Web/Components/Pages/Error.razor | 36 ++ Queueify.Web/Components/Pages/Home.razor | 7 + Queueify.Web/Components/Pages/NotFound.razor | 5 + Queueify.Web/Components/Routes.razor | 11 + Queueify.Web/Components/_Imports.razor | 12 + Queueify.Web/Data/ApplicationDbContext.cs | 8 + Queueify.Web/Data/ApplicationUser.cs | 9 + ...000000000_CreateIdentitySchema.Designer.cs | 350 ++++++++++++++++++ .../00000000000000_CreateIdentitySchema.cs | 249 +++++++++++++ .../ApplicationDbContextModelSnapshot.cs | 347 +++++++++++++++++ Queueify.Web/Data/app.db | Bin 0 -> 118784 bytes Queueify.Web/Program.cs | 69 ++++ Queueify.Web/Properties/launchSettings.json | 23 ++ Queueify.Web/Queueify.Web.csproj | 29 ++ Queueify.Web/appsettings.Development.json | 8 + Queueify.Web/appsettings.json | 12 + Queueify.Web/wwwroot/app.css | 60 +++ Queueify.Web/wwwroot/favicon.png | Bin 0 -> 1148 bytes Queueify.slnx | 2 + docs/WEB_PORT.md | 145 ++++++++ docs/adr/0010-web-app-and-shared-queue.md | 59 +++ docs/adr/README.md | 1 + 81 files changed, 5462 insertions(+), 2 deletions(-) create mode 100644 Queueify.Web.Tests/Queueify.Web.Tests.csproj create mode 100644 Queueify.Web.Tests/SmokeTests.cs create mode 100644 Queueify.Web/Components/Account/IdentityComponentsEndpointRouteBuilderExtensions.cs create mode 100644 Queueify.Web/Components/Account/IdentityNoOpEmailSender.cs create mode 100644 Queueify.Web/Components/Account/IdentityRedirectManager.cs create mode 100644 Queueify.Web/Components/Account/IdentityRevalidatingAuthenticationStateProvider.cs create mode 100644 Queueify.Web/Components/Account/Pages/AccessDenied.razor create mode 100644 Queueify.Web/Components/Account/Pages/ConfirmEmail.razor create mode 100644 Queueify.Web/Components/Account/Pages/ConfirmEmailChange.razor create mode 100644 Queueify.Web/Components/Account/Pages/ExternalLogin.razor create mode 100644 Queueify.Web/Components/Account/Pages/ForgotPassword.razor create mode 100644 Queueify.Web/Components/Account/Pages/ForgotPasswordConfirmation.razor create mode 100644 Queueify.Web/Components/Account/Pages/InvalidPasswordReset.razor create mode 100644 Queueify.Web/Components/Account/Pages/InvalidUser.razor create mode 100644 Queueify.Web/Components/Account/Pages/Lockout.razor create mode 100644 Queueify.Web/Components/Account/Pages/Login.razor create mode 100644 Queueify.Web/Components/Account/Pages/LoginWith2fa.razor create mode 100644 Queueify.Web/Components/Account/Pages/LoginWithRecoveryCode.razor create mode 100644 Queueify.Web/Components/Account/Pages/Manage/ChangePassword.razor create mode 100644 Queueify.Web/Components/Account/Pages/Manage/DeletePersonalData.razor create mode 100644 Queueify.Web/Components/Account/Pages/Manage/Disable2fa.razor create mode 100644 Queueify.Web/Components/Account/Pages/Manage/Email.razor create mode 100644 Queueify.Web/Components/Account/Pages/Manage/EnableAuthenticator.razor create mode 100644 Queueify.Web/Components/Account/Pages/Manage/ExternalLogins.razor create mode 100644 Queueify.Web/Components/Account/Pages/Manage/GenerateRecoveryCodes.razor create mode 100644 Queueify.Web/Components/Account/Pages/Manage/Index.razor create mode 100644 Queueify.Web/Components/Account/Pages/Manage/Passkeys.razor create mode 100644 Queueify.Web/Components/Account/Pages/Manage/PersonalData.razor create mode 100644 Queueify.Web/Components/Account/Pages/Manage/RenamePasskey.razor create mode 100644 Queueify.Web/Components/Account/Pages/Manage/ResetAuthenticator.razor create mode 100644 Queueify.Web/Components/Account/Pages/Manage/SetPassword.razor create mode 100644 Queueify.Web/Components/Account/Pages/Manage/TwoFactorAuthentication.razor create mode 100644 Queueify.Web/Components/Account/Pages/Manage/_Imports.razor create mode 100644 Queueify.Web/Components/Account/Pages/Register.razor create mode 100644 Queueify.Web/Components/Account/Pages/RegisterConfirmation.razor create mode 100644 Queueify.Web/Components/Account/Pages/ResendEmailConfirmation.razor create mode 100644 Queueify.Web/Components/Account/Pages/ResetPassword.razor create mode 100644 Queueify.Web/Components/Account/Pages/ResetPasswordConfirmation.razor create mode 100644 Queueify.Web/Components/Account/Pages/_Imports.razor create mode 100644 Queueify.Web/Components/Account/PasskeyInputModel.cs create mode 100644 Queueify.Web/Components/Account/PasskeyOperation.cs create mode 100644 Queueify.Web/Components/Account/Shared/ExternalLoginPicker.razor create mode 100644 Queueify.Web/Components/Account/Shared/ManageLayout.razor create mode 100644 Queueify.Web/Components/Account/Shared/ManageNavMenu.razor create mode 100644 Queueify.Web/Components/Account/Shared/PasskeySubmit.razor create mode 100644 Queueify.Web/Components/Account/Shared/PasskeySubmit.razor.js create mode 100644 Queueify.Web/Components/Account/Shared/RedirectToLogin.razor create mode 100644 Queueify.Web/Components/Account/Shared/ShowRecoveryCodes.razor create mode 100644 Queueify.Web/Components/Account/Shared/StatusMessage.razor create mode 100644 Queueify.Web/Components/App.razor create mode 100644 Queueify.Web/Components/Layout/MainLayout.razor create mode 100644 Queueify.Web/Components/Layout/MainLayout.razor.css create mode 100644 Queueify.Web/Components/Layout/NavMenu.razor create mode 100644 Queueify.Web/Components/Layout/NavMenu.razor.css create mode 100644 Queueify.Web/Components/Layout/ReconnectModal.razor create mode 100644 Queueify.Web/Components/Layout/ReconnectModal.razor.css create mode 100644 Queueify.Web/Components/Layout/ReconnectModal.razor.js create mode 100644 Queueify.Web/Components/Pages/Auth.razor create mode 100644 Queueify.Web/Components/Pages/Error.razor create mode 100644 Queueify.Web/Components/Pages/Home.razor create mode 100644 Queueify.Web/Components/Pages/NotFound.razor create mode 100644 Queueify.Web/Components/Routes.razor create mode 100644 Queueify.Web/Components/_Imports.razor create mode 100644 Queueify.Web/Data/ApplicationDbContext.cs create mode 100644 Queueify.Web/Data/ApplicationUser.cs create mode 100644 Queueify.Web/Data/Migrations/00000000000000_CreateIdentitySchema.Designer.cs create mode 100644 Queueify.Web/Data/Migrations/00000000000000_CreateIdentitySchema.cs create mode 100644 Queueify.Web/Data/Migrations/ApplicationDbContextModelSnapshot.cs create mode 100644 Queueify.Web/Data/app.db create mode 100644 Queueify.Web/Program.cs create mode 100644 Queueify.Web/Properties/launchSettings.json create mode 100644 Queueify.Web/Queueify.Web.csproj create mode 100644 Queueify.Web/appsettings.Development.json create mode 100644 Queueify.Web/appsettings.json create mode 100644 Queueify.Web/wwwroot/app.css create mode 100644 Queueify.Web/wwwroot/favicon.png create mode 100644 docs/WEB_PORT.md create mode 100644 docs/adr/0010-web-app-and-shared-queue.md diff --git a/Queueify.Core/Queueify.Core.csproj b/Queueify.Core/Queueify.Core.csproj index a5adc3b..0c7b5c4 100644 --- a/Queueify.Core/Queueify.Core.csproj +++ b/Queueify.Core/Queueify.Core.csproj @@ -1,8 +1,9 @@ - net10.0-windows10.0.26100.0 - 10.0.19041.0 + + net10.0;net10.0-windows10.0.26100.0 + 10.0.19041.0 Queueify enable enable @@ -13,6 +14,10 @@ embedded + + + + diff --git a/Queueify.Web.Tests/Queueify.Web.Tests.csproj b/Queueify.Web.Tests/Queueify.Web.Tests.csproj new file mode 100644 index 0000000..e5094f2 --- /dev/null +++ b/Queueify.Web.Tests/Queueify.Web.Tests.csproj @@ -0,0 +1,24 @@ + + + + net10.0 + Exe + enable + enable + false + + + + + + + + + + + + + + + + diff --git a/Queueify.Web.Tests/SmokeTests.cs b/Queueify.Web.Tests/SmokeTests.cs new file mode 100644 index 0000000..b9a658f --- /dev/null +++ b/Queueify.Web.Tests/SmokeTests.cs @@ -0,0 +1,13 @@ +using Microsoft.AspNetCore.Mvc.Testing; + +namespace Queueify.Web.Tests; + +public sealed class SmokeTests(WebApplicationFactory factory) : IClassFixture> +{ + [Fact] + public async Task Health_endpoint_answers_without_signing_in() + { + var response = await factory.CreateClient().GetAsync("/healthz"); + Assert.True(response.IsSuccessStatusCode); + } +} diff --git a/Queueify.Web/Components/Account/IdentityComponentsEndpointRouteBuilderExtensions.cs b/Queueify.Web/Components/Account/IdentityComponentsEndpointRouteBuilderExtensions.cs new file mode 100644 index 0000000..42d85a6 --- /dev/null +++ b/Queueify.Web/Components/Account/IdentityComponentsEndpointRouteBuilderExtensions.cs @@ -0,0 +1,152 @@ +using System.Security.Claims; +using System.Text.Json; +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Components.Authorization; +using Microsoft.AspNetCore.Http.Extensions; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Primitives; +using Queueify.Web.Components.Account.Pages; +using Queueify.Web.Components.Account.Pages.Manage; +using Queueify.Web.Data; + +namespace Microsoft.AspNetCore.Routing; + +internal static class IdentityComponentsEndpointRouteBuilderExtensions +{ + // These endpoints are required by the Identity Razor components defined in the /Components/Account/Pages directory of this project. + public static IEndpointConventionBuilder MapAdditionalIdentityEndpoints(this IEndpointRouteBuilder endpoints) + { + ArgumentNullException.ThrowIfNull(endpoints); + + var accountGroup = endpoints.MapGroup("/Account"); + + accountGroup.MapPost("/PerformExternalLogin", ( + HttpContext context, + [FromServices] SignInManager signInManager, + [FromForm] string provider, + [FromForm] string returnUrl) => + { + IEnumerable> query = [ + new("ReturnUrl", returnUrl), + new("Action", ExternalLogin.LoginCallbackAction)]; + + var redirectUrl = UriHelper.BuildRelative( + context.Request.PathBase, + "/Account/ExternalLogin", + QueryString.Create(query)); + + var properties = signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl); + return TypedResults.Challenge(properties, [provider]); + }); + + accountGroup.MapPost("/Logout", async ( + ClaimsPrincipal user, + [FromServices] SignInManager signInManager, + [FromForm] string returnUrl) => + { + await signInManager.SignOutAsync(); + return TypedResults.LocalRedirect($"~/{returnUrl}"); + }); + + accountGroup.MapPost("/PasskeyCreationOptions", async ( + HttpContext context, + [FromServices] UserManager userManager, + [FromServices] SignInManager signInManager, + [FromServices] IAntiforgery antiforgery) => + { + await antiforgery.ValidateRequestAsync(context); + + var user = await userManager.GetUserAsync(context.User); + if (user is null) + { + return Results.NotFound($"Unable to load user with ID '{userManager.GetUserId(context.User)}'."); + } + + var userId = await userManager.GetUserIdAsync(user); + var userName = await userManager.GetUserNameAsync(user) ?? "User"; + var optionsJson = await signInManager.MakePasskeyCreationOptionsAsync(new() + { + Id = userId, + Name = userName, + DisplayName = userName + }); + return TypedResults.Content(optionsJson, contentType: "application/json"); + }); + + accountGroup.MapPost("/PasskeyRequestOptions", async ( + HttpContext context, + [FromServices] UserManager userManager, + [FromServices] SignInManager signInManager, + [FromServices] IAntiforgery antiforgery, + [FromQuery] string? username) => + { + await antiforgery.ValidateRequestAsync(context); + + var user = string.IsNullOrEmpty(username) ? null : await userManager.FindByNameAsync(username); + var optionsJson = await signInManager.MakePasskeyRequestOptionsAsync(user); + return TypedResults.Content(optionsJson, contentType: "application/json"); + }); + + var manageGroup = accountGroup.MapGroup("/Manage").RequireAuthorization(); + + manageGroup.MapPost("/LinkExternalLogin", async ( + HttpContext context, + [FromServices] SignInManager signInManager, + [FromForm] string provider) => + { + // Clear the existing external cookie to ensure a clean login process + await context.SignOutAsync(IdentityConstants.ExternalScheme); + + var redirectUrl = UriHelper.BuildRelative( + context.Request.PathBase, + "/Account/Manage/ExternalLogins", + QueryString.Create("Action", ExternalLogins.LinkLoginCallbackAction)); + + var properties = signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, signInManager.UserManager.GetUserId(context.User)); + return TypedResults.Challenge(properties, [provider]); + }); + + var loggerFactory = endpoints.ServiceProvider.GetRequiredService(); + var downloadLogger = loggerFactory.CreateLogger("DownloadPersonalData"); + + manageGroup.MapPost("/DownloadPersonalData", async ( + HttpContext context, + [FromServices] UserManager userManager, + [FromServices] AuthenticationStateProvider authenticationStateProvider) => + { + var user = await userManager.GetUserAsync(context.User); + if (user is null) + { + return Results.NotFound($"Unable to load user with ID '{userManager.GetUserId(context.User)}'."); + } + + var userId = await userManager.GetUserIdAsync(user); + downloadLogger.LogInformation("User with ID '{UserId}' asked for their personal data.", userId); + + // Only include personal data for download + var personalData = new Dictionary(); + var personalDataProps = typeof(ApplicationUser).GetProperties().Where( + prop => Attribute.IsDefined(prop, typeof(PersonalDataAttribute))); + foreach (var p in personalDataProps) + { + personalData.Add(p.Name, p.GetValue(user)?.ToString() ?? "null"); + } + + var logins = await userManager.GetLoginsAsync(user); + foreach (var l in logins) + { + personalData.Add($"{l.LoginProvider} external login provider key", l.ProviderKey); + } + + personalData.Add("Authenticator Key", (await userManager.GetAuthenticatorKeyAsync(user))!); + var fileBytes = JsonSerializer.SerializeToUtf8Bytes(personalData); + + context.Response.Headers.TryAdd("Content-Disposition", "attachment; filename=PersonalData.json"); + return TypedResults.File(fileBytes, contentType: "application/json", fileDownloadName: "PersonalData.json"); + }); + + return accountGroup; + } +} diff --git a/Queueify.Web/Components/Account/IdentityNoOpEmailSender.cs b/Queueify.Web/Components/Account/IdentityNoOpEmailSender.cs new file mode 100644 index 0000000..b5e43e2 --- /dev/null +++ b/Queueify.Web/Components/Account/IdentityNoOpEmailSender.cs @@ -0,0 +1,20 @@ +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Identity.UI.Services; +using Queueify.Web.Data; + +namespace Queueify.Web.Components.Account; + +// Remove the "else if (EmailSender is IdentityNoOpEmailSender)" block from RegisterConfirmation.razor after updating with a real implementation. +internal sealed class IdentityNoOpEmailSender : IEmailSender +{ + private readonly IEmailSender emailSender = new NoOpEmailSender(); + + public Task SendConfirmationLinkAsync(ApplicationUser user, string email, string confirmationLink) => + emailSender.SendEmailAsync(email, "Confirm your email", $"Please confirm your account by clicking here."); + + public Task SendPasswordResetLinkAsync(ApplicationUser user, string email, string resetLink) => + emailSender.SendEmailAsync(email, "Reset your password", $"Please reset your password by clicking here."); + + public Task SendPasswordResetCodeAsync(ApplicationUser user, string email, string resetCode) => + emailSender.SendEmailAsync(email, "Reset your password", $"Please reset your password using the following code: {resetCode}"); +} diff --git a/Queueify.Web/Components/Account/IdentityRedirectManager.cs b/Queueify.Web/Components/Account/IdentityRedirectManager.cs new file mode 100644 index 0000000..e5004f7 --- /dev/null +++ b/Queueify.Web/Components/Account/IdentityRedirectManager.cs @@ -0,0 +1,55 @@ +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Identity; +using Queueify.Web.Data; + +namespace Queueify.Web.Components.Account; + +internal sealed class IdentityRedirectManager(NavigationManager navigationManager) +{ + public const string StatusCookieName = "Identity.StatusMessage"; + + private static readonly CookieBuilder StatusCookieBuilder = new() + { + SameSite = SameSiteMode.Strict, + HttpOnly = true, + IsEssential = true, + MaxAge = TimeSpan.FromSeconds(5), + }; + + public void RedirectTo(string? uri) + { + uri ??= ""; + + // Prevent open redirects. + if (!Uri.IsWellFormedUriString(uri, UriKind.Relative) + || uri.StartsWith("//", StringComparison.Ordinal)) + { + uri = navigationManager.ToBaseRelativePath(uri); + } + + navigationManager.NavigateTo(uri); + } + + public void RedirectTo(string uri, Dictionary queryParameters) + { + var uriWithoutQuery = navigationManager.ToAbsoluteUri(uri).GetLeftPart(UriPartial.Path); + var newUri = navigationManager.GetUriWithQueryParameters(uriWithoutQuery, queryParameters); + RedirectTo(newUri); + } + + public void RedirectToWithStatus(string uri, string message, HttpContext context) + { + context.Response.Cookies.Append(StatusCookieName, message, StatusCookieBuilder.Build(context)); + RedirectTo(uri); + } + + private string CurrentPath => navigationManager.ToAbsoluteUri(navigationManager.Uri).GetLeftPart(UriPartial.Path); + + public void RedirectToCurrentPage() => RedirectTo(CurrentPath); + + public void RedirectToCurrentPageWithStatus(string message, HttpContext context) + => RedirectToWithStatus(CurrentPath, message, context); + + public void RedirectToInvalidUser(UserManager userManager, HttpContext context) + => RedirectToWithStatus("Account/InvalidUser", $"Error: Unable to load user with ID '{userManager.GetUserId(context.User)}'.", context); +} diff --git a/Queueify.Web/Components/Account/IdentityRevalidatingAuthenticationStateProvider.cs b/Queueify.Web/Components/Account/IdentityRevalidatingAuthenticationStateProvider.cs new file mode 100644 index 0000000..27f8cce --- /dev/null +++ b/Queueify.Web/Components/Account/IdentityRevalidatingAuthenticationStateProvider.cs @@ -0,0 +1,47 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Components.Authorization; +using Microsoft.AspNetCore.Components.Server; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Options; +using Queueify.Web.Data; + +namespace Queueify.Web.Components.Account; + +// This is a server-side AuthenticationStateProvider that revalidates the security stamp for the connected user +// every 30 minutes an interactive circuit is connected. +internal sealed class IdentityRevalidatingAuthenticationStateProvider( + ILoggerFactory loggerFactory, + IServiceScopeFactory scopeFactory, + IOptions options) + : RevalidatingServerAuthenticationStateProvider(loggerFactory) +{ + protected override TimeSpan RevalidationInterval => TimeSpan.FromMinutes(30); + + protected override async Task ValidateAuthenticationStateAsync( + AuthenticationState authenticationState, CancellationToken cancellationToken) + { + // Get the user manager from a new scope to ensure it fetches fresh data + await using var scope = scopeFactory.CreateAsyncScope(); + var userManager = scope.ServiceProvider.GetRequiredService>(); + return await ValidateSecurityStampAsync(userManager, authenticationState.User); + } + + private async Task ValidateSecurityStampAsync(UserManager userManager, ClaimsPrincipal principal) + { + var user = await userManager.GetUserAsync(principal); + if (user is null) + { + return false; + } + else if (!userManager.SupportsUserSecurityStamp) + { + return true; + } + else + { + var principalStamp = principal.FindFirstValue(options.Value.ClaimsIdentity.SecurityStampClaimType); + var userStamp = await userManager.GetSecurityStampAsync(user); + return principalStamp == userStamp; + } + } +} diff --git a/Queueify.Web/Components/Account/Pages/AccessDenied.razor b/Queueify.Web/Components/Account/Pages/AccessDenied.razor new file mode 100644 index 0000000..905dec3 --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/AccessDenied.razor @@ -0,0 +1,8 @@ +@page "/Account/AccessDenied" + +Access denied + +
+

Access denied

+

You do not have access to this resource.

+
diff --git a/Queueify.Web/Components/Account/Pages/ConfirmEmail.razor b/Queueify.Web/Components/Account/Pages/ConfirmEmail.razor new file mode 100644 index 0000000..56dd2cf --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/ConfirmEmail.razor @@ -0,0 +1,49 @@ +@page "/Account/ConfirmEmail" + +@using System.Text +@using Microsoft.AspNetCore.Identity +@using Microsoft.AspNetCore.WebUtilities +@using Queueify.Web.Data + +@inject UserManager UserManager +@inject IdentityRedirectManager RedirectManager + +Confirm email + +

Confirm email

+ + +@code { + private string? statusMessage; + + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + [SupplyParameterFromQuery] + private string? UserId { get; set; } + + [SupplyParameterFromQuery] + private string? Code { get; set; } + + protected override async Task OnInitializedAsync() + { + if (UserId is null || Code is null) + { + RedirectManager.RedirectTo(""); + return; + } + + var user = await UserManager.FindByIdAsync(UserId); + if (user is null) + { + HttpContext.Response.StatusCode = StatusCodes.Status404NotFound; + statusMessage = $"Error loading user with ID {UserId}"; + } + else + { + var code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(Code)); + var result = await UserManager.ConfirmEmailAsync(user, code); + statusMessage = result.Succeeded ? "Thank you for confirming your email." : "Error confirming your email."; + } + } +} diff --git a/Queueify.Web/Components/Account/Pages/ConfirmEmailChange.razor b/Queueify.Web/Components/Account/Pages/ConfirmEmailChange.razor new file mode 100644 index 0000000..8feddd0 --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/ConfirmEmailChange.razor @@ -0,0 +1,69 @@ +@page "/Account/ConfirmEmailChange" + +@using System.Text +@using Microsoft.AspNetCore.Identity +@using Microsoft.AspNetCore.WebUtilities +@using Queueify.Web.Data + +@inject UserManager UserManager +@inject SignInManager SignInManager +@inject IdentityRedirectManager RedirectManager + +Confirm email change + +

Confirm email change

+ + + +@code { + private string? message; + + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + [SupplyParameterFromQuery] + private string? UserId { get; set; } + + [SupplyParameterFromQuery] + private string? Email { get; set; } + + [SupplyParameterFromQuery] + private string? Code { get; set; } + + protected override async Task OnInitializedAsync() + { + if (UserId is null || Email is null || Code is null) + { + RedirectManager.RedirectToWithStatus( + "Account/Login", "Error: Invalid email change confirmation link.", HttpContext); + return; + } + + var user = await UserManager.FindByIdAsync(UserId); + if (user is null) + { + message = "Unable to find user with Id '{userId}'"; + return; + } + + var code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(Code)); + var result = await UserManager.ChangeEmailAsync(user, Email, code); + if (!result.Succeeded) + { + message = "Error changing email."; + return; + } + + // In our UI email and user name are one and the same, so when we update the email + // we need to update the user name. + var setUserNameResult = await UserManager.SetUserNameAsync(user, Email); + if (!setUserNameResult.Succeeded) + { + message = "Error changing user name."; + return; + } + + await SignInManager.RefreshSignInAsync(user); + message = "Thank you for confirming your email change."; + } +} diff --git a/Queueify.Web/Components/Account/Pages/ExternalLogin.razor b/Queueify.Web/Components/Account/Pages/ExternalLogin.razor new file mode 100644 index 0000000..b6ce168 --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/ExternalLogin.razor @@ -0,0 +1,217 @@ +@page "/Account/ExternalLogin" + +@using System.ComponentModel.DataAnnotations +@using System.Security.Claims +@using System.Text +@using System.Text.Encodings.Web +@using Microsoft.AspNetCore.Identity +@using Microsoft.AspNetCore.WebUtilities +@using Queueify.Web.Data + +@inject SignInManager SignInManager +@inject UserManager UserManager +@inject IUserStore UserStore +@inject IEmailSender EmailSender +@inject NavigationManager NavigationManager +@inject IdentityRedirectManager RedirectManager +@inject ILogger Logger + +Register + + +

Register

+

Associate your @ProviderDisplayName account.

+
+ +
+ You've successfully authenticated with @ProviderDisplayName. + Please enter an email address for this site below and click the Register button to finish + logging in. +
+ +
+
+ + + +
+ + + +
+ +
+
+
+ +@code { + public const string LoginCallbackAction = "LoginCallback"; + + private string? message; + private ExternalLoginInfo? externalLoginInfo; + + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + [SupplyParameterFromForm] + private InputModel Input { get; set; } = default!; + + [SupplyParameterFromQuery] + private string? RemoteError { get; set; } + + [SupplyParameterFromQuery] + private string? ReturnUrl { get; set; } + + [SupplyParameterFromQuery] + private string? Action { get; set; } + + private string? ProviderDisplayName => externalLoginInfo?.ProviderDisplayName; + + protected override async Task OnInitializedAsync() + { + Input ??= new(); + + if (RemoteError is not null) + { + RedirectManager.RedirectToWithStatus("Account/Login", $"Error from external provider: {RemoteError}", HttpContext); + return; + } + + var info = await SignInManager.GetExternalLoginInfoAsync(); + if (info is null) + { + RedirectManager.RedirectToWithStatus("Account/Login", "Error loading external login information.", HttpContext); + return; + } + + externalLoginInfo = info; + + if (HttpMethods.IsGet(HttpContext.Request.Method)) + { + if (Action == LoginCallbackAction) + { + await OnLoginCallbackAsync(); + return; + } + + // We should only reach this page via the login callback, so redirect back to + // the login page if we get here some other way. + RedirectManager.RedirectTo("Account/Login"); + } + } + + private async Task OnLoginCallbackAsync() + { + if (externalLoginInfo is null) + { + RedirectManager.RedirectToWithStatus("Account/Login", "Error loading external login information.", HttpContext); + return; + } + + // Sign in the user with this external login provider if the user already has a login. + var result = await SignInManager.ExternalLoginSignInAsync( + externalLoginInfo.LoginProvider, + externalLoginInfo.ProviderKey, + isPersistent: false, + bypassTwoFactor: true); + + if (result.Succeeded) + { + Logger.LogInformation( + "{Name} logged in with {LoginProvider} provider.", + externalLoginInfo.Principal.Identity?.Name, + externalLoginInfo.LoginProvider); + RedirectManager.RedirectTo(ReturnUrl); + return; + } + else if (result.IsLockedOut) + { + RedirectManager.RedirectTo("Account/Lockout"); + return; + } + + // If the user does not have an account, then ask the user to create an account. + if (externalLoginInfo.Principal.HasClaim(c => c.Type == ClaimTypes.Email)) + { + Input.Email = externalLoginInfo.Principal.FindFirstValue(ClaimTypes.Email) ?? ""; + } + } + + private async Task OnValidSubmitAsync() + { + if (externalLoginInfo is null) + { + RedirectManager.RedirectToWithStatus("Account/Login", "Error loading external login information during confirmation.", HttpContext); + return; + } + + var emailStore = GetEmailStore(); + var user = CreateUser(); + + await UserStore.SetUserNameAsync(user, Input.Email, CancellationToken.None); + await emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None); + + var result = await UserManager.CreateAsync(user); + if (result.Succeeded) + { + result = await UserManager.AddLoginAsync(user, externalLoginInfo); + if (result.Succeeded) + { + Logger.LogInformation("User created an account using {Name} provider.", externalLoginInfo.LoginProvider); + + var userId = await UserManager.GetUserIdAsync(user); + var code = await UserManager.GenerateEmailConfirmationTokenAsync(user); + code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); + + var callbackUrl = NavigationManager.GetUriWithQueryParameters( + NavigationManager.ToAbsoluteUri("Account/ConfirmEmail").AbsoluteUri, + new Dictionary { ["userId"] = userId, ["code"] = code }); + await EmailSender.SendConfirmationLinkAsync(user, Input.Email, HtmlEncoder.Default.Encode(callbackUrl)); + + // If account confirmation is required, we need to show the link if we don't have a real email sender + if (UserManager.Options.SignIn.RequireConfirmedAccount) + { + RedirectManager.RedirectTo("Account/RegisterConfirmation", new() { ["email"] = Input.Email }); + } + else + { + await SignInManager.SignInAsync(user, isPersistent: false, externalLoginInfo.LoginProvider); + RedirectManager.RedirectTo(ReturnUrl); + } + } + } + else + { + message = $"Error: {string.Join(",", result.Errors.Select(error => error.Description))}"; + } + } + + private ApplicationUser CreateUser() + { + try + { + return Activator.CreateInstance(); + } + catch + { + throw new InvalidOperationException($"Can't create an instance of '{nameof(ApplicationUser)}'. " + + $"Ensure that '{nameof(ApplicationUser)}' is not an abstract class and has a parameterless constructor"); + } + } + + private IUserEmailStore GetEmailStore() + { + if (!UserManager.SupportsUserEmail) + { + throw new NotSupportedException("The default UI requires a user store with email support."); + } + return (IUserEmailStore)UserStore; + } + + private sealed class InputModel + { + [Required] + [EmailAddress] + public string Email { get; set; } = ""; + } +} diff --git a/Queueify.Web/Components/Account/Pages/ForgotPassword.razor b/Queueify.Web/Components/Account/Pages/ForgotPassword.razor new file mode 100644 index 0000000..6c9bc5e --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/ForgotPassword.razor @@ -0,0 +1,74 @@ +@page "/Account/ForgotPassword" + +@using System.ComponentModel.DataAnnotations +@using System.Text +@using System.Text.Encodings.Web +@using Microsoft.AspNetCore.Identity +@using Microsoft.AspNetCore.WebUtilities +@using Queueify.Web.Data + +@inject UserManager UserManager +@inject IEmailSender EmailSender +@inject NavigationManager NavigationManager +@inject IdentityRedirectManager RedirectManager + +Forgot your password? + +

Forgot your password?

+

Enter your email.

+
+
+
+ + + + +
+ + + +
+ +
+
+
+ +@code { + [SupplyParameterFromForm] + private InputModel Input { get; set; } = default!; + + protected override void OnInitialized() + { + Input ??= new(); + } + + private async Task OnValidSubmitAsync() + { + var user = await UserManager.FindByEmailAsync(Input.Email); + if (user is null || !(await UserManager.IsEmailConfirmedAsync(user))) + { + // Don't reveal that the user does not exist or is not confirmed + RedirectManager.RedirectTo("Account/ForgotPasswordConfirmation"); + return; + } + + // For more information on how to enable account confirmation and password reset please + // visit https://go.microsoft.com/fwlink/?LinkID=532713 + var code = await UserManager.GeneratePasswordResetTokenAsync(user); + code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); + var callbackUrl = NavigationManager.GetUriWithQueryParameters( + NavigationManager.ToAbsoluteUri("Account/ResetPassword").AbsoluteUri, + new Dictionary { ["code"] = code }); + + await EmailSender.SendPasswordResetLinkAsync(user, Input.Email, HtmlEncoder.Default.Encode(callbackUrl)); + + RedirectManager.RedirectTo("Account/ForgotPasswordConfirmation"); + } + + private sealed class InputModel + { + [Required] + [EmailAddress] + public string Email { get; set; } = ""; + } +} diff --git a/Queueify.Web/Components/Account/Pages/ForgotPasswordConfirmation.razor b/Queueify.Web/Components/Account/Pages/ForgotPasswordConfirmation.razor new file mode 100644 index 0000000..a771a3a --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/ForgotPasswordConfirmation.razor @@ -0,0 +1,8 @@ +@page "/Account/ForgotPasswordConfirmation" + +Forgot password confirmation + +

Forgot password confirmation

+

+ Please check your email to reset your password. +

diff --git a/Queueify.Web/Components/Account/Pages/InvalidPasswordReset.razor b/Queueify.Web/Components/Account/Pages/InvalidPasswordReset.razor new file mode 100644 index 0000000..561b651 --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/InvalidPasswordReset.razor @@ -0,0 +1,8 @@ +@page "/Account/InvalidPasswordReset" + +Invalid password reset + +

Invalid password reset

+

+ The password reset link is invalid. +

diff --git a/Queueify.Web/Components/Account/Pages/InvalidUser.razor b/Queueify.Web/Components/Account/Pages/InvalidUser.razor new file mode 100644 index 0000000..e61fe5d --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/InvalidUser.razor @@ -0,0 +1,7 @@ +@page "/Account/InvalidUser" + +Invalid user + +

Invalid user

+ + diff --git a/Queueify.Web/Components/Account/Pages/Lockout.razor b/Queueify.Web/Components/Account/Pages/Lockout.razor new file mode 100644 index 0000000..017e31d --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/Lockout.razor @@ -0,0 +1,8 @@ +@page "/Account/Lockout" + +Locked out + +
+

Locked out

+ +
diff --git a/Queueify.Web/Components/Account/Pages/Login.razor b/Queueify.Web/Components/Account/Pages/Login.razor new file mode 100644 index 0000000..2e83eda --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/Login.razor @@ -0,0 +1,164 @@ +@page "/Account/Login" + +@using System.ComponentModel.DataAnnotations +@using Microsoft.AspNetCore.Authentication +@using Microsoft.AspNetCore.Identity +@using Queueify.Web.Data + +@inject UserManager UserManager +@inject SignInManager SignInManager +@inject ILogger Logger +@inject NavigationManager NavigationManager +@inject IdentityRedirectManager RedirectManager + +Log in + +

Log in

+
+
+
+ + + +

Use a local account to log in.

+
+ +
+ + + +
+
+ + + +
+
+ +
+
+ +
+
+
+ OR + Log in with a passkey +
+
+ +
+
+
+
+
+

Use another service to log in.

+
+ +
+
+
+ +@code { + private string? errorMessage; + private EditContext editContext = default!; + + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + [SupplyParameterFromForm] + private InputModel Input { get; set; } = default!; + + [SupplyParameterFromQuery] + private string? ReturnUrl { get; set; } + + protected override async Task OnInitializedAsync() + { + Input ??= new(); + + editContext = new EditContext(Input); + + if (HttpMethods.IsGet(HttpContext.Request.Method)) + { + // Clear the existing external cookie to ensure a clean login process + await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); + } + } + + public async Task LoginUser() + { + if (!string.IsNullOrEmpty(Input.Passkey?.Error)) + { + errorMessage = $"Error: {Input.Passkey.Error}"; + return; + } + + SignInResult result; + if (!string.IsNullOrEmpty(Input.Passkey?.CredentialJson)) + { + // When performing passkey sign-in, don't perform form validation. + result = await SignInManager.PasskeySignInAsync(Input.Passkey.CredentialJson); + } + else + { + // If doing a password sign-in, validate the form. + if (!editContext.Validate()) + { + return; + } + + // This doesn't count login failures towards account lockout + // To enable password failures to trigger account lockout, set lockoutOnFailure: true + result = await SignInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false); + } + + if (result.Succeeded) + { + Logger.LogInformation("User logged in."); + RedirectManager.RedirectTo(ReturnUrl); + } + else if (result.RequiresTwoFactor) + { + RedirectManager.RedirectTo( + "Account/LoginWith2fa", + new() { ["returnUrl"] = ReturnUrl, ["rememberMe"] = Input.RememberMe }); + } + else if (result.IsLockedOut) + { + Logger.LogWarning("User account locked out."); + RedirectManager.RedirectTo("Account/Lockout"); + } + else + { + errorMessage = "Error: Invalid login attempt."; + } + } + + private sealed class InputModel + { + [Required] + [EmailAddress] + public string Email { get; set; } = ""; + + [Required] + [DataType(DataType.Password)] + public string Password { get; set; } = ""; + + [Display(Name = "Remember me?")] + public bool RememberMe { get; set; } + + public PasskeyInputModel? Passkey { get; set; } + } +} diff --git a/Queueify.Web/Components/Account/Pages/LoginWith2fa.razor b/Queueify.Web/Components/Account/Pages/LoginWith2fa.razor new file mode 100644 index 0000000..96596d0 --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/LoginWith2fa.razor @@ -0,0 +1,103 @@ +@page "/Account/LoginWith2fa" + +@using System.ComponentModel.DataAnnotations +@using Microsoft.AspNetCore.Identity +@using Queueify.Web.Data + +@inject SignInManager SignInManager +@inject UserManager UserManager +@inject IdentityRedirectManager RedirectManager +@inject ILogger Logger + +Two-factor authentication + +

Two-factor authentication

+
+ +

Your login is protected with an authenticator app. Enter your authenticator code below.

+
+
+ + + + + +
+ + + +
+
+ +
+
+ +
+
+
+
+

+ Don't have access to your authenticator device? You can + log in with a recovery code. +

+ +@code { + private string? message; + private ApplicationUser user = default!; + + [SupplyParameterFromForm] + private InputModel Input { get; set; } = default!; + + [SupplyParameterFromQuery] + private string? ReturnUrl { get; set; } + + [SupplyParameterFromQuery] + private bool RememberMe { get; set; } + + protected override async Task OnInitializedAsync() + { + Input ??= new(); + + // Ensure the user has gone through the username & password screen first + user = await SignInManager.GetTwoFactorAuthenticationUserAsync() ?? + throw new InvalidOperationException("Unable to load two-factor authentication user."); + } + + private async Task OnValidSubmitAsync() + { + var authenticatorCode = Input.TwoFactorCode!.Replace(" ", string.Empty).Replace("-", string.Empty); + var result = await SignInManager.TwoFactorAuthenticatorSignInAsync(authenticatorCode, RememberMe, Input.RememberMachine); + var userId = await UserManager.GetUserIdAsync(user); + + if (result.Succeeded) + { + Logger.LogInformation("User with ID '{UserId}' logged in with 2fa.", userId); + RedirectManager.RedirectTo(ReturnUrl); + } + else if (result.IsLockedOut) + { + Logger.LogWarning("User with ID '{UserId}' account locked out.", userId); + RedirectManager.RedirectTo("Account/Lockout"); + } + else + { + Logger.LogWarning("Invalid authenticator code entered for user with ID '{UserId}'.", userId); + message = "Error: Invalid authenticator code."; + } + } + + private sealed class InputModel + { + [Required] + [StringLength(7, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] + [DataType(DataType.Text)] + [Display(Name = "Authenticator code")] + public string? TwoFactorCode { get; set; } + + [Display(Name = "Remember this machine")] + public bool RememberMachine { get; set; } + } +} diff --git a/Queueify.Web/Components/Account/Pages/LoginWithRecoveryCode.razor b/Queueify.Web/Components/Account/Pages/LoginWithRecoveryCode.razor new file mode 100644 index 0000000..7c2bfff --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/LoginWithRecoveryCode.razor @@ -0,0 +1,87 @@ +@page "/Account/LoginWithRecoveryCode" + +@using System.ComponentModel.DataAnnotations +@using Microsoft.AspNetCore.Identity +@using Queueify.Web.Data + +@inject SignInManager SignInManager +@inject UserManager UserManager +@inject IdentityRedirectManager RedirectManager +@inject ILogger Logger + +Recovery code verification + +

Recovery code verification

+
+ +

+ You have requested to log in with a recovery code. This login will not be remembered until you provide + an authenticator app code at log in or disable 2FA and log in again. +

+
+
+ + + +
+ + + +
+ +
+
+
+ +@code { + private string? message; + private ApplicationUser user = default!; + + [SupplyParameterFromForm] + private InputModel Input { get; set; } = default!; + + [SupplyParameterFromQuery] + private string? ReturnUrl { get; set; } + + protected override async Task OnInitializedAsync() + { + Input ??= new(); + + // Ensure the user has gone through the username & password screen first + user = await SignInManager.GetTwoFactorAuthenticationUserAsync() ?? + throw new InvalidOperationException("Unable to load two-factor authentication user."); + } + + private async Task OnValidSubmitAsync() + { + var recoveryCode = Input.RecoveryCode.Replace(" ", string.Empty); + + var result = await SignInManager.TwoFactorRecoveryCodeSignInAsync(recoveryCode); + + var userId = await UserManager.GetUserIdAsync(user); + + if (result.Succeeded) + { + Logger.LogInformation("User with ID '{UserId}' logged in with a recovery code.", userId); + RedirectManager.RedirectTo(ReturnUrl); + } + else if (result.IsLockedOut) + { + Logger.LogWarning("User account locked out."); + RedirectManager.RedirectTo("Account/Lockout"); + } + else + { + Logger.LogWarning("Invalid recovery code entered for user with ID '{UserId}' ", userId); + message = "Error: Invalid recovery code entered."; + } + } + + private sealed class InputModel + { + [Required] + [DataType(DataType.Text)] + [Display(Name = "Recovery Code")] + public string RecoveryCode { get; set; } = ""; + } +} diff --git a/Queueify.Web/Components/Account/Pages/Manage/ChangePassword.razor b/Queueify.Web/Components/Account/Pages/Manage/ChangePassword.razor new file mode 100644 index 0000000..bb2307b --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/Manage/ChangePassword.razor @@ -0,0 +1,109 @@ +@page "/Account/Manage/ChangePassword" + +@using System.ComponentModel.DataAnnotations +@using Microsoft.AspNetCore.Identity +@using Queueify.Web.Data + +@inject UserManager UserManager +@inject SignInManager SignInManager +@inject IdentityRedirectManager RedirectManager +@inject ILogger Logger + +Change password + +

Change password

+ +
+
+ + + +
+ + + +
+
+ + + +
+
+ + + +
+ +
+
+
+ +@code { + private string? message; + private ApplicationUser? user; + private bool hasPassword; + + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + [SupplyParameterFromForm] + private InputModel Input { get; set; } = default!; + + protected override async Task OnInitializedAsync() + { + Input ??= new(); + + user = await UserManager.GetUserAsync(HttpContext.User); + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + return; + } + + hasPassword = await UserManager.HasPasswordAsync(user); + if (!hasPassword) + { + RedirectManager.RedirectTo("Account/Manage/SetPassword"); + } + } + + private async Task OnValidSubmitAsync() + { + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + return; + } + + var changePasswordResult = await UserManager.ChangePasswordAsync(user, Input.OldPassword, Input.NewPassword); + if (!changePasswordResult.Succeeded) + { + message = $"Error: {string.Join(",", changePasswordResult.Errors.Select(error => error.Description))}"; + return; + } + + await SignInManager.RefreshSignInAsync(user); + Logger.LogInformation("User changed their password successfully."); + + RedirectManager.RedirectToCurrentPageWithStatus("Your password has been changed", HttpContext); + } + + private sealed class InputModel + { + [Required] + [DataType(DataType.Password)] + [Display(Name = "Current password")] + public string OldPassword { get; set; } = ""; + + [Required] + [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] + [DataType(DataType.Password)] + [Display(Name = "New password")] + public string NewPassword { get; set; } = ""; + + [DataType(DataType.Password)] + [Display(Name = "Confirm new password")] + [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] + public string ConfirmPassword { get; set; } = ""; + } +} diff --git a/Queueify.Web/Components/Account/Pages/Manage/DeletePersonalData.razor b/Queueify.Web/Components/Account/Pages/Manage/DeletePersonalData.razor new file mode 100644 index 0000000..33985b2 --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/Manage/DeletePersonalData.razor @@ -0,0 +1,97 @@ +@page "/Account/Manage/DeletePersonalData" + +@using System.ComponentModel.DataAnnotations +@using Microsoft.AspNetCore.Identity +@using Queueify.Web.Data + +@inject UserManager UserManager +@inject SignInManager SignInManager +@inject IdentityRedirectManager RedirectManager +@inject ILogger Logger + +Delete Personal Data + + + +

Delete Personal Data

+ + + +
+ + + + @if (requirePassword) + { +
+ + + +
+ } + +
+
+ +@code { + private string? message; + private ApplicationUser? user; + private bool requirePassword; + + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + [SupplyParameterFromForm] + private InputModel Input { get; set; } = default!; + + protected override async Task OnInitializedAsync() + { + Input ??= new(); + + user = await UserManager.GetUserAsync(HttpContext.User); + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + return; + } + requirePassword = await UserManager.HasPasswordAsync(user); + } + + private async Task OnValidSubmitAsync() + { + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + return; + } + + if (requirePassword && !await UserManager.CheckPasswordAsync(user, Input.Password)) + { + message = "Error: Incorrect password."; + return; + } + + var result = await UserManager.DeleteAsync(user); + if (!result.Succeeded) + { + throw new InvalidOperationException("Unexpected error occurred deleting user."); + } + + await SignInManager.SignOutAsync(); + + var userId = await UserManager.GetUserIdAsync(user); + Logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId); + + RedirectManager.RedirectToCurrentPage(); + } + + private sealed class InputModel + { + [DataType(DataType.Password)] + public string Password { get; set; } = ""; + } +} diff --git a/Queueify.Web/Components/Account/Pages/Manage/Disable2fa.razor b/Queueify.Web/Components/Account/Pages/Manage/Disable2fa.razor new file mode 100644 index 0000000..c4133e7 --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/Manage/Disable2fa.razor @@ -0,0 +1,74 @@ +@page "/Account/Manage/Disable2fa" + +@using Microsoft.AspNetCore.Identity +@using Queueify.Web.Data + +@inject UserManager UserManager +@inject IdentityRedirectManager RedirectManager +@inject ILogger Logger + +Disable two-factor authentication (2FA) + + +

Disable two-factor authentication (2FA)

+ + + +
+
+ + + +
+ +@code { + private ApplicationUser? user; + + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + protected override async Task OnInitializedAsync() + { + user = await UserManager.GetUserAsync(HttpContext.User); + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + return; + } + + if (HttpMethods.IsGet(HttpContext.Request.Method) && !await UserManager.GetTwoFactorEnabledAsync(user)) + { + throw new InvalidOperationException("Cannot disable 2FA for user as it's not currently enabled."); + } + } + + private async Task OnSubmitAsync() + { + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + return; + } + + var disable2faResult = await UserManager.SetTwoFactorEnabledAsync(user, false); + if (!disable2faResult.Succeeded) + { + throw new InvalidOperationException("Unexpected error occurred disabling 2FA."); + } + + var userId = await UserManager.GetUserIdAsync(user); + Logger.LogInformation("User with ID '{UserId}' has disabled 2fa.", userId); + RedirectManager.RedirectToWithStatus( + "Account/Manage/TwoFactorAuthentication", + "2fa has been disabled. You can reenable 2fa when you setup an authenticator app", + HttpContext); + } +} diff --git a/Queueify.Web/Components/Account/Pages/Manage/Email.razor b/Queueify.Web/Components/Account/Pages/Manage/Email.razor new file mode 100644 index 0000000..1935036 --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/Manage/Email.razor @@ -0,0 +1,143 @@ +@page "/Account/Manage/Email" + +@using System.ComponentModel.DataAnnotations +@using System.Text +@using System.Text.Encodings.Web +@using Microsoft.AspNetCore.Identity +@using Microsoft.AspNetCore.WebUtilities +@using Queueify.Web.Data + +@inject UserManager UserManager +@inject IEmailSender EmailSender +@inject NavigationManager NavigationManager +@inject IdentityRedirectManager RedirectManager + +Manage email + +

Manage email

+ + +
+
+
+ + + + + + @if (isEmailConfirmed) + { +
+ +
+ ✓ +
+ +
+ } + else + { +
+ + + +
+ } +
+ + + +
+ +
+
+
+ +@code { + private string? message; + private ApplicationUser? user; + private string? email; + private bool isEmailConfirmed; + + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + [SupplyParameterFromForm(FormName = "change-email")] + private InputModel Input { get; set; } = default!; + + protected override async Task OnInitializedAsync() + { + Input ??= new(); + + user = await UserManager.GetUserAsync(HttpContext.User); + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + return; + } + + email = await UserManager.GetEmailAsync(user); + isEmailConfirmed = await UserManager.IsEmailConfirmedAsync(user); + + Input.NewEmail ??= email; + } + + private async Task OnValidSubmitAsync() + { + if (Input.NewEmail is null || Input.NewEmail == email) + { + message = "Your email is unchanged."; + return; + } + + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + return; + } + + var userId = await UserManager.GetUserIdAsync(user); + var code = await UserManager.GenerateChangeEmailTokenAsync(user, Input.NewEmail); + code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); + var callbackUrl = NavigationManager.GetUriWithQueryParameters( + NavigationManager.ToAbsoluteUri("Account/ConfirmEmailChange").AbsoluteUri, + new Dictionary { ["userId"] = userId, ["email"] = Input.NewEmail, ["code"] = code }); + + await EmailSender.SendConfirmationLinkAsync(user, Input.NewEmail, HtmlEncoder.Default.Encode(callbackUrl)); + + message = "Confirmation link to change email sent. Please check your email."; + } + + private async Task OnSendEmailVerificationAsync() + { + if (email is null) + { + return; + } + + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + return; + } + + var userId = await UserManager.GetUserIdAsync(user); + var code = await UserManager.GenerateEmailConfirmationTokenAsync(user); + code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); + var callbackUrl = NavigationManager.GetUriWithQueryParameters( + NavigationManager.ToAbsoluteUri("Account/ConfirmEmail").AbsoluteUri, + new Dictionary { ["userId"] = userId, ["code"] = code }); + + await EmailSender.SendConfirmationLinkAsync(user, email, HtmlEncoder.Default.Encode(callbackUrl)); + + message = "Verification email sent. Please check your email."; + } + + private sealed class InputModel + { + [Required] + [EmailAddress] + [Display(Name = "New email")] + public string? NewEmail { get; set; } + } +} diff --git a/Queueify.Web/Components/Account/Pages/Manage/EnableAuthenticator.razor b/Queueify.Web/Components/Account/Pages/Manage/EnableAuthenticator.razor new file mode 100644 index 0000000..e20ed12 --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/Manage/EnableAuthenticator.razor @@ -0,0 +1,184 @@ +@page "/Account/Manage/EnableAuthenticator" + +@using System.ComponentModel.DataAnnotations +@using System.Globalization +@using System.Text +@using System.Text.Encodings.Web +@using Microsoft.AspNetCore.Identity +@using Queueify.Web.Data + +@inject UserManager UserManager +@inject UrlEncoder UrlEncoder +@inject IdentityRedirectManager RedirectManager +@inject ILogger Logger + +Configure authenticator app + +@if (recoveryCodes is not null) +{ + +} +else +{ + +

Configure authenticator app

+
+

To use an authenticator app go through the following steps:

+
    +
  1. +

    + Download a two-factor authenticator app like Microsoft Authenticator for + Android and + iOS or + Google Authenticator for + Android and + iOS. +

    +
  2. +
  3. +

    Scan the QR Code or enter this key @sharedKey into your two factor authenticator app. Spaces and casing do not matter.

    + +
    +
    +
  4. +
  5. +

    + Once you have scanned the QR code or input the key above, your two factor authentication app will provide you + with a unique code. Enter the code in the confirmation box below. +

    +
    +
    + + +
    + + + +
    + + +
    +
    +
    +
  6. +
+
+} + +@code { + private const string AuthenticatorUriFormat = "otpauth://totp/{0}:{1}?secret={2}&issuer={0}&digits=6"; + + private string? message; + private ApplicationUser? user; + private string? sharedKey; + private string? authenticatorUri; + private IEnumerable? recoveryCodes; + + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + [SupplyParameterFromForm] + private InputModel Input { get; set; } = default!; + + protected override async Task OnInitializedAsync() + { + Input ??= new(); + + user = await UserManager.GetUserAsync(HttpContext.User); + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + return; + } + + await LoadSharedKeyAndQrCodeUriAsync(user); + } + + private async Task OnValidSubmitAsync() + { + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + return; + } + + // Strip spaces and hyphens + var verificationCode = Input.Code.Replace(" ", string.Empty).Replace("-", string.Empty); + + var is2faTokenValid = await UserManager.VerifyTwoFactorTokenAsync( + user, UserManager.Options.Tokens.AuthenticatorTokenProvider, verificationCode); + + if (!is2faTokenValid) + { + message = "Error: Verification code is invalid."; + return; + } + + await UserManager.SetTwoFactorEnabledAsync(user, true); + var userId = await UserManager.GetUserIdAsync(user); + Logger.LogInformation("User with ID '{UserId}' has enabled 2FA with an authenticator app.", userId); + + message = "Your authenticator app has been verified."; + + if (await UserManager.CountRecoveryCodesAsync(user) == 0) + { + recoveryCodes = await UserManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10); + } + else + { + RedirectManager.RedirectToWithStatus("Account/Manage/TwoFactorAuthentication", message, HttpContext); + } + } + + private async ValueTask LoadSharedKeyAndQrCodeUriAsync(ApplicationUser user) + { + // Load the authenticator key & QR code URI to display on the form + var unformattedKey = await UserManager.GetAuthenticatorKeyAsync(user); + if (string.IsNullOrEmpty(unformattedKey)) + { + await UserManager.ResetAuthenticatorKeyAsync(user); + unformattedKey = await UserManager.GetAuthenticatorKeyAsync(user); + } + + sharedKey = FormatKey(unformattedKey!); + + var email = await UserManager.GetEmailAsync(user); + authenticatorUri = GenerateQrCodeUri(email!, unformattedKey!); + } + + private string FormatKey(string unformattedKey) + { + var result = new StringBuilder(); + int currentPosition = 0; + while (currentPosition + 4 < unformattedKey.Length) + { + result.Append(unformattedKey.AsSpan(currentPosition, 4)).Append(' '); + currentPosition += 4; + } + if (currentPosition < unformattedKey.Length) + { + result.Append(unformattedKey.AsSpan(currentPosition)); + } + + return result.ToString().ToLowerInvariant(); + } + + private string GenerateQrCodeUri(string email, string unformattedKey) + { + return string.Format( + CultureInfo.InvariantCulture, + AuthenticatorUriFormat, + UrlEncoder.Encode("Microsoft.AspNetCore.Identity.UI"), + UrlEncoder.Encode(email), + unformattedKey); + } + + private sealed class InputModel + { + [Required] + [StringLength(7, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] + [DataType(DataType.Text)] + [Display(Name = "Verification Code")] + public string Code { get; set; } = ""; + } +} diff --git a/Queueify.Web/Components/Account/Pages/Manage/ExternalLogins.razor b/Queueify.Web/Components/Account/Pages/Manage/ExternalLogins.razor new file mode 100644 index 0000000..8c20ea1 --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/Manage/ExternalLogins.razor @@ -0,0 +1,162 @@ +@page "/Account/Manage/ExternalLogins" + +@using Microsoft.AspNetCore.Authentication +@using Microsoft.AspNetCore.Identity +@using Queueify.Web.Data + +@inject UserManager UserManager +@inject SignInManager SignInManager +@inject IUserStore UserStore +@inject IdentityRedirectManager RedirectManager + +Manage your external logins + + +@if (currentLogins?.Count > 0) +{ +

Registered Logins

+ + + @foreach (var login in currentLogins) + { + + + + + } + +
@login.ProviderDisplayName + @if (showRemoveButton) + { +
+ +
+ + + +
+ + } + else + { + @:   + } +
+} +@if (otherLogins?.Count > 0) +{ +

Add another service to log in.

+
+
+ +
+

+ @foreach (var provider in otherLogins) + { + + } +

+
+ +} + +@code { + public const string LinkLoginCallbackAction = "LinkLoginCallback"; + + private ApplicationUser? user; + private IList? currentLogins; + private IList? otherLogins; + private bool showRemoveButton; + + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + [SupplyParameterFromForm] + private string? LoginProvider { get; set; } + + [SupplyParameterFromForm] + private string? ProviderKey { get; set; } + + [SupplyParameterFromQuery] + private string? Action { get; set; } + + protected override async Task OnInitializedAsync() + { + user = await UserManager.GetUserAsync(HttpContext.User); + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + return; + } + + currentLogins = await UserManager.GetLoginsAsync(user); + otherLogins = (await SignInManager.GetExternalAuthenticationSchemesAsync()) + .Where(auth => currentLogins.All(ul => auth.Name != ul.LoginProvider)) + .ToList(); + + string? passwordHash = null; + if (UserStore is IUserPasswordStore userPasswordStore) + { + passwordHash = await userPasswordStore.GetPasswordHashAsync(user, HttpContext.RequestAborted); + } + + showRemoveButton = passwordHash is not null || currentLogins.Count > 1; + + if (HttpMethods.IsGet(HttpContext.Request.Method) && Action == LinkLoginCallbackAction) + { + await OnGetLinkLoginCallbackAsync(); + } + } + + private async Task OnSubmitAsync() + { + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + return; + } + + var result = await UserManager.RemoveLoginAsync(user, LoginProvider!, ProviderKey!); + if (!result.Succeeded) + { + RedirectManager.RedirectToCurrentPageWithStatus("Error: The external login was not removed.", HttpContext); + } + else + { + await SignInManager.RefreshSignInAsync(user); + RedirectManager.RedirectToCurrentPageWithStatus("The external login was removed.", HttpContext); + } + } + + private async Task OnGetLinkLoginCallbackAsync() + { + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + return; + } + + var userId = await UserManager.GetUserIdAsync(user); + var info = await SignInManager.GetExternalLoginInfoAsync(userId); + if (info is null) + { + RedirectManager.RedirectToCurrentPageWithStatus("Error: Could not load external login info.", HttpContext); + return; + } + + var result = await UserManager.AddLoginAsync(user, info); + if (result.Succeeded) + { + // Clear the existing external cookie to ensure a clean login process + await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); + + RedirectManager.RedirectToCurrentPageWithStatus("The external login was added.", HttpContext); + } + else + { + RedirectManager.RedirectToCurrentPageWithStatus("Error: The external login was not added. External logins can only be associated with one account.", HttpContext); + } + } +} diff --git a/Queueify.Web/Components/Account/Pages/Manage/GenerateRecoveryCodes.razor b/Queueify.Web/Components/Account/Pages/Manage/GenerateRecoveryCodes.razor new file mode 100644 index 0000000..90f3d0e --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/Manage/GenerateRecoveryCodes.razor @@ -0,0 +1,78 @@ +@page "/Account/Manage/GenerateRecoveryCodes" + +@using Microsoft.AspNetCore.Identity +@using Queueify.Web.Data + +@inject UserManager UserManager +@inject IdentityRedirectManager RedirectManager +@inject ILogger Logger + +Generate two-factor authentication (2FA) recovery codes + +@if (recoveryCodes is not null) +{ + +} +else +{ +

Generate two-factor authentication (2FA) recovery codes

+ +
+
+ + + +
+} + +@code { + private string? message; + private ApplicationUser? user; + private IEnumerable? recoveryCodes; + + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + protected override async Task OnInitializedAsync() + { + user = await UserManager.GetUserAsync(HttpContext.User); + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + return; + } + + var isTwoFactorEnabled = await UserManager.GetTwoFactorEnabledAsync(user); + if (!isTwoFactorEnabled) + { + throw new InvalidOperationException("Cannot generate recovery codes for user because they do not have 2FA enabled."); + } + } + + private async Task OnSubmitAsync() + { + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + return; + } + + var userId = await UserManager.GetUserIdAsync(user); + recoveryCodes = await UserManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10); + message = "You have generated new recovery codes."; + + Logger.LogInformation("User with ID '{UserId}' has generated new 2FA recovery codes.", userId); + } +} diff --git a/Queueify.Web/Components/Account/Pages/Manage/Index.razor b/Queueify.Web/Components/Account/Pages/Manage/Index.razor new file mode 100644 index 0000000..24bd2fc --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/Manage/Index.razor @@ -0,0 +1,91 @@ +@page "/Account/Manage" + +@using System.ComponentModel.DataAnnotations +@using Microsoft.AspNetCore.Identity +@using Queueify.Web.Data + +@inject UserManager UserManager +@inject SignInManager SignInManager +@inject IdentityRedirectManager RedirectManager + +Profile + +

Profile

+ + +
+
+ + + +
+ + +
+
+ + + +
+ +
+
+
+ +@code { + private ApplicationUser? user; + private string? username; + private string? phoneNumber; + + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + [SupplyParameterFromForm] + private InputModel Input { get; set; } = default!; + + protected override async Task OnInitializedAsync() + { + Input ??= new(); + + user = await UserManager.GetUserAsync(HttpContext.User); + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + return; + } + + username = await UserManager.GetUserNameAsync(user); + phoneNumber = await UserManager.GetPhoneNumberAsync(user); + + Input.PhoneNumber ??= phoneNumber; + } + + private async Task OnValidSubmitAsync() + { + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + return; + } + + if (Input.PhoneNumber != phoneNumber) + { + var setPhoneResult = await UserManager.SetPhoneNumberAsync(user, Input.PhoneNumber); + if (!setPhoneResult.Succeeded) + { + RedirectManager.RedirectToCurrentPageWithStatus("Error: Failed to set phone number.", HttpContext); + return; + } + } + + await SignInManager.RefreshSignInAsync(user); + RedirectManager.RedirectToCurrentPageWithStatus("Your profile has been updated", HttpContext); + } + + private sealed class InputModel + { + [Phone] + [Display(Name = "Phone number")] + public string? PhoneNumber { get; set; } + } +} diff --git a/Queueify.Web/Components/Account/Pages/Manage/Passkeys.razor b/Queueify.Web/Components/Account/Pages/Manage/Passkeys.razor new file mode 100644 index 0000000..e626ac7 --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/Manage/Passkeys.razor @@ -0,0 +1,182 @@ +@page "/Account/Manage/Passkeys" + +@using Queueify.Web.Data +@using Microsoft.AspNetCore.Identity +@using System.ComponentModel.DataAnnotations +@using System.Buffers.Text + +@inject UserManager UserManager +@inject SignInManager SignInManager +@inject IdentityRedirectManager RedirectManager + +Manage your passkeys + +

Manage your passkeys

+ + + +@if (currentPasskeys is { Count: > 0 }) +{ + + + @foreach (var passkey in currentPasskeys) + { + + + + + } + +
@(passkey.Name ?? "Unnamed passkey") + @{ + var credentialId = Base64Url.EncodeToString(passkey.CredentialId); + } +
+ +
+ + + +
+ +
+} +else +{ +

No passkeys are registered.

+} + +
+ + @if (currentPasskeys is { Count: >= MaxPasskeyCount }) + { +

You have reached the maximum number of allowed passkeys. Please delete one before adding a new one.

+ } + else + { + Add a new passkey + } + + + +@code { + private const int MaxPasskeyCount = 100; + + private ApplicationUser? user; + private IList? currentPasskeys; + + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + [SupplyParameterFromForm] + private string? Action { get; set; } + + [SupplyParameterFromForm] + private string? CredentialId { get; set; } + + [SupplyParameterFromForm(FormName = "add-passkey")] + private PasskeyInputModel Input { get; set; } = default!; + + protected override async Task OnInitializedAsync() + { + Input ??= new(); + + user = await UserManager.GetUserAsync(HttpContext.User); + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + return; + } + currentPasskeys = await UserManager.GetPasskeysAsync(user); + } + + private async Task AddPasskey() + { + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + return; + } + + if (!string.IsNullOrEmpty(Input.Error)) + { + RedirectManager.RedirectToCurrentPageWithStatus($"Error: {Input.Error}", HttpContext); + return; + } + + if (string.IsNullOrEmpty(Input.CredentialJson)) + { + RedirectManager.RedirectToCurrentPageWithStatus("Error: The browser did not provide a passkey.", HttpContext); + return; + } + + if (currentPasskeys!.Count >= MaxPasskeyCount) + { + RedirectManager.RedirectToCurrentPageWithStatus($"Error: You have reached the maximum number of allowed passkeys.", HttpContext); + return; + } + + var attestationResult = await SignInManager.PerformPasskeyAttestationAsync(Input.CredentialJson); + if (!attestationResult.Succeeded) + { + RedirectManager.RedirectToCurrentPageWithStatus($"Error: Could not add the passkey: {attestationResult.Failure.Message}", HttpContext); + return; + } + + var addPasskeyResult = await UserManager.AddOrUpdatePasskeyAsync(user, attestationResult.Passkey); + if (!addPasskeyResult.Succeeded) + { + RedirectManager.RedirectToCurrentPageWithStatus("Error: The passkey could not be added to your account.", HttpContext); + return; + } + + // Immediately prompt the user to enter a name for the credential + var credentialIdBase64Url = Base64Url.EncodeToString(attestationResult.Passkey.CredentialId); + RedirectManager.RedirectTo($"Account/Manage/RenamePasskey/{credentialIdBase64Url}"); + } + + private async Task UpdatePasskey() + { + switch (Action) + { + case "rename": + RedirectManager.RedirectTo($"Account/Manage/RenamePasskey/{CredentialId}"); + break; + case "delete": + await DeletePasskey(); + break; + default: + RedirectManager.RedirectToCurrentPageWithStatus($"Error: Unknown action '{Action}'.", HttpContext); + break; + } + } + + private async Task DeletePasskey() + { + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + return; + } + + byte[] credentialId; + try + { + credentialId = Base64Url.DecodeFromChars(CredentialId); + } + catch (FormatException) + { + RedirectManager.RedirectToCurrentPageWithStatus("Error: The specified passkey ID had an invalid format.", HttpContext); + return; + } + + var result = await UserManager.RemovePasskeyAsync(user, credentialId); + if (!result.Succeeded) + { + RedirectManager.RedirectToCurrentPageWithStatus("Error: The passkey could not be deleted.", HttpContext); + return; + } + + RedirectManager.RedirectToCurrentPageWithStatus("Passkey deleted successfully.", HttpContext); + } +} diff --git a/Queueify.Web/Components/Account/Pages/Manage/PersonalData.razor b/Queueify.Web/Components/Account/Pages/Manage/PersonalData.razor new file mode 100644 index 0000000..653a0db --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/Manage/PersonalData.razor @@ -0,0 +1,42 @@ +@page "/Account/Manage/PersonalData" + +@using Microsoft.AspNetCore.Identity +@using Queueify.Web.Data + +@inject UserManager UserManager +@inject IdentityRedirectManager RedirectManager + +Personal Data + + +

Personal Data

+ +
+
+

Your account contains personal data that you have given us. This page allows you to download or delete that data.

+

+ Deleting this data will permanently remove your account, and this cannot be recovered. +

+
+ + + +

+ Delete +

+
+
+ +@code { + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + protected override async Task OnInitializedAsync() + { + var user = await UserManager.GetUserAsync(HttpContext.User); + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + } + } +} diff --git a/Queueify.Web/Components/Account/Pages/Manage/RenamePasskey.razor b/Queueify.Web/Components/Account/Pages/Manage/RenamePasskey.razor new file mode 100644 index 0000000..c7ecfd6 --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/Manage/RenamePasskey.razor @@ -0,0 +1,95 @@ +@page "/Account/Manage/RenamePasskey/{Id}" + +@using Queueify.Web.Data +@using System.ComponentModel.DataAnnotations +@using Microsoft.AspNetCore.Identity +@using System.Buffers.Text + +@inject UserManager UserManager +@inject IdentityRedirectManager RedirectManager + + + + @if (passkey?.Name is { } name) + { +

Enter a new name for your "@name" passkey

+ } + else + { +

Enter a name for your passkey

+ } +
+ +
+ + + +
+
+ +
+
+ +@code { + private ApplicationUser? user; + private UserPasskeyInfo? passkey; + + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + [Parameter] + public string? Id { get; set; } + + [SupplyParameterFromForm] + private InputModel Input { get; set; } = default!; + + protected override async Task OnInitializedAsync() + { + Input ??= new(); + + user = (await UserManager.GetUserAsync(HttpContext.User))!; + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + return; + } + + byte[] credentialId; + try + { + credentialId = Base64Url.DecodeFromChars(Id); + } + catch (FormatException) + { + RedirectManager.RedirectToWithStatus("Account/Manage/Passkeys", "Error: The specified passkey ID had an invalid format.", HttpContext); + return; + } + + passkey = await UserManager.GetPasskeyAsync(user, credentialId); + if (passkey is null) + { + RedirectManager.RedirectToWithStatus("Account/Manage/Passkeys", "Error: The specified passkey could not be found.", HttpContext); + return; + } + } + + private async Task Rename() + { + passkey!.Name = Input.Name; + var result = await UserManager.AddOrUpdatePasskeyAsync(user!, passkey); + if (!result.Succeeded) + { + RedirectManager.RedirectToWithStatus("Account/Manage/Passkeys", "Error: The passkey could not be updated.", HttpContext); + return; + } + + RedirectManager.RedirectToWithStatus("Account/Manage/Passkeys", "Passkey updated successfully.", HttpContext); + } + + private sealed class InputModel + { + [Required] + [StringLength(200, ErrorMessage = "Passkey names must be no longer than {1} characters.")] + public string Name { get; set; } = ""; + } +} diff --git a/Queueify.Web/Components/Account/Pages/Manage/ResetAuthenticator.razor b/Queueify.Web/Components/Account/Pages/Manage/ResetAuthenticator.razor new file mode 100644 index 0000000..b876675 --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/Manage/ResetAuthenticator.razor @@ -0,0 +1,57 @@ +@page "/Account/Manage/ResetAuthenticator" + +@using Microsoft.AspNetCore.Identity +@using Queueify.Web.Data + +@inject UserManager UserManager +@inject SignInManager SignInManager +@inject IdentityRedirectManager RedirectManager +@inject ILogger Logger + +Reset authenticator key + + +

Reset authenticator key

+ +
+
+ + + +
+ +@code { + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + private async Task OnSubmitAsync() + { + var user = await UserManager.GetUserAsync(HttpContext.User); + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + return; + } + + await UserManager.SetTwoFactorEnabledAsync(user, false); + await UserManager.ResetAuthenticatorKeyAsync(user); + var userId = await UserManager.GetUserIdAsync(user); + Logger.LogInformation("User with ID '{UserId}' has reset their authentication app key.", userId); + + await SignInManager.RefreshSignInAsync(user); + + RedirectManager.RedirectToWithStatus( + "Account/Manage/EnableAuthenticator", + "Your authenticator app key has been reset, you will need to configure your authenticator app using the new key.", + HttpContext); + } +} diff --git a/Queueify.Web/Components/Account/Pages/Manage/SetPassword.razor b/Queueify.Web/Components/Account/Pages/Manage/SetPassword.razor new file mode 100644 index 0000000..5e837dd --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/Manage/SetPassword.razor @@ -0,0 +1,99 @@ +@page "/Account/Manage/SetPassword" + +@using System.ComponentModel.DataAnnotations +@using Microsoft.AspNetCore.Identity +@using Queueify.Web.Data + +@inject UserManager UserManager +@inject SignInManager SignInManager +@inject IdentityRedirectManager RedirectManager + +Set password + +

Set your password

+ +

+ You do not have a local username/password for this site. Add a local + account so you can log in without an external login. +

+
+
+ + + +
+ + + +
+
+ + + +
+ +
+
+
+ +@code { + private string? message; + private ApplicationUser? user; + + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + [SupplyParameterFromForm] + private InputModel Input { get; set; } = default!; + + protected override async Task OnInitializedAsync() + { + Input ??= new(); + + user = await UserManager.GetUserAsync(HttpContext.User); + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + return; + } + + var hasPassword = await UserManager.HasPasswordAsync(user); + if (hasPassword) + { + RedirectManager.RedirectTo("Account/Manage/ChangePassword"); + } + } + + private async Task OnValidSubmitAsync() + { + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + return; + } + + var addPasswordResult = await UserManager.AddPasswordAsync(user, Input.NewPassword!); + if (!addPasswordResult.Succeeded) + { + message = $"Error: {string.Join(",", addPasswordResult.Errors.Select(error => error.Description))}"; + return; + } + + await SignInManager.RefreshSignInAsync(user); + RedirectManager.RedirectToCurrentPageWithStatus("Your password has been set.", HttpContext); + } + + private sealed class InputModel + { + [Required] + [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] + [DataType(DataType.Password)] + [Display(Name = "New password")] + public string? NewPassword { get; set; } + + [DataType(DataType.Password)] + [Display(Name = "Confirm new password")] + [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] + public string? ConfirmPassword { get; set; } + } +} diff --git a/Queueify.Web/Components/Account/Pages/Manage/TwoFactorAuthentication.razor b/Queueify.Web/Components/Account/Pages/Manage/TwoFactorAuthentication.razor new file mode 100644 index 0000000..291e96c --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/Manage/TwoFactorAuthentication.razor @@ -0,0 +1,106 @@ +@page "/Account/Manage/TwoFactorAuthentication" + +@using Microsoft.AspNetCore.Http.Features +@using Microsoft.AspNetCore.Identity +@using Queueify.Web.Data + +@inject UserManager UserManager +@inject SignInManager SignInManager +@inject IdentityRedirectManager RedirectManager + +Two-factor authentication (2FA) + + +

Two-factor authentication (2FA)

+@if (canTrack) +{ + if (is2faEnabled) + { + if (recoveryCodesLeft == 0) + { +
+ You have no recovery codes left. +

You must generate a new set of recovery codes before you can log in with a recovery code.

+
+ } + else if (recoveryCodesLeft == 1) + { +
+ You have 1 recovery code left. +

You can generate a new set of recovery codes.

+
+ } + else if (recoveryCodesLeft <= 3) + { +
+ You have @recoveryCodesLeft recovery codes left. +

You should generate a new set of recovery codes.

+
+ } + + if (isMachineRemembered) + { +
+ + + + } + + Disable 2FA + Reset recovery codes + } + +

Authenticator app

+ @if (!hasAuthenticator) + { + Add authenticator app + } + else + { + Set up authenticator app + Reset authenticator app + } +} +else +{ +
+ Privacy and cookie policy have not been accepted. +

You must accept the policy before you can enable two factor authentication.

+
+} + +@code { + private bool canTrack; + private bool hasAuthenticator; + private int recoveryCodesLeft; + private bool is2faEnabled; + private bool isMachineRemembered; + + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + protected override async Task OnInitializedAsync() + { + var user = await UserManager.GetUserAsync(HttpContext.User); + if (user is null) + { + RedirectManager.RedirectToInvalidUser(UserManager, HttpContext); + return; + } + + canTrack = HttpContext.Features.Get()?.CanTrack ?? true; + hasAuthenticator = await UserManager.GetAuthenticatorKeyAsync(user) is not null; + is2faEnabled = await UserManager.GetTwoFactorEnabledAsync(user); + isMachineRemembered = await SignInManager.IsTwoFactorClientRememberedAsync(user); + recoveryCodesLeft = await UserManager.CountRecoveryCodesAsync(user); + } + + private async Task OnSubmitForgetBrowserAsync() + { + await SignInManager.ForgetTwoFactorClientAsync(); + + RedirectManager.RedirectToCurrentPageWithStatus( + "The current browser has been forgotten. When you login again from this browser you will be prompted for your 2fa code.", + HttpContext); + } +} diff --git a/Queueify.Web/Components/Account/Pages/Manage/_Imports.razor b/Queueify.Web/Components/Account/Pages/Manage/_Imports.razor new file mode 100644 index 0000000..ada5bb0 --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/Manage/_Imports.razor @@ -0,0 +1,2 @@ +@layout ManageLayout +@attribute [Microsoft.AspNetCore.Authorization.Authorize] diff --git a/Queueify.Web/Components/Account/Pages/Register.razor b/Queueify.Web/Components/Account/Pages/Register.razor new file mode 100644 index 0000000..2eea071 --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/Register.razor @@ -0,0 +1,152 @@ +@page "/Account/Register" + +@using System.ComponentModel.DataAnnotations +@using System.Text +@using System.Text.Encodings.Web +@using Microsoft.AspNetCore.Identity +@using Microsoft.AspNetCore.WebUtilities +@using Queueify.Web.Data + +@inject UserManager UserManager +@inject IUserStore UserStore +@inject SignInManager SignInManager +@inject IEmailSender EmailSender +@inject ILogger Logger +@inject NavigationManager NavigationManager +@inject IdentityRedirectManager RedirectManager + +Register + +

Register

+ +
+
+ + + +

Create a new account.

+
+ +
+ + + +
+
+ + + +
+
+ + + +
+ +
+
+
+
+

Use another service to register.

+
+ +
+
+
+ +@code { + private IEnumerable? identityErrors; + + [SupplyParameterFromForm] + private InputModel Input { get; set; } = default!; + + [SupplyParameterFromQuery] + private string? ReturnUrl { get; set; } + + private string? Message => identityErrors is null ? null : $"Error: {string.Join(", ", identityErrors.Select(error => error.Description))}"; + + protected override void OnInitialized() + { + Input ??= new(); + } + + public async Task RegisterUser(EditContext editContext) + { + var user = CreateUser(); + + await UserStore.SetUserNameAsync(user, Input.Email, CancellationToken.None); + var emailStore = GetEmailStore(); + await emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None); + var result = await UserManager.CreateAsync(user, Input.Password); + + if (!result.Succeeded) + { + identityErrors = result.Errors; + return; + } + + Logger.LogInformation("User created a new account with password."); + + var userId = await UserManager.GetUserIdAsync(user); + var code = await UserManager.GenerateEmailConfirmationTokenAsync(user); + code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); + var callbackUrl = NavigationManager.GetUriWithQueryParameters( + NavigationManager.ToAbsoluteUri("Account/ConfirmEmail").AbsoluteUri, + new Dictionary { ["userId"] = userId, ["code"] = code, ["returnUrl"] = ReturnUrl }); + + await EmailSender.SendConfirmationLinkAsync(user, Input.Email, HtmlEncoder.Default.Encode(callbackUrl)); + + if (UserManager.Options.SignIn.RequireConfirmedAccount) + { + RedirectManager.RedirectTo( + "Account/RegisterConfirmation", + new() { ["email"] = Input.Email, ["returnUrl"] = ReturnUrl }); + } + else + { + await SignInManager.SignInAsync(user, isPersistent: false); + RedirectManager.RedirectTo(ReturnUrl); + } + } + + private ApplicationUser CreateUser() + { + try + { + return Activator.CreateInstance(); + } + catch + { + throw new InvalidOperationException($"Can't create an instance of '{nameof(ApplicationUser)}'. " + + $"Ensure that '{nameof(ApplicationUser)}' is not an abstract class and has a parameterless constructor."); + } + } + + private IUserEmailStore GetEmailStore() + { + if (!UserManager.SupportsUserEmail) + { + throw new NotSupportedException("The default UI requires a user store with email support."); + } + return (IUserEmailStore)UserStore; + } + + private sealed class InputModel + { + [Required] + [EmailAddress] + [Display(Name = "Email")] + public string Email { get; set; } = ""; + + [Required] + [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] + [DataType(DataType.Password)] + [Display(Name = "Password")] + public string Password { get; set; } = ""; + + [DataType(DataType.Password)] + [Display(Name = "Confirm password")] + [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] + public string ConfirmPassword { get; set; } = ""; + } +} diff --git a/Queueify.Web/Components/Account/Pages/RegisterConfirmation.razor b/Queueify.Web/Components/Account/Pages/RegisterConfirmation.razor new file mode 100644 index 0000000..46b7be3 --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/RegisterConfirmation.razor @@ -0,0 +1,69 @@ +@page "/Account/RegisterConfirmation" + +@using System.Text +@using Microsoft.AspNetCore.Identity +@using Microsoft.AspNetCore.WebUtilities +@using Queueify.Web.Data + +@inject UserManager UserManager +@inject IEmailSender EmailSender +@inject NavigationManager NavigationManager +@inject IdentityRedirectManager RedirectManager + +Register confirmation + +

Register confirmation

+ + + +@if (emailConfirmationLink is not null) +{ +

+ This app does not currently have a real email sender registered, see these docs for how to configure a real email sender. + Normally this would be emailed: Click here to confirm your account +

+} +else +{ +

Please check your email to confirm your account.

+} + +@code { + private string? emailConfirmationLink; + private string? statusMessage; + + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + [SupplyParameterFromQuery] + private string? Email { get; set; } + + [SupplyParameterFromQuery] + private string? ReturnUrl { get; set; } + + protected override async Task OnInitializedAsync() + { + if (Email is null) + { + RedirectManager.RedirectTo(""); + return; + } + + var user = await UserManager.FindByEmailAsync(Email); + if (user is null) + { + HttpContext.Response.StatusCode = StatusCodes.Status404NotFound; + statusMessage = "Error finding user for unspecified email"; + } + else if (EmailSender is IdentityNoOpEmailSender) + { + // Once you add a real email sender, you should remove this code that lets you confirm the account + var userId = await UserManager.GetUserIdAsync(user); + var code = await UserManager.GenerateEmailConfirmationTokenAsync(user); + code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); + emailConfirmationLink = NavigationManager.GetUriWithQueryParameters( + NavigationManager.ToAbsoluteUri("Account/ConfirmEmail").AbsoluteUri, + new Dictionary { ["userId"] = userId, ["code"] = code, ["returnUrl"] = ReturnUrl }); + } + } +} diff --git a/Queueify.Web/Components/Account/Pages/ResendEmailConfirmation.razor b/Queueify.Web/Components/Account/Pages/ResendEmailConfirmation.razor new file mode 100644 index 0000000..10d16a0 --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/ResendEmailConfirmation.razor @@ -0,0 +1,73 @@ +@page "/Account/ResendEmailConfirmation" + +@using System.ComponentModel.DataAnnotations +@using System.Text +@using System.Text.Encodings.Web +@using Microsoft.AspNetCore.Identity +@using Microsoft.AspNetCore.WebUtilities +@using Queueify.Web.Data + +@inject UserManager UserManager +@inject IEmailSender EmailSender +@inject NavigationManager NavigationManager +@inject IdentityRedirectManager RedirectManager + +Resend email confirmation + +

Resend email confirmation

+

Enter your email.

+
+ +
+
+ + + +
+ + + +
+ +
+
+
+ +@code { + private string? message; + + [SupplyParameterFromForm] + private InputModel Input { get; set; } = default!; + + protected override void OnInitialized() + { + Input ??= new(); + } + + private async Task OnValidSubmitAsync() + { + var user = await UserManager.FindByEmailAsync(Input.Email!); + if (user is null) + { + message = "Verification email sent. Please check your email."; + return; + } + + var userId = await UserManager.GetUserIdAsync(user); + var code = await UserManager.GenerateEmailConfirmationTokenAsync(user); + code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); + var callbackUrl = NavigationManager.GetUriWithQueryParameters( + NavigationManager.ToAbsoluteUri("Account/ConfirmEmail").AbsoluteUri, + new Dictionary { ["userId"] = userId, ["code"] = code }); + await EmailSender.SendConfirmationLinkAsync(user, Input.Email, HtmlEncoder.Default.Encode(callbackUrl)); + + message = "Verification email sent. Please check your email."; + } + + private sealed class InputModel + { + [Required] + [EmailAddress] + public string Email { get; set; } = ""; + } +} diff --git a/Queueify.Web/Components/Account/Pages/ResetPassword.razor b/Queueify.Web/Components/Account/Pages/ResetPassword.razor new file mode 100644 index 0000000..668d867 --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/ResetPassword.razor @@ -0,0 +1,108 @@ +@page "/Account/ResetPassword" + +@using System.ComponentModel.DataAnnotations +@using System.Text +@using Microsoft.AspNetCore.Identity +@using Microsoft.AspNetCore.WebUtilities +@using Queueify.Web.Data + +@inject IdentityRedirectManager RedirectManager +@inject UserManager UserManager + +Reset password + +

Reset password

+

Reset your password.

+
+
+
+ + + + + + +
+ + + +
+
+ + + +
+
+ + + +
+ +
+
+
+ +@code { + private IEnumerable? identityErrors; + + [SupplyParameterFromForm] + private InputModel Input { get; set; } = default!; + + [SupplyParameterFromQuery] + private string? Code { get; set; } + + private string? Message => identityErrors is null ? null : $"Error: {string.Join(", ", identityErrors.Select(error => error.Description))}"; + + protected override void OnInitialized() + { + Input ??= new(); + + if (Code is null) + { + RedirectManager.RedirectTo("Account/InvalidPasswordReset"); + return; + } + + Input.Code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(Code)); + } + + private async Task OnValidSubmitAsync() + { + var user = await UserManager.FindByEmailAsync(Input.Email); + if (user is null) + { + // Don't reveal that the user does not exist + RedirectManager.RedirectTo("Account/ResetPasswordConfirmation"); + return; + } + + var result = await UserManager.ResetPasswordAsync(user, Input.Code, Input.Password); + if (result.Succeeded) + { + RedirectManager.RedirectTo("Account/ResetPasswordConfirmation"); + return; + } + + identityErrors = result.Errors; + } + + private sealed class InputModel + { + [Required] + [EmailAddress] + public string Email { get; set; } = ""; + + [Required] + [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] + [DataType(DataType.Password)] + public string Password { get; set; } = ""; + + [DataType(DataType.Password)] + [Display(Name = "Confirm password")] + [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] + public string ConfirmPassword { get; set; } = ""; + + [Required] + public string Code { get; set; } = ""; + } +} diff --git a/Queueify.Web/Components/Account/Pages/ResetPasswordConfirmation.razor b/Queueify.Web/Components/Account/Pages/ResetPasswordConfirmation.razor new file mode 100644 index 0000000..247e96e --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/ResetPasswordConfirmation.razor @@ -0,0 +1,7 @@ +@page "/Account/ResetPasswordConfirmation" +Reset password confirmation + +

Reset password confirmation

+

+ Your password has been reset. Please click here to log in. +

diff --git a/Queueify.Web/Components/Account/Pages/_Imports.razor b/Queueify.Web/Components/Account/Pages/_Imports.razor new file mode 100644 index 0000000..a29d9fc --- /dev/null +++ b/Queueify.Web/Components/Account/Pages/_Imports.razor @@ -0,0 +1,2 @@ +@using Queueify.Web.Components.Account.Shared +@attribute [ExcludeFromInteractiveRouting] diff --git a/Queueify.Web/Components/Account/PasskeyInputModel.cs b/Queueify.Web/Components/Account/PasskeyInputModel.cs new file mode 100644 index 0000000..ce42b36 --- /dev/null +++ b/Queueify.Web/Components/Account/PasskeyInputModel.cs @@ -0,0 +1,7 @@ +namespace Queueify.Web.Components.Account; + +public class PasskeyInputModel +{ + public string? CredentialJson { get; set; } + public string? Error { get; set; } +} diff --git a/Queueify.Web/Components/Account/PasskeyOperation.cs b/Queueify.Web/Components/Account/PasskeyOperation.cs new file mode 100644 index 0000000..e90cb1f --- /dev/null +++ b/Queueify.Web/Components/Account/PasskeyOperation.cs @@ -0,0 +1,7 @@ +namespace Queueify.Web.Components.Account; + +public enum PasskeyOperation +{ + Create = 0, + Request = 1, +} diff --git a/Queueify.Web/Components/Account/Shared/ExternalLoginPicker.razor b/Queueify.Web/Components/Account/Shared/ExternalLoginPicker.razor new file mode 100644 index 0000000..12b3a8f --- /dev/null +++ b/Queueify.Web/Components/Account/Shared/ExternalLoginPicker.razor @@ -0,0 +1,43 @@ +@using Microsoft.AspNetCore.Authentication +@using Microsoft.AspNetCore.Identity +@using Queueify.Web.Data + +@inject SignInManager SignInManager +@inject IdentityRedirectManager RedirectManager + +@if (externalLogins.Length == 0) +{ +
+

+ There are no external authentication services configured. See this article + about setting up this ASP.NET application to support logging in via external services. +

+
+} +else +{ +
+
+ + +

+ @foreach (var provider in externalLogins) + { + + } +

+
+
+} + +@code { + private AuthenticationScheme[] externalLogins = []; + + [SupplyParameterFromQuery] + private string? ReturnUrl { get; set; } + + protected override async Task OnInitializedAsync() + { + externalLogins = (await SignInManager.GetExternalAuthenticationSchemesAsync()).ToArray(); + } +} diff --git a/Queueify.Web/Components/Account/Shared/ManageLayout.razor b/Queueify.Web/Components/Account/Shared/ManageLayout.razor new file mode 100644 index 0000000..d365218 --- /dev/null +++ b/Queueify.Web/Components/Account/Shared/ManageLayout.razor @@ -0,0 +1,17 @@ +@inherits LayoutComponentBase +@layout Queueify.Web.Components.Layout.MainLayout + +

Manage your account

+ +
+

Change your account settings

+
+
+
+ +
+
+ @Body +
+
+
diff --git a/Queueify.Web/Components/Account/Shared/ManageNavMenu.razor b/Queueify.Web/Components/Account/Shared/ManageNavMenu.razor new file mode 100644 index 0000000..a1043ec --- /dev/null +++ b/Queueify.Web/Components/Account/Shared/ManageNavMenu.razor @@ -0,0 +1,40 @@ +@using Microsoft.AspNetCore.Identity +@using Queueify.Web.Data + +@inject SignInManager SignInManager + + + +@code { + private bool hasExternalLogins; + + protected override async Task OnInitializedAsync() + { + hasExternalLogins = (await SignInManager.GetExternalAuthenticationSchemesAsync()).Any(); + } +} diff --git a/Queueify.Web/Components/Account/Shared/PasskeySubmit.razor b/Queueify.Web/Components/Account/Shared/PasskeySubmit.razor new file mode 100644 index 0000000..9db61ff --- /dev/null +++ b/Queueify.Web/Components/Account/Shared/PasskeySubmit.razor @@ -0,0 +1,40 @@ +@using Microsoft.AspNetCore.Antiforgery +@inject IServiceProvider Services + + + + + +@code { + private AntiforgeryTokenSet? tokens; + + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + [Parameter] + [EditorRequired] + public PasskeyOperation Operation { get; set; } + + [Parameter] + [EditorRequired] + public string Name { get; set; } = default!; + + [Parameter] + public string? EmailName { get; set; } + + [Parameter] + public RenderFragment? ChildContent { get; set; } + + [Parameter(CaptureUnmatchedValues = true)] + public IDictionary? AdditionalAttributes { get; set; } + + protected override void OnInitialized() + { + tokens = Services.GetService()?.GetTokens(HttpContext); + } +} diff --git a/Queueify.Web/Components/Account/Shared/PasskeySubmit.razor.js b/Queueify.Web/Components/Account/Shared/PasskeySubmit.razor.js new file mode 100644 index 0000000..55a83bc --- /dev/null +++ b/Queueify.Web/Components/Account/Shared/PasskeySubmit.razor.js @@ -0,0 +1,123 @@ +const browserSupportsPasskeys = + typeof navigator.credentials !== 'undefined' && + typeof window.PublicKeyCredential !== 'undefined' && + typeof window.PublicKeyCredential.parseCreationOptionsFromJSON === 'function' && + typeof window.PublicKeyCredential.parseRequestOptionsFromJSON === 'function'; + +async function fetchWithErrorHandling(url, options = {}) { + const response = await fetch(url, { + credentials: 'include', + ...options + }); + if (!response.ok) { + const text = await response.text(); + console.error(text); + throw new Error(`The server responded with status ${response.status}.`); + } + return response; +} + +async function createCredential(headers, signal) { + const optionsResponse = await fetchWithErrorHandling('/Account/PasskeyCreationOptions', { + method: 'POST', + headers, + signal, + }); + const optionsJson = await optionsResponse.json(); + const options = PublicKeyCredential.parseCreationOptionsFromJSON(optionsJson); + return await navigator.credentials.create({ publicKey: options, signal }); +} + +async function requestCredential(email, mediation, headers, signal) { + const optionsResponse = await fetchWithErrorHandling(`/Account/PasskeyRequestOptions?username=${email}`, { + method: 'POST', + headers, + signal, + }); + const optionsJson = await optionsResponse.json(); + const options = PublicKeyCredential.parseRequestOptionsFromJSON(optionsJson); + return await navigator.credentials.get({ publicKey: options, mediation, signal }); +} + +customElements.define('passkey-submit', class extends HTMLElement { + static formAssociated = true; + + connectedCallback() { + this.internals = this.attachInternals(); + this.attrs = { + operation: this.getAttribute('operation'), + name: this.getAttribute('name'), + emailName: this.getAttribute('email-name'), + requestTokenName: this.getAttribute('request-token-name'), + requestTokenValue: this.getAttribute('request-token-value'), + }; + + this.internals.form.addEventListener('submit', (event) => { + if (event.submitter?.name === '__passkeySubmit') { + event.preventDefault(); + this.obtainAndSubmitCredential(); + } + }); + + this.tryAutofillPasskey(); + } + + disconnectedCallback() { + this.abortController?.abort(); + } + + async obtainCredential(useConditionalMediation, signal) { + if (!browserSupportsPasskeys) { + throw new Error('Some passkey features are missing. Please update your browser.'); + } + + const headers = { + [this.attrs.requestTokenName]: this.attrs.requestTokenValue, + }; + + if (this.attrs.operation === 'Create') { + return await createCredential(headers, signal); + } else if (this.attrs.operation === 'Request') { + const email = new FormData(this.internals.form).get(this.attrs.emailName); + const mediation = useConditionalMediation ? 'conditional' : undefined; + return await requestCredential(email, mediation, headers, signal); + } else { + throw new Error(`Unknown passkey operation '${this.attrs.operation}'.`); + } + } + + async obtainAndSubmitCredential(useConditionalMediation = false) { + this.abortController?.abort(); + this.abortController = new AbortController(); + const signal = this.abortController.signal; + const formData = new FormData(); + try { + const credential = await this.obtainCredential(useConditionalMediation, signal); + const credentialJson = JSON.stringify(credential); + formData.append(`${this.attrs.name}.CredentialJson`, credentialJson); + } catch (error) { + if (error.name === 'AbortError') { + // The user explicitly canceled the operation - return without error. + return; + } + console.error(error); + if (useConditionalMediation) { + // An error occurred during conditional mediation, which is not user-initiated. + // We log the error in the console but do not relay it to the user. + return; + } + const errorMessage = error.name === 'NotAllowedError' + ? 'No passkey was provided by the authenticator.' + : error.message; + formData.append(`${this.attrs.name}.Error`, errorMessage); + } + this.internals.setFormValue(formData); + this.internals.form.submit(); + } + + async tryAutofillPasskey() { + if (browserSupportsPasskeys && this.attrs.operation === 'Request' && await PublicKeyCredential.isConditionalMediationAvailable?.()) { + await this.obtainAndSubmitCredential(/* useConditionalMediation */ true); + } + } +}); diff --git a/Queueify.Web/Components/Account/Shared/RedirectToLogin.razor b/Queueify.Web/Components/Account/Shared/RedirectToLogin.razor new file mode 100644 index 0000000..c8b8eff --- /dev/null +++ b/Queueify.Web/Components/Account/Shared/RedirectToLogin.razor @@ -0,0 +1,8 @@ +@inject NavigationManager NavigationManager + +@code { + protected override void OnInitialized() + { + NavigationManager.NavigateTo($"Account/Login?returnUrl={Uri.EscapeDataString(NavigationManager.Uri)}", forceLoad: true); + } +} diff --git a/Queueify.Web/Components/Account/Shared/ShowRecoveryCodes.razor b/Queueify.Web/Components/Account/Shared/ShowRecoveryCodes.razor new file mode 100644 index 0000000..aa92e11 --- /dev/null +++ b/Queueify.Web/Components/Account/Shared/ShowRecoveryCodes.razor @@ -0,0 +1,28 @@ + +

Recovery codes

+ +
+
+ @foreach (var recoveryCode in RecoveryCodes) + { +
+ @recoveryCode +
+ } +
+
+ +@code { + [Parameter] + public string[] RecoveryCodes { get; set; } = []; + + [Parameter] + public string? StatusMessage { get; set; } +} diff --git a/Queueify.Web/Components/Account/Shared/StatusMessage.razor b/Queueify.Web/Components/Account/Shared/StatusMessage.razor new file mode 100644 index 0000000..12cd544 --- /dev/null +++ b/Queueify.Web/Components/Account/Shared/StatusMessage.razor @@ -0,0 +1,29 @@ +@if (!string.IsNullOrEmpty(DisplayMessage)) +{ + var statusMessageClass = DisplayMessage.StartsWith("Error") ? "danger" : "success"; + +} + +@code { + private string? messageFromCookie; + + [Parameter] + public string? Message { get; set; } + + [CascadingParameter] + private HttpContext HttpContext { get; set; } = default!; + + private string? DisplayMessage => Message ?? messageFromCookie; + + protected override void OnInitialized() + { + messageFromCookie = HttpContext.Request.Cookies[IdentityRedirectManager.StatusCookieName]; + + if (messageFromCookie is not null) + { + HttpContext.Response.Cookies.Delete(IdentityRedirectManager.StatusCookieName); + } + } +} diff --git a/Queueify.Web/Components/App.razor b/Queueify.Web/Components/App.razor new file mode 100644 index 0000000..d77e1a8 --- /dev/null +++ b/Queueify.Web/Components/App.razor @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Queueify.Web/Components/Layout/MainLayout.razor b/Queueify.Web/Components/Layout/MainLayout.razor new file mode 100644 index 0000000..78624f3 --- /dev/null +++ b/Queueify.Web/Components/Layout/MainLayout.razor @@ -0,0 +1,23 @@ +@inherits LayoutComponentBase + +
+ + +
+
+ About +
+ +
+ @Body +
+
+
+ +
+ An unhandled error has occurred. + Reload + 🗙 +
diff --git a/Queueify.Web/Components/Layout/MainLayout.razor.css b/Queueify.Web/Components/Layout/MainLayout.razor.css new file mode 100644 index 0000000..38d1f25 --- /dev/null +++ b/Queueify.Web/Components/Layout/MainLayout.razor.css @@ -0,0 +1,98 @@ +.page { + position: relative; + display: flex; + flex-direction: column; +} + +main { + flex: 1; +} + +.sidebar { + background-image: linear-gradient(180deg, rgb(5, 39, 103) 0%, #3a0647 70%); +} + +.top-row { + background-color: #f7f7f7; + border-bottom: 1px solid #d6d5d5; + justify-content: flex-end; + height: 3.5rem; + display: flex; + align-items: center; +} + + .top-row ::deep a, .top-row ::deep .btn-link { + white-space: nowrap; + margin-left: 1.5rem; + text-decoration: none; + } + + .top-row ::deep a:hover, .top-row ::deep .btn-link:hover { + text-decoration: underline; + } + + .top-row ::deep a:first-child { + overflow: hidden; + text-overflow: ellipsis; + } + +@media (max-width: 640.98px) { + .top-row { + justify-content: space-between; + } + + .top-row ::deep a, .top-row ::deep .btn-link { + margin-left: 0; + } +} + +@media (min-width: 641px) { + .page { + flex-direction: row; + } + + .sidebar { + width: 250px; + height: 100vh; + position: sticky; + top: 0; + } + + .top-row { + position: sticky; + top: 0; + z-index: 1; + } + + .top-row.auth ::deep a:first-child { + flex: 1; + text-align: right; + width: 0; + } + + .top-row, article { + padding-left: 2rem !important; + padding-right: 1.5rem !important; + } +} + +#blazor-error-ui { + color-scheme: light only; + background: lightyellow; + bottom: 0; + box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2); + box-sizing: border-box; + display: none; + left: 0; + padding: 0.6rem 1.25rem 0.7rem 1.25rem; + position: fixed; + width: 100%; + z-index: 1000; +} + + #blazor-error-ui .dismiss { + cursor: pointer; + position: absolute; + right: 0.75rem; + top: 0.5rem; + } diff --git a/Queueify.Web/Components/Layout/NavMenu.razor b/Queueify.Web/Components/Layout/NavMenu.razor new file mode 100644 index 0000000..6ddc241 --- /dev/null +++ b/Queueify.Web/Components/Layout/NavMenu.razor @@ -0,0 +1,92 @@ +@implements IDisposable + +@inject NavigationManager NavigationManager + + + + + + + +@code { + private string? currentUrl; + + protected override void OnInitialized() + { + currentUrl = NavigationManager.ToBaseRelativePath(NavigationManager.Uri); + NavigationManager.LocationChanged += OnLocationChanged; + } + + private void OnLocationChanged(object? sender, LocationChangedEventArgs e) + { + currentUrl = NavigationManager.ToBaseRelativePath(e.Location); + StateHasChanged(); + } + + public void Dispose() + { + NavigationManager.LocationChanged -= OnLocationChanged; + } +} + diff --git a/Queueify.Web/Components/Layout/NavMenu.razor.css b/Queueify.Web/Components/Layout/NavMenu.razor.css new file mode 100644 index 0000000..0145d9d --- /dev/null +++ b/Queueify.Web/Components/Layout/NavMenu.razor.css @@ -0,0 +1,125 @@ +.navbar-toggler { + appearance: none; + cursor: pointer; + width: 3.5rem; + height: 2.5rem; + color: white; + position: absolute; + top: 0.5rem; + right: 1rem; + border: 1px solid rgba(255, 255, 255, 0.1); + background: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba%28255, 255, 255, 0.55%29' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e") no-repeat center/1.75rem rgba(255, 255, 255, 0.1); +} + +.navbar-toggler:checked { + background-color: rgba(255, 255, 255, 0.5); +} + +.top-row { + min-height: 3.5rem; + background-color: rgba(0,0,0,0.4); +} + +.navbar-brand { + font-size: 1.1rem; +} + +.bi { + display: inline-block; + position: relative; + width: 1.25rem; + height: 1.25rem; + margin-right: 0.75rem; + top: -1px; + background-size: cover; +} + +.bi-house-door-fill-nav-menu { + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-house-door-fill' viewBox='0 0 16 16'%3E%3Cpath d='M6.5 14.5v-3.505c0-.245.25-.495.5-.495h2c.25 0 .5.25.5.5v3.5a.5.5 0 0 0 .5.5h4a.5.5 0 0 0 .5-.5v-7a.5.5 0 0 0-.146-.354L13 5.793V2.5a.5.5 0 0 0-.5-.5h-1a.5.5 0 0 0-.5.5v1.293L8.354 1.146a.5.5 0 0 0-.708 0l-6 6A.5.5 0 0 0 1.5 7.5v7a.5.5 0 0 0 .5.5h4a.5.5 0 0 0 .5-.5Z'/%3E%3C/svg%3E"); +} + +.bi-plus-square-fill-nav-menu { + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-plus-square-fill' viewBox='0 0 16 16'%3E%3Cpath d='M2 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2zm6.5 4.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3a.5.5 0 0 1 1 0z'/%3E%3C/svg%3E"); +} + +.bi-list-nested-nav-menu { + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-list-nested' viewBox='0 0 16 16'%3E%3Cpath fill-rule='evenodd' d='M4.5 11.5A.5.5 0 0 1 5 11h10a.5.5 0 0 1 0 1H5a.5.5 0 0 1-.5-.5zm-2-4A.5.5 0 0 1 3 7h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5zm-2-4A.5.5 0 0 1 1 3h10a.5.5 0 0 1 0 1H1a.5.5 0 0 1-.5-.5z'/%3E%3C/svg%3E"); +} + +.bi-lock-nav-menu { + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-list-nested' viewBox='0 0 16 16'%3E%3Cpath d='M8 1a2 2 0 0 1 2 2v4H6V3a2 2 0 0 1 2-2zm3 6V3a3 3 0 0 0-6 0v4a2 2 0 0 0-2 2v5a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2zM5 8h6a1 1 0 0 1 1 1v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V9a1 1 0 0 1 1-1z'/%3E%3C/svg%3E"); +} + +.bi-person-nav-menu { + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-person' viewBox='0 0 16 16'%3E%3Cpath d='M8 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6Zm2-3a2 2 0 1 1-4 0 2 2 0 0 1 4 0Zm4 8c0 1-1 1-1 1H3s-1 0-1-1 1-4 6-4 6 3 6 4Zm-1-.004c-.001-.246-.154-.986-.832-1.664C11.516 10.68 10.289 10 8 10c-2.29 0-3.516.68-4.168 1.332-.678.678-.83 1.418-.832 1.664h10Z'/%3E%3C/svg%3E"); +} + +.bi-person-badge-nav-menu { + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-person-badge' viewBox='0 0 16 16'%3E%3Cpath d='M6.5 2a.5.5 0 0 0 0 1h3a.5.5 0 0 0 0-1h-3zM11 8a3 3 0 1 1-6 0 3 3 0 0 1 6 0z'/%3E%3Cpath d='M4.5 0A2.5 2.5 0 0 0 2 2.5V14a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V2.5A2.5 2.5 0 0 0 11.5 0h-7zM3 2.5A1.5 1.5 0 0 1 4.5 1h7A1.5 1.5 0 0 1 13 2.5v10.795a4.2 4.2 0 0 0-.776-.492C11.392 12.387 10.063 12 8 12s-3.392.387-4.224.803a4.2 4.2 0 0 0-.776.492V2.5z'/%3E%3C/svg%3E"); +} + +.bi-person-fill-nav-menu { + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-person-fill' viewBox='0 0 16 16'%3E%3Cpath d='M3 14s-1 0-1-1 1-4 6-4 6 3 6 4-1 1-1 1H3Zm5-6a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z'/%3E%3C/svg%3E"); +} + +.bi-arrow-bar-left-nav-menu { + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-arrow-bar-left' viewBox='0 0 16 16'%3E%3Cpath d='M12.5 15a.5.5 0 0 1-.5-.5v-13a.5.5 0 0 1 1 0v13a.5.5 0 0 1-.5.5ZM10 8a.5.5 0 0 1-.5.5H3.707l2.147 2.146a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 1 1 .708.708L3.707 7.5H9.5a.5.5 0 0 1 .5.5Z'/%3E%3C/svg%3E"); +} + +.nav-item { + font-size: 0.9rem; + padding-bottom: 0.5rem; +} + + .nav-item:first-of-type { + padding-top: 1rem; + } + + .nav-item:last-of-type { + padding-bottom: 1rem; + } + + .nav-item ::deep .nav-link { + color: #d7d7d7; + background: none; + border: none; + border-radius: 4px; + height: 3rem; + display: flex; + align-items: center; + line-height: 3rem; + width: 100%; + } + +.nav-item ::deep a.active { + background-color: rgba(255,255,255,0.37); + color: white; +} + +.nav-item ::deep .nav-link:hover { + background-color: rgba(255,255,255,0.1); + color: white; +} + +.nav-scrollable { + display: none; +} + +.navbar-toggler:checked ~ .nav-scrollable { + display: block; +} + +@media (min-width: 641px) { + .navbar-toggler { + display: none; + } + + .nav-scrollable { + /* Never collapse the sidebar for wide screens */ + display: block; + + /* Allow sidebar to scroll for tall menus */ + height: calc(100vh - 3.5rem); + overflow-y: auto; + } +} diff --git a/Queueify.Web/Components/Layout/ReconnectModal.razor b/Queueify.Web/Components/Layout/ReconnectModal.razor new file mode 100644 index 0000000..e740b0c --- /dev/null +++ b/Queueify.Web/Components/Layout/ReconnectModal.razor @@ -0,0 +1,31 @@ + + + +
+ +

+ Rejoining the server... +

+

+ Rejoin failed... trying again in seconds. +

+

+ Failed to rejoin.
Please retry or reload the page. +

+ +

+ The session has been paused by the server. +

+

+ Failed to resume the session.
Please retry or reload the page. +

+ +
+
diff --git a/Queueify.Web/Components/Layout/ReconnectModal.razor.css b/Queueify.Web/Components/Layout/ReconnectModal.razor.css new file mode 100644 index 0000000..3ad3773 --- /dev/null +++ b/Queueify.Web/Components/Layout/ReconnectModal.razor.css @@ -0,0 +1,157 @@ +.components-reconnect-first-attempt-visible, +.components-reconnect-repeated-attempt-visible, +.components-reconnect-failed-visible, +.components-pause-visible, +.components-resume-failed-visible, +.components-rejoining-animation { + display: none; +} + +#components-reconnect-modal.components-reconnect-show .components-reconnect-first-attempt-visible, +#components-reconnect-modal.components-reconnect-show .components-rejoining-animation, +#components-reconnect-modal.components-reconnect-paused .components-pause-visible, +#components-reconnect-modal.components-reconnect-resume-failed .components-resume-failed-visible, +#components-reconnect-modal.components-reconnect-retrying, +#components-reconnect-modal.components-reconnect-retrying .components-reconnect-repeated-attempt-visible, +#components-reconnect-modal.components-reconnect-retrying .components-rejoining-animation, +#components-reconnect-modal.components-reconnect-failed, +#components-reconnect-modal.components-reconnect-failed .components-reconnect-failed-visible { + display: block; +} + + +#components-reconnect-modal { + background-color: white; + width: 20rem; + margin: 20vh auto; + padding: 2rem; + border: 0; + border-radius: 0.5rem; + box-shadow: 0 3px 6px 2px rgba(0, 0, 0, 0.3); + opacity: 0; + transition: display 0.5s allow-discrete, overlay 0.5s allow-discrete; + animation: components-reconnect-modal-fadeOutOpacity 0.5s both; + &[open] + +{ + animation: components-reconnect-modal-slideUp 1.5s cubic-bezier(.05, .89, .25, 1.02) 0.3s, components-reconnect-modal-fadeInOpacity 0.5s ease-in-out 0.3s; + animation-fill-mode: both; +} + +} + +#components-reconnect-modal::backdrop { + background-color: rgba(0, 0, 0, 0.4); + animation: components-reconnect-modal-fadeInOpacity 0.5s ease-in-out; + opacity: 1; +} + +@keyframes components-reconnect-modal-slideUp { + 0% { + transform: translateY(30px) scale(0.95); + } + + 100% { + transform: translateY(0); + } +} + +@keyframes components-reconnect-modal-fadeInOpacity { + 0% { + opacity: 0; + } + + 100% { + opacity: 1; + } +} + +@keyframes components-reconnect-modal-fadeOutOpacity { + 0% { + opacity: 1; + } + + 100% { + opacity: 0; + } +} + +.components-reconnect-container { + display: flex; + flex-direction: column; + align-items: center; + gap: 1rem; +} + +#components-reconnect-modal p { + margin: 0; + text-align: center; +} + +#components-reconnect-modal button { + border: 0; + background-color: #6b9ed2; + color: white; + padding: 4px 24px; + border-radius: 4px; +} + + #components-reconnect-modal button:hover { + background-color: #3b6ea2; + } + + #components-reconnect-modal button:active { + background-color: #6b9ed2; + } + +.components-rejoining-animation { + position: relative; + width: 80px; + height: 80px; +} + + .components-rejoining-animation div { + position: absolute; + border: 3px solid #0087ff; + opacity: 1; + border-radius: 50%; + animation: components-rejoining-animation 1.5s cubic-bezier(0, 0.2, 0.8, 1) infinite; + } + + .components-rejoining-animation div:nth-child(2) { + animation-delay: -0.5s; + } + +@keyframes components-rejoining-animation { + 0% { + top: 40px; + left: 40px; + width: 0; + height: 0; + opacity: 0; + } + + 4.9% { + top: 40px; + left: 40px; + width: 0; + height: 0; + opacity: 0; + } + + 5% { + top: 40px; + left: 40px; + width: 0; + height: 0; + opacity: 1; + } + + 100% { + top: 0px; + left: 0px; + width: 80px; + height: 80px; + opacity: 0; + } +} diff --git a/Queueify.Web/Components/Layout/ReconnectModal.razor.js b/Queueify.Web/Components/Layout/ReconnectModal.razor.js new file mode 100644 index 0000000..a44de78 --- /dev/null +++ b/Queueify.Web/Components/Layout/ReconnectModal.razor.js @@ -0,0 +1,63 @@ +// Set up event handlers +const reconnectModal = document.getElementById("components-reconnect-modal"); +reconnectModal.addEventListener("components-reconnect-state-changed", handleReconnectStateChanged); + +const retryButton = document.getElementById("components-reconnect-button"); +retryButton.addEventListener("click", retry); + +const resumeButton = document.getElementById("components-resume-button"); +resumeButton.addEventListener("click", resume); + +function handleReconnectStateChanged(event) { + if (event.detail.state === "show") { + reconnectModal.showModal(); + } else if (event.detail.state === "hide") { + reconnectModal.close(); + } else if (event.detail.state === "failed") { + document.addEventListener("visibilitychange", retryWhenDocumentBecomesVisible); + } else if (event.detail.state === "rejected") { + location.reload(); + } +} + +async function retry() { + document.removeEventListener("visibilitychange", retryWhenDocumentBecomesVisible); + + try { + // Reconnect will asynchronously return: + // - true to mean success + // - false to mean we reached the server, but it rejected the connection (e.g., unknown circuit ID) + // - exception to mean we didn't reach the server (this can be sync or async) + const successful = await Blazor.reconnect(); + if (!successful) { + // We have been able to reach the server, but the circuit is no longer available. + // We'll reload the page so the user can continue using the app as quickly as possible. + const resumeSuccessful = await Blazor.resumeCircuit(); + if (!resumeSuccessful) { + location.reload(); + } else { + reconnectModal.close(); + } + } + } catch (err) { + // We got an exception, server is currently unavailable + document.addEventListener("visibilitychange", retryWhenDocumentBecomesVisible); + } +} + +async function resume() { + try { + const successful = await Blazor.resumeCircuit(); + if (!successful) { + location.reload(); + } + } catch { + reconnectModal.classList.replace("components-reconnect-paused", "components-reconnect-resume-failed"); + } +} + +async function retryWhenDocumentBecomesVisible() { + if (document.visibilityState === "visible") { + await retry(); + } +} diff --git a/Queueify.Web/Components/Pages/Auth.razor b/Queueify.Web/Components/Pages/Auth.razor new file mode 100644 index 0000000..b7bbe6e --- /dev/null +++ b/Queueify.Web/Components/Pages/Auth.razor @@ -0,0 +1,13 @@ +@page "/auth" + +@using Microsoft.AspNetCore.Authorization + +@attribute [Authorize] + +Auth + +

You are authenticated

+ + + Hello @context.User.Identity?.Name! + diff --git a/Queueify.Web/Components/Pages/Error.razor b/Queueify.Web/Components/Pages/Error.razor new file mode 100644 index 0000000..576cc2d --- /dev/null +++ b/Queueify.Web/Components/Pages/Error.razor @@ -0,0 +1,36 @@ +@page "/Error" +@using System.Diagnostics + +Error + +

Error.

+

An error occurred while processing your request.

+ +@if (ShowRequestId) +{ +

+ Request ID: @RequestId +

+} + +

Development Mode

+

+ Swapping to Development environment will display more detailed information about the error that occurred. +

+

+ The Development environment shouldn't be enabled for deployed applications. + It can result in displaying sensitive information from exceptions to end users. + For local debugging, enable the Development environment by setting the ASPNETCORE_ENVIRONMENT environment variable to Development + and restarting the app. +

+ +@code{ + [CascadingParameter] + private HttpContext? HttpContext { get; set; } + + private string? RequestId { get; set; } + private bool ShowRequestId => !string.IsNullOrEmpty(RequestId); + + protected override void OnInitialized() => + RequestId = Activity.Current?.Id ?? HttpContext?.TraceIdentifier; +} diff --git a/Queueify.Web/Components/Pages/Home.razor b/Queueify.Web/Components/Pages/Home.razor new file mode 100644 index 0000000..9001e0b --- /dev/null +++ b/Queueify.Web/Components/Pages/Home.razor @@ -0,0 +1,7 @@ +@page "/" + +Home + +

Hello, world!

+ +Welcome to your new app. diff --git a/Queueify.Web/Components/Pages/NotFound.razor b/Queueify.Web/Components/Pages/NotFound.razor new file mode 100644 index 0000000..917ada1 --- /dev/null +++ b/Queueify.Web/Components/Pages/NotFound.razor @@ -0,0 +1,5 @@ +@page "/not-found" +@layout MainLayout + +

Not Found

+

Sorry, the content you are looking for does not exist.

\ No newline at end of file diff --git a/Queueify.Web/Components/Routes.razor b/Queueify.Web/Components/Routes.razor new file mode 100644 index 0000000..ae5f724 --- /dev/null +++ b/Queueify.Web/Components/Routes.razor @@ -0,0 +1,11 @@ +@using Queueify.Web.Components.Account.Shared + + + + + + + + + + diff --git a/Queueify.Web/Components/_Imports.razor b/Queueify.Web/Components/_Imports.razor new file mode 100644 index 0000000..d9e4c71 --- /dev/null +++ b/Queueify.Web/Components/_Imports.razor @@ -0,0 +1,12 @@ +@using System.Net.Http +@using System.Net.Http.Json +@using Microsoft.AspNetCore.Components.Authorization +@using Microsoft.AspNetCore.Components.Forms +@using Microsoft.AspNetCore.Components.Routing +@using Microsoft.AspNetCore.Components.Web +@using static Microsoft.AspNetCore.Components.Web.RenderMode +@using Microsoft.AspNetCore.Components.Web.Virtualization +@using Microsoft.JSInterop +@using Queueify.Web +@using Queueify.Web.Components +@using Queueify.Web.Components.Layout diff --git a/Queueify.Web/Data/ApplicationDbContext.cs b/Queueify.Web/Data/ApplicationDbContext.cs new file mode 100644 index 0000000..a726eaa --- /dev/null +++ b/Queueify.Web/Data/ApplicationDbContext.cs @@ -0,0 +1,8 @@ +using Microsoft.AspNetCore.Identity.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; + +namespace Queueify.Web.Data; + +public class ApplicationDbContext(DbContextOptions options) : IdentityDbContext(options) +{ +} diff --git a/Queueify.Web/Data/ApplicationUser.cs b/Queueify.Web/Data/ApplicationUser.cs new file mode 100644 index 0000000..6c55f58 --- /dev/null +++ b/Queueify.Web/Data/ApplicationUser.cs @@ -0,0 +1,9 @@ +using Microsoft.AspNetCore.Identity; + +namespace Queueify.Web.Data; + +// Add profile data for application users by adding properties to the ApplicationUser class +public class ApplicationUser : IdentityUser +{ +} + diff --git a/Queueify.Web/Data/Migrations/00000000000000_CreateIdentitySchema.Designer.cs b/Queueify.Web/Data/Migrations/00000000000000_CreateIdentitySchema.Designer.cs new file mode 100644 index 0000000..1f6d212 --- /dev/null +++ b/Queueify.Web/Data/Migrations/00000000000000_CreateIdentitySchema.Designer.cs @@ -0,0 +1,350 @@ +// +using System; +using Queueify.Web.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Queueify.Web.Migrations +{ + [DbContext(typeof(ApplicationDbContext))] + [Migration("00000000000000_CreateIdentitySchema")] + partial class CreateIdentitySchema + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.0"); + + modelBuilder.Entity("Queueify.Web.Data.ApplicationUser", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PhoneNumber") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserPasskey", b => + { + b.Property("CredentialId") + .HasMaxLength(1024) + .HasColumnType("BLOB"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("CredentialId"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserPasskeys", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("LoginProvider") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Queueify.Web.Data.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Queueify.Web.Data.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserPasskey", b => + { + b.HasOne("Queueify.Web.Data.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsOne("Microsoft.AspNetCore.Identity.IdentityPasskeyData", "Data", b1 => + { + b1.Property("IdentityUserPasskeyCredentialId") + .HasColumnType("BLOB"); + + b1.Property("AttestationObject") + .IsRequired() + .HasColumnType("BLOB"); + + b1.Property("ClientDataJson") + .IsRequired() + .HasColumnType("BLOB"); + + b1.Property("CreatedAt") + .HasColumnType("TEXT"); + + b1.Property("IsBackedUp") + .HasColumnType("INTEGER"); + + b1.Property("IsBackupEligible") + .HasColumnType("INTEGER"); + + b1.Property("IsUserVerified") + .HasColumnType("INTEGER"); + + b1.Property("Name") + .HasColumnType("TEXT"); + + b1.Property("PublicKey") + .IsRequired() + .HasColumnType("BLOB"); + + b1.Property("SignCount") + .HasColumnType("INTEGER"); + + b1.PrimitiveCollection("Transports") + .HasColumnType("TEXT"); + + b1.HasKey("IdentityUserPasskeyCredentialId"); + + b1.ToTable("AspNetUserPasskeys"); + + b1.ToJson("Data"); + + b1.WithOwner() + .HasForeignKey("IdentityUserPasskeyCredentialId"); + }); + + b.Navigation("Data") + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Queueify.Web.Data.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Queueify.Web.Data.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Queueify.Web/Data/Migrations/00000000000000_CreateIdentitySchema.cs b/Queueify.Web/Data/Migrations/00000000000000_CreateIdentitySchema.cs new file mode 100644 index 0000000..0f7eff8 --- /dev/null +++ b/Queueify.Web/Data/Migrations/00000000000000_CreateIdentitySchema.cs @@ -0,0 +1,249 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Queueify.Web.Migrations +{ + /// + public partial class CreateIdentitySchema : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AspNetRoles", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + Name = table.Column(type: "TEXT", maxLength: 256, nullable: true), + NormalizedName = table.Column(type: "TEXT", maxLength: 256, nullable: true), + ConcurrencyStamp = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetRoles", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AspNetUsers", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + UserName = table.Column(type: "TEXT", maxLength: 256, nullable: true), + NormalizedUserName = table.Column(type: "TEXT", maxLength: 256, nullable: true), + Email = table.Column(type: "TEXT", maxLength: 256, nullable: true), + NormalizedEmail = table.Column(type: "TEXT", maxLength: 256, nullable: true), + EmailConfirmed = table.Column(type: "INTEGER", nullable: false), + PasswordHash = table.Column(type: "TEXT", nullable: true), + SecurityStamp = table.Column(type: "TEXT", nullable: true), + ConcurrencyStamp = table.Column(type: "TEXT", nullable: true), + PhoneNumber = table.Column(type: "TEXT", maxLength: 256, nullable: true), + PhoneNumberConfirmed = table.Column(type: "INTEGER", nullable: false), + TwoFactorEnabled = table.Column(type: "INTEGER", nullable: false), + LockoutEnd = table.Column(type: "TEXT", nullable: true), + LockoutEnabled = table.Column(type: "INTEGER", nullable: false), + AccessFailedCount = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUsers", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AspNetRoleClaims", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + RoleId = table.Column(type: "TEXT", nullable: false), + ClaimType = table.Column(type: "TEXT", nullable: true), + ClaimValue = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); + table.ForeignKey( + name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", + column: x => x.RoleId, + principalTable: "AspNetRoles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AspNetUserClaims", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + UserId = table.Column(type: "TEXT", nullable: false), + ClaimType = table.Column(type: "TEXT", nullable: true), + ClaimValue = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); + table.ForeignKey( + name: "FK_AspNetUserClaims_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AspNetUserLogins", + columns: table => new + { + LoginProvider = table.Column(type: "TEXT", maxLength: 128, nullable: false), + ProviderKey = table.Column(type: "TEXT", maxLength: 128, nullable: false), + ProviderDisplayName = table.Column(type: "TEXT", nullable: true), + UserId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); + table.ForeignKey( + name: "FK_AspNetUserLogins_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AspNetUserPasskeys", + columns: table => new + { + CredentialId = table.Column(type: "BLOB", maxLength: 1024, nullable: false), + UserId = table.Column(type: "TEXT", nullable: false), + Data = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserPasskeys", x => x.CredentialId); + table.ForeignKey( + name: "FK_AspNetUserPasskeys_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AspNetUserRoles", + columns: table => new + { + UserId = table.Column(type: "TEXT", nullable: false), + RoleId = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); + table.ForeignKey( + name: "FK_AspNetUserRoles_AspNetRoles_RoleId", + column: x => x.RoleId, + principalTable: "AspNetRoles", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_AspNetUserRoles_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "AspNetUserTokens", + columns: table => new + { + UserId = table.Column(type: "TEXT", nullable: false), + LoginProvider = table.Column(type: "TEXT", maxLength: 128, nullable: false), + Name = table.Column(type: "TEXT", maxLength: 128, nullable: false), + Value = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); + table.ForeignKey( + name: "FK_AspNetUserTokens_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_AspNetRoleClaims_RoleId", + table: "AspNetRoleClaims", + column: "RoleId"); + + migrationBuilder.CreateIndex( + name: "RoleNameIndex", + table: "AspNetRoles", + column: "NormalizedName", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_AspNetUserClaims_UserId", + table: "AspNetUserClaims", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_AspNetUserLogins_UserId", + table: "AspNetUserLogins", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_AspNetUserPasskeys_UserId", + table: "AspNetUserPasskeys", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_AspNetUserRoles_RoleId", + table: "AspNetUserRoles", + column: "RoleId"); + + migrationBuilder.CreateIndex( + name: "EmailIndex", + table: "AspNetUsers", + column: "NormalizedEmail"); + + migrationBuilder.CreateIndex( + name: "UserNameIndex", + table: "AspNetUsers", + column: "NormalizedUserName", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AspNetRoleClaims"); + + migrationBuilder.DropTable( + name: "AspNetUserClaims"); + + migrationBuilder.DropTable( + name: "AspNetUserLogins"); + + migrationBuilder.DropTable( + name: "AspNetUserPasskeys"); + + migrationBuilder.DropTable( + name: "AspNetUserRoles"); + + migrationBuilder.DropTable( + name: "AspNetUserTokens"); + + migrationBuilder.DropTable( + name: "AspNetRoles"); + + migrationBuilder.DropTable( + name: "AspNetUsers"); + } + } +} diff --git a/Queueify.Web/Data/Migrations/ApplicationDbContextModelSnapshot.cs b/Queueify.Web/Data/Migrations/ApplicationDbContextModelSnapshot.cs new file mode 100644 index 0000000..d697e1e --- /dev/null +++ b/Queueify.Web/Data/Migrations/ApplicationDbContextModelSnapshot.cs @@ -0,0 +1,347 @@ +// +using System; +using Queueify.Web.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Queueify.Web.Migrations +{ + [DbContext(typeof(ApplicationDbContext))] + partial class ApplicationDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.0"); + + modelBuilder.Entity("Queueify.Web.Data.ApplicationUser", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PhoneNumber") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserPasskey", b => + { + b.Property("CredentialId") + .HasMaxLength(1024) + .HasColumnType("BLOB"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("CredentialId"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserPasskeys", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("LoginProvider") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Queueify.Web.Data.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Queueify.Web.Data.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserPasskey", b => + { + b.HasOne("Queueify.Web.Data.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsOne("Microsoft.AspNetCore.Identity.IdentityPasskeyData", "Data", b1 => + { + b1.Property("IdentityUserPasskeyCredentialId") + .HasColumnType("BLOB"); + + b1.Property("AttestationObject") + .IsRequired() + .HasColumnType("BLOB"); + + b1.Property("ClientDataJson") + .IsRequired() + .HasColumnType("BLOB"); + + b1.Property("CreatedAt") + .HasColumnType("TEXT"); + + b1.Property("IsBackedUp") + .HasColumnType("INTEGER"); + + b1.Property("IsBackupEligible") + .HasColumnType("INTEGER"); + + b1.Property("IsUserVerified") + .HasColumnType("INTEGER"); + + b1.Property("Name") + .HasColumnType("TEXT"); + + b1.Property("PublicKey") + .IsRequired() + .HasColumnType("BLOB"); + + b1.Property("SignCount") + .HasColumnType("INTEGER"); + + b1.PrimitiveCollection("Transports") + .HasColumnType("TEXT"); + + b1.HasKey("IdentityUserPasskeyCredentialId"); + + b1.ToTable("AspNetUserPasskeys"); + + b1.ToJson("Data"); + + b1.WithOwner() + .HasForeignKey("IdentityUserPasskeyCredentialId"); + }); + + b.Navigation("Data") + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Queueify.Web.Data.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Queueify.Web.Data.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Queueify.Web/Data/app.db b/Queueify.Web/Data/app.db new file mode 100644 index 0000000000000000000000000000000000000000..ae41190d55c40dea2c508ec62e4332f8b6fba474 GIT binary patch literal 118784 zcmeI)O>^7E83%B}lt_uzn_m*dN!=h+rxiz%hxAL_dYW-*3bHw(NSUM@c`_arCSe<6 zl8^~7jxy;%mgAY^)DO{9KS7TE1UdAQX-}Q$^w4t;8BZ?VU0{U;35ZM_c4W?<6NLhH zvAg&^4;F7qDz^)Utt$`APD`_uOOb_$Bt`z9D3M4cN`B6hAO1N_ewpA4WWXrXzwOiEfZABT3ucE726 zlxw4wAs!BC`qo69up3Y{B$cgleluIXt8A!ul_lQIijs8OOu2oC&8+t|<2K8htntyT zm&$7XX3=e#x2KfVb+xP(b83a}F58UkYLe_jN+}hUHMO7;lU%lv%dV+EW(1VUs&Op; z2;8-)fDy3G!bdQhNPV;rlW#8%&I*S>ND8*%)H8iHE@v{*^KMU0Y-yJDSl<)Ug0Gni z%M4z@OO9MeZ|H5?(3&(0ZWKy44pT%C1Lups*Nl(?JfpZ^V7jeowicX;VrRZA;hhQj zHr=3?^4nZaQ?98bnO;`qAxgY?O`yt*pAIMWlXg89&B3!!qBXTk#I6nkM}%Ud1u zQ=_4Gf&r7fcthVCP-D%ocAMH>QETbErZ6QO6+kgczLekt77~ISmHuIqsX-j$!1=*x zbJTIaJ~P~;?T$u>y0d2XAd+A)|MF5#%yUi6XbCZQmQRMo+$r{AP7g>j_o_G5@({-) z-&zbncDq{27fFAcYOy-h@yS}L?(GKU1uMIwHM;?YVqW-;UT0XNj^WmHjGi{{vH-Xz zUQ2({)!TKwXEEX9?0ZfKt~n5 z-t8FnUd7g0y8-2-2U4L!4wuj>TaV1PUhKB+d*>hFoFSABG1}@=b6u<3W=Cz)%iJUO zt6m&wxBWHHocK^Ie((Ot-Cg&FipZ|T=?bg)( zy$P132a=Gb^dNDwl>Isxl%=f1KQs8QnS!&_-Ab4dcn*XlpO<7I6^;l#Wtkkz!p6jJ zXV^k)f9FJ8zIs)9R$?r*n!3JeJnU$;VYaPXhDCzE7q~L&rwXj&p&hn4@E8wiD8P|i zqcpm8`wqDsAcN(3=iWCFk$f~J-@6)?D1rUdGJ&h>B^sYJe6^bN}Xa z&55I&Xax^xmOP8)Jr_1iW=?m!#ml9;Zr1`%`$Upc%00Izz00bZa0SG_<0uX=z1R(IH3H&-*nf5&dNC!Rz z;D7)BrtKca3jqi~00Izz00bZa0SG_<0uX?}@B;MxKmG6j@qqvYAOHafKmY;|fB*y_ z009Uw?1Rwwb2tWV=5P$##AOHafZ~?sk=Mwma00bZa0SG_<0uX=z z1Rwwb2#l`)-v5tpY_Vq$fB*y_009U<00Izz00bZa0WN_1e=dP<2tWV=5P$##AOHaf zKmY;|fWY_);QoJnV~ah500bZa0SG_<0uX=z1Rwwb2yg-1|8og^LjVF0fB*y_009U< z00Izz00hQY0RR8L@r^C^3<3~<00bZa0SG_<0uX=z1R%f#@cy4m;2Q!EfB*y_009U< z00Izz00bZ~z5;mvKfbZWokp`Xcsfax(T!bZ6qFv=%)lMWra;X3V~?pN`3uRViY$8~SI~lcr(o zHLYu#Y`K=Tc8j{bZRwq=`B-mTwM_4tGY94QxV*e9z4*k|?l*O>ylgggt7mZ`S5~uC zRjFog6jUYIQ<_wkW)lkeBx#TNMpCJ&J5{AvB0t-O!irl+8xAYXm5P;WIh!w5mE_ij zFn%_gq_S1cZ)VGPl@0Z-vc$VtQIc+(DYp-?nf1PA+-6ymH9ng4Qd!O4EV?c8_LQ=^ zu9nqePOb3WWt)**O_F^`DW#&arWRCUlFL?d*){dYjDRv(HIC&Ufx9*pFaow&_y}eb zsrk#%f8JgmoD~j%kQ8jisb~6ZT+U>q=iQ#1*wQTPvA!py1z$54mKnT)mmIl{-q72& zp*3k1+$fZ89HxjO2F@3MuNff)ct&x-z;s*FY%Mqw#m;63AJbya$CrYBeh^P$leLgg&agayhe_QJ%Lw>svhMnmre115R#hQ2qT z#+qU6HnqK?*3x-RVM;hEfMS$4^MljosN;TpX1Gb)9gPrm zXU*(EB*9|-<)xmO=bD<)5@PNwpA3t+Q|!f@9*|`2Rd1^0A&yDDwHScxcD0l*lKwW; zVs)tFleJRa+YQPKR(3~gb^{8#EUJ#F4)0dP;emj0xxx9fV(V#3GY zQ@GS7hr|lmGIbD{>JKWNkewZJ4t;NV+SjUkF7}FlN>IhE2L_c^4m*t}f7YOS!y4(C zo18bFH)C;maZ&o}{hs4WIHat25IjF8yVp2J;EzNoq&{0LNcRPl?SFyF$Za_Kd zfmG;_!zHxJ)+4j67rU+d-uXv3X9%T3jJEpJT-WNh*-_i{GWUr6Dwy@hX4h8Rq>ghz zA#{3JIG~Yioy-E(I*Eba$eG=?-9N9Abh{Fd$@#^>=YQXIyEV0cZ-Qm%fh1%pJxJUv zWxq}aWhpE1&kVk6rr<1fw-ROqo&zDt=OtN4g(HGbStbXwurcx58MYAH-#HPNuU?g& zl^9E{rmk-q4?CJ|m~HEpVUghP1+I+xsRHYGXoqbMJjO#B3UDOXD2;C2zC&&Y$Y6Qi zx%W*(Bp;2*_pXK|N?<>=OyKGXa{oI;?}7KT61&EKwi=*C)7-x~U320nCtATn8sS`e@F(aktL9)97|Fe|uXc_gib~j`PTjo-JAJ zBz>+VJYFN$h)YTDtjb$Xrv7*?E`LCJoMt_;OSj(ce&KfK_T$wV(1~+>nEKN@aryeP zw11xUklzvRtDJK%{dd0M?H^nFp1;%3&3ebcHl{o4w3n>FLsmHPbw?8VILB#Ln07|;DE6a;nEV<~%<&e*c^Kq>hrth@fOijV;Maeqj`t|yyVbtgnx9DMyPjk69tD5@KjIr2G!Fp?KmY;| zfB*y_009U<00Iy=1_HSMKL$a-5Fh{n2tWV=5P$##AOHafKmYU00bZa0SG_<0uX=z1Rwwb2#i<&_x~dXM)MGW z00bZa0SG_<0uX=z1Rwx`V<3S0|6>pY3;_ZVfB*y_009U<00Izz00bZ~VgcO$j~E!u zLjVF0fB*y_009U<00Izz00fSK0Pg>fK@czm2tWV=5P$##AOHafKmY;|fWU|a{s;9z B<$nMG literal 0 HcmV?d00001 diff --git a/Queueify.Web/Program.cs b/Queueify.Web/Program.cs new file mode 100644 index 0000000..6fa04c5 --- /dev/null +++ b/Queueify.Web/Program.cs @@ -0,0 +1,69 @@ +using Microsoft.AspNetCore.Components.Authorization; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; +using Queueify.Web.Components; +using Queueify.Web.Components.Account; +using Queueify.Web.Data; + +var builder = WebApplication.CreateBuilder(args); + +// Add services to the container. +builder.Services.AddRazorComponents() + .AddInteractiveServerComponents(); + +builder.Services.AddCascadingAuthenticationState(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); + +builder.Services.AddAuthentication(options => + { + options.DefaultScheme = IdentityConstants.ApplicationScheme; + options.DefaultSignInScheme = IdentityConstants.ExternalScheme; + }) + .AddIdentityCookies(); + +var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found."); +builder.Services.AddDbContext(options => + options.UseSqlite(connectionString)); +builder.Services.AddDatabaseDeveloperPageExceptionFilter(); + +builder.Services.AddIdentityCore(options => + { + options.SignIn.RequireConfirmedAccount = true; + options.Stores.SchemaVersion = IdentitySchemaVersions.Version3; + }) + .AddEntityFrameworkStores() + .AddSignInManager() + .AddDefaultTokenProviders(); + +builder.Services.AddSingleton, IdentityNoOpEmailSender>(); + +var app = builder.Build(); + +// Configure the HTTP request pipeline. +if (app.Environment.IsDevelopment()) +{ + app.UseMigrationsEndPoint(); +} +else +{ + app.UseExceptionHandler("/Error", createScopeForErrors: true); + // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. + app.UseHsts(); +} +app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true); +app.UseHttpsRedirection(); + +app.UseAntiforgery(); + +app.MapStaticAssets(); +app.MapRazorComponents() + .AddInteractiveServerRenderMode(); + +// Add additional endpoints required by the Identity /Account Razor components. +app.MapAdditionalIdentityEndpoints(); + +app.MapGet("/healthz", () => Results.Ok("ok")).AllowAnonymous(); + +app.Run(); +public partial class Program; diff --git a/Queueify.Web/Properties/launchSettings.json b/Queueify.Web/Properties/launchSettings.json new file mode 100644 index 0000000..bc9e9e9 --- /dev/null +++ b/Queueify.Web/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5147", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7193;http://localhost:5147", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } + } diff --git a/Queueify.Web/Queueify.Web.csproj b/Queueify.Web/Queueify.Web.csproj new file mode 100644 index 0000000..7aee75d --- /dev/null +++ b/Queueify.Web/Queueify.Web.csproj @@ -0,0 +1,29 @@ + + + + net10.0 + enable + enable + aspnet-Queueify_Web-86f5f9b8-1fbe-4cb8-8319-bc31a324140e + true + + + + + + + + + + + + + + + + + + + + + diff --git a/Queueify.Web/appsettings.Development.json b/Queueify.Web/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/Queueify.Web/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/Queueify.Web/appsettings.json b/Queueify.Web/appsettings.json new file mode 100644 index 0000000..f5d9bae --- /dev/null +++ b/Queueify.Web/appsettings.json @@ -0,0 +1,12 @@ +{ + "ConnectionStrings": { + "DefaultConnection": "DataSource=Data/app.db;Cache=Shared" + }, + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/Queueify.Web/wwwroot/app.css b/Queueify.Web/wwwroot/app.css new file mode 100644 index 0000000..73a69d6 --- /dev/null +++ b/Queueify.Web/wwwroot/app.css @@ -0,0 +1,60 @@ +html, body { + font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; +} + +a, .btn-link { + color: #006bb7; +} + +.btn-primary { + color: #fff; + background-color: #1b6ec2; + border-color: #1861ac; +} + +.btn:focus, .btn:active:focus, .btn-link.nav-link:focus, .form-control:focus, .form-check-input:focus { + box-shadow: 0 0 0 0.1rem white, 0 0 0 0.25rem #258cfb; +} + +.content { + padding-top: 1.1rem; +} + +h1:focus { + outline: none; +} + +.valid.modified:not([type=checkbox]) { + outline: 1px solid #26b050; +} + +.invalid { + outline: 1px solid #e50000; +} + +.validation-message { + color: #e50000; +} + +.blazor-error-boundary { + background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121; + padding: 1rem 1rem 1rem 3.7rem; + color: white; +} + + .blazor-error-boundary::after { + content: "An error has occurred." + } + +.darker-border-checkbox.form-check-input { + border-color: #929292; +} + +.form-floating > .form-control-plaintext::placeholder, .form-floating > .form-control::placeholder { + color: var(--bs-secondary-color); + text-align: end; +} + +.form-floating > .form-control-plaintext:focus::placeholder, .form-floating > .form-control:focus::placeholder { + text-align: start; +} \ No newline at end of file diff --git a/Queueify.Web/wwwroot/favicon.png b/Queueify.Web/wwwroot/favicon.png new file mode 100644 index 0000000000000000000000000000000000000000..8422b59695935d180d11d5dbe99653e711097819 GIT binary patch literal 1148 zcmV-?1cUpDP)9h26h2-Cs%i*@Moc3?#6qJID|D#|3|2Hn7gTIYEkr|%Xjp);YgvFmB&0#2E2b=| zkVr)lMv9=KqwN&%obTp-$<51T%rx*NCwceh-E+=&e(oLO`@Z~7gybJ#U|^tB2Pai} zRN@5%1qsZ1e@R(XC8n~)nU1S0QdzEYlWPdUpH{wJ2Pd4V8kI3BM=)sG^IkUXF2-j{ zrPTYA6sxpQ`Q1c6mtar~gG~#;lt=s^6_OccmRd>o{*=>)KS=lM zZ!)iG|8G0-9s3VLm`bsa6e ze*TlRxAjXtm^F8V`M1%s5d@tYS>&+_ga#xKGb|!oUBx3uc@mj1%=MaH4GR0tPBG_& z9OZE;->dO@`Q)nr<%dHAsEZRKl zedN6+3+uGHejJp;Q==pskSAcRcyh@6mjm2z-uG;s%dM-u0*u##7OxI7wwyCGpS?4U zBFAr(%GBv5j$jS@@t@iI8?ZqE36I^4t+P^J9D^ELbS5KMtZ z{Qn#JnSd$15nJ$ggkF%I4yUQC+BjDF^}AtB7w348EL>7#sAsLWs}ndp8^DsAcOIL9 zTOO!!0!k2`9BLk25)NeZp7ev>I1Mn={cWI3Yhx2Q#DnAo4IphoV~R^c0x&nw*MoIV zPthX?{6{u}sMS(MxD*dmd5rU(YazQE59b|TsB5Tm)I4a!VaN@HYOR)DwH1U5y(E)z zQqQU*B%MwtRQ$%x&;1p%ANmc|PkoFJZ%<-uq%PX&C!c-7ypis=eP+FCeuv+B@h#{4 zGx1m0PjS~FJt}3mdt4c!lel`1;4W|03kcZRG+DzkTy|7-F~eDsV2Tx!73dM0H0CTh zl)F-YUkE1zEzEW(;JXc|KR5{ox%YTh{$%F$a36JP6Nb<0%#NbSh$dMYF-{ z1_x(Vx)}fs?5_|!5xBTWiiIQHG<%)*e=45Fhjw_tlnmlixq;mUdC$R8v#j( zhQ$9YR-o%i5Uc`S?6EC51!bTRK=Xkyb<18FkCKnS2;o*qlij1YA@-nRpq#OMTX&RbL<^2q@0qja!uIvI;j$6>~k@IMwD42=8$$!+R^@5o6HX(*n~ + + diff --git a/docs/WEB_PORT.md b/docs/WEB_PORT.md new file mode 100644 index 0000000..9b82a1a --- /dev/null +++ b/docs/WEB_PORT.md @@ -0,0 +1,145 @@ +# Web version: analysis and report + +Status: proposal (2026-10-14). Nothing here is built yet. + +## 1. Summary + +Port Queueify to the web as a **Blazor Web App on .NET 10** that references `Queueify.Core` directly. +About 2,500 lines of Core carry over almost untouched; the ~3,200 lines of WinUI code (`MainWindow.xaml` +and its code-behind) are rewritten as Razor components, with the same layout, copy and Fluent look. + +Why this needs the least new code: + +| Choice | Reason | +| --- | --- | +| Blazor (C# in components) | The XAML page structure maps one-to-one to Razor components; ViewModel-style logic in `MainWindow.xaml.cs` is plain C# and moves over. | +| Reference `Queueify.Core` as is | Matcher, catalogs, `BacklogStore`, `Loc` + `Strings.En/Es`, `Countries`, `QueueText`, `Shortcuts` have no UI or Windows dependency. All 20 test files keep working. | +| Fluent UI Blazor (`Microsoft.FluentUI.AspNetCore.Components`) | Same Fluent design tokens, accent, corner radius, light/dark, nav pane, cards, dialogs, toasts and info bars as WinUI 3. Closest possible aesthetic with no custom CSS framework. | +| Interactive Server render mode | No API layer to write: components call services directly and secrets never reach the browser. Use WebAssembly only if offline use is wanted (see §6). | + +## 2. What carries over from the current code + +| Part | Lines | Web fate | +| --- | --- | --- | +| `Models/*` (BacklogItem, AlbumResult, AlbumMatch, AppSettings) | ~270 | Reuse as is. | +| `Matcher`, `SpotifyCatalog`, `TidalCatalog`, `CoverUrls`, `Countries` | ~600 | Reuse as is (server-side `HttpClient`; fixes the browser CORS problem too). | +| `Loc`, `Strings.En`, `Strings.Es`, `QueueText`, `Shortcuts` | ~850 | Reuse. `Loc` is a static, so it must become per-request/per-user (see §4, localization). | +| `BacklogStore` (SQLite) | 259 | Reuse, one database file per user (or an EF Core migration later). | +| `Updater`, `AppData`, `UiState`, `ExternalLinks` | ~490 | Drop or replace (web has no self-update; app data is server config; `UiState` becomes user preferences). | +| `CloudSync` + Firestore rules | ~310 | Not needed for the web: the server is the single source of truth. Keep it only as an **import/sync bridge** with the desktop app (see §5). | +| `OcrService`, `OcrLanguages` | ~350 | Replace (Windows.Media.Ocr is Windows-only; see §4). | +| `Queueify.Launcher`, `tools/Pack`, AOT/LZMA packaging | ~3,500 | Not used by the web. | +| `MainWindow.xaml` + `.cs`, `Controls/*` | ~3,400 | Rewrite as Razor components (see §3). | + +Core currently targets `net10.0-windows10.0.26100.0`. Only `OcrService` (and `ExternalLinks`' `Process.Start`) +need Windows. Move those two behind interfaces (`IOcr`, `ILinkOpener`), retarget Core to plain `net10.0` +(or multi-target both), and the web project can reference it. The desktop app keeps using the Windows +implementations. This is the single biggest "less code" lever. + +## 3. UI mapping (WinUI to Blazor) + +| WinUI 3 | Blazor / Fluent UI | +| --- | --- | +| `NavigationView` (LeftCompact) with InfoBadges | `FluentNav` / `FluentNavMenu` with `FluentBadge`; collapses to an icon rail. | +| Left "Add" pane + `PaneSplitter` | CSS grid with a resizable column (small JS-free splitter or `FluentSplitter`). | +| `ListView` / `GridView` for queue (rows / cover tiles) | `FluentDataGrid` or a plain `@foreach` list with the same templates; virtualise with ``. | +| `CommandBar` (filter, Surprise me, sort, covers toggle) | `FluentToolbar` + `FluentSearch`, `FluentMenuButton`, `FluentSwitch`. | +| `InfoBar`, toast | `FluentMessageBar`, `IToastService`. | +| `ContentDialog`, `TeachingTip` quick tour | `IDialogService`, `FluentPopover` (tour steps). | +| `ServiceCard`, `ServiceLogo`, round number badges, pills | Small Razor components; the `Card`, `Pill`, `StepNumber` styles become ~40 lines of CSS using Fluent tokens (`--neutral-fill-rest`, `--accent-fill-rest`, `--layer-corner-radius`). | +| `ComboBox`, `ToggleSwitch` | `FluentSelect`, `FluentSwitch`. | +| Keyboard accelerators (Ctrl+F, Ctrl+B, Ctrl+V, F1) | Small JS interop keydown handler (or `@onkeydown` on the root). | +| Drag and drop photo, clipboard paste image | `InputFile` + a small JS interop for paste/drop. | +| Photo page with zoom and OCR line boxes | `` + an SVG/canvas overlay; zoom by CSS transform. | +| Light/dark/system theme | Fluent design token `BaseLayerLuminance` + `prefers-color-scheme`. | + +Aesthetic notes: keep Segoe UI Variable where available with `system-ui` fallback, 8 px corner radius, +the same accent colour, same icons (Fluent System Icons, same family as the `Segoe Fluent Icons` glyphs), +and the existing copy (the strings carry over verbatim). + +## 4. New components and services required + +### Identity (login / logout) +The desktop app has no accounts; the queue is the "password" (the Firestore key). A web app that holds +secrets needs real accounts. + +| Need | Recommendation | +| --- | --- | +| Sign in / sign out | **ASP.NET Core Identity** (Blazor Web App template, "Individual accounts"). .NET 10 adds **passkey** support, so a passwordless login is built in. | +| Social login (fewer passwords to manage) | Add Google and/or GitHub external providers (`AddGoogle`, `AddGitHub`). | +| Pages | `Login`, `Logout`, `Register`, `ForgotPassword`/`ResetPassword` (only if passwords are used), `Manage` (change email, passkeys, delete account). Scaffolded by the template; restyled with Fluent. | +| Authorisation | `[Authorize]` on every page except Login/Register/Help. Single-user mode option: register disabled after the first user (`AllowRegistration=false`). | +| Per-user data | The user id picks the database: `data/{userId}/queueify.db`. | +| Anti-forgery, cookies | Defaults of the template (HTTPS-only, `HttpOnly`, `SameSite=Lax`). | + +### Server-side services +| Component | Notes | +| --- | --- | +| `IUserDataLocator` | Replaces static `AppData.Folder` with a per-user folder. | +| Settings store (per user) | Replaces `settings.json`. Spotify/Tidal client secrets **encrypted with ASP.NET Data Protection**, never sent to the browser. | +| `IOcr` + implementation | Windows OCR does not exist on Linux hosts. Options: **Tesseract** (NuGet `Tesseract`, `spa`/`eng` traineddata, free, runs anywhere); **Azure AI Vision Read** (best quality for magazine photos, small cost); or host on Windows and keep `Windows.Media.Ocr`. Recommended: Tesseract first, Azure behind the same interface later. | +| `ILinkOpener` | Web: plain ``; deep links `https://open.spotify.com/...` and `https://tidal.com/browse/album/...` work in browsers. | +| Per-request localization | `Loc` is static today. Wrap in a scoped `ILocalizer` (same string tables) keyed on the user's language; keeps Rioplatense ES. | +| Photo upload limits | Max size, content-type check, `ImageSharp`-based re-encode, delete after OCR (nothing stored). | +| Backup / export | Download `queueify.db` as JSON/CSV; **import** from desktop (see §5). | +| Health + logging | `/healthz`, structured logs, no secrets in logs. | + +Not needed on the web: updater, launcher/packaging, taskbar identity, PaneSplitter drag code, Firestore +sync (optional), `OcrLanguages` installer. + +## 5. Moving data and keeping both apps + +Two options: + +1. **Web replaces the desktop app.** One-time import of `queueify.db` (upload the file, rows keep their + `uid`, so nothing duplicates). Simplest. +2. **Both live together.** The server exposes a small sync endpoint in the **same shape `CloudSync` + already speaks** (`uid`, `updatedAt`, `deleted`, server time). The desktop app gets a second "provider" + next to Firestore. More code; do this only if the desktop app stays. + +Recommendation: option 1 first, option 2 only if wanted. + +## 6. Hosting and rendering decision + +| Option | Pros | Cons | +| --- | --- | --- | +| Blazor Server (recommended) | Least code, secrets stay on server, Core runs unchanged. | Needs a live connection; no offline. | +| Blazor WebAssembly + minimal API | Offline/PWA possible. | Needs an API layer, SQLite in browser or sync, secrets and catalog calls must still be proxied (CORS, client secret). More code. | +| Host | Azure App Service / Container Apps (free-tier friendly), or a Docker container on the existing machine. SQLite on a mounted volume + nightly copy. | | + +## 7. Plan (test first, per project rules) + +1. Introduce `IOcr` / `ILinkOpener` in Core; retarget Core to `net10.0`; tests stay green. +2. New `Queueify.Web` project (Blazor Web App, Identity template, Fluent UI). Add a bUnit + xUnit project. +3. Shell: layout, nav, theme, localization, login/logout (tests: unauthenticated redirect, per-user data isolation). +4. Queue page: list/cover view, filter, sort, Surprise me, mark listened, rating. +5. Add pane: search with Matcher + catalogs, add without link. +6. Photo page with Tesseract. +7. Settings page (keys encrypted, country, preferred service, theme, language) + Help + quick tour. +8. Import/export, hosting, CI, security review ([SECURITY.md](../SECURITY.md) updated), docs and an ADR. + +Rough size: 25-35 Razor components, ~2,000 lines of new C# and ~400 lines of CSS, against ~3,400 lines of +WinUI code retired for the web. Core and its tests are unchanged except the two interface extractions. + +## 8. Risks + +- Client secrets for Spotify/Tidal now live on a server: encrypt, restrict file permissions, rate-limit search. +- Photo OCR quality differs from Windows OCR; compare on real magazine photos before choosing Tesseract vs Azure. +- Blazor Server keeps a circuit per tab; fine for a few users, plan capacity if opened to many. +- Static `Loc` and `AppData` are the main hidden global state to remove. + +## 9. Tooling to use on this work (saved for later) + +- `/security-review` (built into Claude Code) on every PR; optional GitHub Action + `anthropics/claude-code-security-review@main` with secret `CLAUDE_API_KEY` + (only for trusted PRs; not hardened against prompt injection). + Copy `.claude/commands/security-review.md` from that repo to customise rules + (add: "secrets in Data Protection", "per-user data isolation", "upload handling"). +- Anthropic `frontend-design` skill (github.com/anthropics/skills, `skills/frontend-design/SKILL.md`) + for the web UI. Its brief is "distinctive, not templated", so give it the existing Fluent/UniGetUI direction + as the explicit visual brief ("follow the brief exactly"). Process: design plan, review, build, + critique with screenshots. Floor: responsive, visible focus, reduced motion, contrast. +- Official .NET skills: `dotnet/skills` marketplace. + Claude Code: `/plugin marketplace add dotnet/skills`, then `/plugin marketplace browse dotnet-agent-skills` + and `/plugin install @dotnet-agent-skills` (for example `dotnet-diag`, skill + `analyzing-dotnet-performance`). Skills are plain `SKILL.md` files, so they can also be copied by hand. diff --git a/docs/adr/0010-web-app-and-shared-queue.md b/docs/adr/0010-web-app-and-shared-queue.md new file mode 100644 index 0000000..991fe24 --- /dev/null +++ b/docs/adr/0010-web-app-and-shared-queue.md @@ -0,0 +1,59 @@ +# ADR-0010: A web app beside the desktop app, one shared queue + +- Status: Accepted +- Date: 2026-10-14 + +## Context + +The queue is filled at the PC while reading magazines. Away from home, someone recommends an album and it +has to be added from a phone, then show up on the PCs. Firestore sync ([ADR-0003](0003-firestore-rest-sync.md)) +already shares a queue between PCs, but a phone needs an app with a login, and the web version can't keep the +Spotify/Tidal secrets in the browser. The analysis is in [WEB_PORT.md](../WEB_PORT.md). + +## Decision + +- **`Queueify.Web`**: a Blazor Web App (.NET 10, Interactive Server) with Fluent UI Blazor, ASP.NET Core + Identity (passkeys, password, optional Google/GitHub) and one SQLite queue per user, stored with + `BacklogStore`. It references `Queueify.Core`, which now also builds for plain `net10.0`; only + `OcrService` and `ExternalLinks` are Windows-only. +- **The web server is the shared database.** The desktop app gets a second sync provider next to Firestore, + speaking the contract below. A PC uses one provider at a time. Firestore stays supported. +- **Phone first for adding**: the Add page is the home page on small screens, installable as a PWA. +- **Secrets stay on the server**: catalogs are searched server-side; the Spotify/Tidal secrets are stored + encrypted with ASP.NET Data Protection and never sent to the browser. +- **OCR on the web** goes through `IOcr` (Tesseract); Windows OCR stays desktop-only. + +## Sync contract (v1) + +One round trip: `POST /api/sync` with `Authorization: Bearer `. + +Tokens are personal access tokens made in the web app (Settings → Connect a PC), shown once, stored as +SHA-256 hashes, revocable, per user. The text a PC is given is `queueify-web||`. + +```jsonc +// request +{ "since": "2026-10-14T12:00:00.000Z" /* the last serverTime received, or null */, + "albums": [ Album ], // this PC's dirty rows, deletions included + "settings": Settings|null } // only when changed here +// response +{ "serverTime": "…Z", // store as the next "since" + "albums": [ Album ], // rows with serverTime > since (not the ones just accepted) + "settings": Settings|null } +// Album +{ "uid", "artist", "album", "year", "source", "coverUrl", "spotifyId", "tidalId", + "addedAt", "listenedAt", "rating", "updatedAt", "deleted" } +// Settings: the shared set of AppSettings.CopySharedFrom, plus "updatedAt" +``` + +Rules: newest `updatedAt` wins per `uid` (ties keep the server's row); the server stamps `serverTime`; text +fields are cut at 500 characters as in the Firestore rules; at most 1,000 albums per request, and the client +repeats until the response is empty; unknown fields are ignored; a bad token is 401 and nothing else is said. +Deletions stay as soft rows. This is the same shape `CloudSync` already uses, so `BacklogStore`'s +`dirty`/`updated_at` columns are enough on the PC. + +## Consequences + +- Accounts now exist: the first user is the owner and registration can be turned off in configuration. +- The server needs HTTPS and a persistent data folder with backups. +- Two sync providers to keep tested; the contract tests run against the in-process server. +- Desktop and web share copy and string tables, so both languages stay identical. diff --git a/docs/adr/README.md b/docs/adr/README.md index b8c7e1d..85bbea3 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -14,3 +14,4 @@ old one and mark the old one `Superseded by ADR-NNNN`. Start from [`0000-templat | [0007](0007-single-trimmed-exe.md) | One trimmed exe as the download | Packaging superseded by 0008 | | [0008](0008-native-aot-and-a-starter-exe.md) | Native AOT and a starter exe | Accepted | | [0009](0009-update-from-github-releases.md) | Update from GitHub releases, inside the app | Accepted | +| [0010](0010-web-app-and-shared-queue.md) | A web app beside the desktop app, one shared queue | Accepted | From 0ecf84e962e45cb09e797229bdce4d334f843baf Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:10:29 -0300 Subject: [PATCH 02/66] feat(web): sync contract, connect text and per-user stores Co-Authored-By: Claude Sonnet 5.5 --- Queueify.Core/Services/SyncContract.cs | 44 +++++++++++++++++++++ Queueify.Tests/SyncContractTests.cs | 53 ++++++++++++++++++++++++++ Queueify.Web.Tests/UserStoresTests.cs | 38 ++++++++++++++++++ Queueify.Web/Storage/UserStores.cs | 22 +++++++++++ 4 files changed, 157 insertions(+) create mode 100644 Queueify.Core/Services/SyncContract.cs create mode 100644 Queueify.Tests/SyncContractTests.cs create mode 100644 Queueify.Web.Tests/UserStoresTests.cs create mode 100644 Queueify.Web/Storage/UserStores.cs diff --git a/Queueify.Core/Services/SyncContract.cs b/Queueify.Core/Services/SyncContract.cs new file mode 100644 index 0000000..9eb4ae3 --- /dev/null +++ b/Queueify.Core/Services/SyncContract.cs @@ -0,0 +1,44 @@ +using System.Text.Json.Serialization; + +namespace Queueify.Services; + +/// One album on the wire between a PC and the Queueify web server (ADR-0010). +public sealed record SyncAlbum( + string Uid, string Artist, string Album, int? Year, string? Source, string? CoverUrl, + string? SpotifyId, string? TidalId, DateTime AddedAt, DateTime? ListenedAt, double Rating, + DateTime UpdatedAt, bool Deleted); + +/// The settings shared between PCs (keys, Play app, country), as in AppSettings.CopySharedFrom. +public sealed record SyncSettings( + string SpotifyClientId, string SpotifyClientSecret, string TidalClientId, string TidalClientSecret, + string PreferredService, string CountryCode, DateTime UpdatedAt); + +public sealed record SyncRequest(DateTime? Since, List Albums, SyncSettings? Settings); + +public sealed record SyncResponse(DateTime ServerTime, List Albums, SyncSettings? Settings); + +[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, WriteIndented = false)] +[JsonSerializable(typeof(SyncRequest))] +[JsonSerializable(typeof(SyncResponse))] +public sealed partial class SyncJson : JsonSerializerContext; + +/// The text that connects a PC to a web server: queueify-web|https://host|token. +public static class SyncConnect +{ + private const string Prefix = "queueify-web"; + + public static string Format(string baseUrl, string token) => $"{Prefix}|{baseUrl.TrimEnd('/')}|{token}"; + + public static bool TryParse(string text, out string baseUrl, out string token) + { + baseUrl = token = ""; + var parts = text.Trim().Split('|'); + if (parts.Length != 3 || parts[0] != Prefix || parts[2].Length == 0 || parts[2].Any(char.IsWhiteSpace)) return false; + if (!Uri.TryCreate(parts[1], UriKind.Absolute, out var uri)) return false; + bool secure = uri.Scheme == Uri.UriSchemeHttps || (uri.Scheme == Uri.UriSchemeHttp && uri.IsLoopback); + if (!secure || uri.UserInfo.Length > 0) return false; + baseUrl = uri.GetLeftPart(UriPartial.Authority); + token = parts[2]; + return true; + } +} diff --git a/Queueify.Tests/SyncContractTests.cs b/Queueify.Tests/SyncContractTests.cs new file mode 100644 index 0000000..46461f9 --- /dev/null +++ b/Queueify.Tests/SyncContractTests.cs @@ -0,0 +1,53 @@ +using System.Text.Json; +using Queueify.Services; + +namespace Queueify.Tests; + +public sealed class SyncContractTests +{ + [Fact] + public void A_request_round_trips_through_the_source_generated_json() + { + var request = new SyncRequest( + new DateTime(2026, 10, 14, 12, 0, 0, DateTimeKind.Utc), + [new SyncAlbum("u1", "Artist", "Album", 1999, "Rolling Stone", null, "sp", "ti", + new DateTime(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc), null, -1, new DateTime(2026, 10, 2, 0, 0, 0, DateTimeKind.Utc), false)], + null); + + var json = JsonSerializer.Serialize(request, SyncJson.Default.SyncRequest); + var back = JsonSerializer.Deserialize(json, SyncJson.Default.SyncRequest)!; + + Assert.Equal(request.Since, back.Since); + Assert.Equal("Album", back.Albums.Single().Album); + Assert.Contains("\"updatedAt\"", json); // camelCase on the wire, as in the ADR + } + + [Fact] + public void Unknown_fields_are_ignored() + { + var back = JsonSerializer.Deserialize("""{"serverTime":"2026-10-14T12:00:00Z","albums":[],"settings":null,"future":1}""", SyncJson.Default.SyncResponse); + Assert.NotNull(back); + } + + [Fact] + public void The_connect_text_holds_the_server_and_the_token() + { + var text = SyncConnect.Format("https://q.example.com", "qw_abc"); + Assert.Equal("queueify-web|https://q.example.com|qw_abc", text); + Assert.True(SyncConnect.TryParse(" " + text + " ", out var url, out var token)); + Assert.Equal("https://q.example.com", url); + Assert.Equal("qw_abc", token); + } + + [Theory] + [InlineData("")] + [InlineData("queueify:proj:abc")] + [InlineData("queueify-web|http://q.example.com|qw_abc")] // plain http is refused, except localhost + [InlineData("queueify-web|https://q.example.com|")] + [InlineData("queueify-web|not a url|qw_abc")] + public void Bad_connect_text_is_refused(string text) => Assert.False(SyncConnect.TryParse(text, out _, out _)); + + [Fact] + public void Localhost_may_use_http_for_development() => + Assert.True(SyncConnect.TryParse("queueify-web|http://localhost:5080|qw_abc", out _, out _)); +} diff --git a/Queueify.Web.Tests/UserStoresTests.cs b/Queueify.Web.Tests/UserStoresTests.cs new file mode 100644 index 0000000..8d3974b --- /dev/null +++ b/Queueify.Web.Tests/UserStoresTests.cs @@ -0,0 +1,38 @@ +using Queueify.Models; +using Queueify.Web.Storage; + +namespace Queueify.Web.Tests; + +public sealed class UserStoresTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "qw-" + Guid.NewGuid().ToString("N")); + public void Dispose() { try { Directory.Delete(_root, true); } catch (IOException) { } } + + [Fact] + public void Each_user_gets_their_own_queue() + { + var stores = new UserStores(_root); + stores.QueueOf("alice").Insert(new BacklogItem { Artist = "A", Album = "One" }); + + Assert.Single(stores.QueueOf("alice").LoadAll()); + Assert.Empty(stores.QueueOf("bob").LoadAll()); + } + + [Fact] + public void Settings_are_kept_per_user() + { + var stores = new UserStores(_root); + stores.SaveSettings("alice", new AppSettings { CountryCode = "ES" }); + + Assert.Equal("ES", stores.LoadSettings("alice").CountryCode); + Assert.Equal("AR", stores.LoadSettings("bob").CountryCode); + } + + [Theory] + [InlineData("../evil")] + [InlineData("a/b")] + [InlineData("")] + [InlineData("a\\b")] + public void A_user_id_can_never_leave_the_data_folder(string id) => + Assert.Throws(() => new UserStores(_root).QueueOf(id)); +} diff --git a/Queueify.Web/Storage/UserStores.cs b/Queueify.Web/Storage/UserStores.cs new file mode 100644 index 0000000..d4a2e7c --- /dev/null +++ b/Queueify.Web/Storage/UserStores.cs @@ -0,0 +1,22 @@ +using Queueify.Models; +using Queueify.Services; + +namespace Queueify.Web.Storage; + +/// One folder per user under the data root, holding their queue (queueify.db) and settings.json. +public sealed class UserStores(string root) +{ + private string FolderOf(string userId) + { + if (userId.Length == 0 || userId.IndexOfAny(['/', '\\', ':']) >= 0 || userId.Contains("..")) + throw new ArgumentException("Not a valid user id.", nameof(userId)); + return Path.Combine(root, userId); + } + + public BacklogStore QueueOf(string userId) => new(Path.Combine(FolderOf(userId), "queueify.db")); + + public AppSettings LoadSettings(string userId) => AppData.LoadSettings(Path.Combine(FolderOf(userId), "settings.json")); + + public void SaveSettings(string userId, AppSettings settings) => + AppData.SaveSettings(settings, Path.Combine(FolderOf(userId), "settings.json")); +} From 39486164a81c99085d1e6f5f99335c30bad06562 Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:14:43 -0300 Subject: [PATCH 03/66] feat(core): IOcr, a Windows adapter and CleanLine on net10.0 Co-Authored-By: Claude Sonnet 5.5 --- Queueify.Core/Queueify.Core.csproj | 2 +- Queueify.Core/Services/IOcr.cs | 19 +++++++++++ Queueify.Core/Services/OcrService.Text.cs | 39 +++++++++++++++++++++++ Queueify.Core/Services/OcrService.cs | 31 ------------------ Queueify.Core/Services/WindowsOcr.cs | 24 ++++++++++++++ Queueify.Tests/WindowsOcrTests.cs | 30 +++++++++++++++++ Queueify.Web.Tests/Ocr/CleanLineTests.cs | 15 +++++++++ 7 files changed, 128 insertions(+), 32 deletions(-) create mode 100644 Queueify.Core/Services/IOcr.cs create mode 100644 Queueify.Core/Services/OcrService.Text.cs create mode 100644 Queueify.Core/Services/WindowsOcr.cs create mode 100644 Queueify.Tests/WindowsOcrTests.cs create mode 100644 Queueify.Web.Tests/Ocr/CleanLineTests.cs diff --git a/Queueify.Core/Queueify.Core.csproj b/Queueify.Core/Queueify.Core.csproj index 0c7b5c4..b2b45a6 100644 --- a/Queueify.Core/Queueify.Core.csproj +++ b/Queueify.Core/Queueify.Core.csproj @@ -15,7 +15,7 @@ - + diff --git a/Queueify.Core/Services/IOcr.cs b/Queueify.Core/Services/IOcr.cs new file mode 100644 index 0000000..46f91b7 --- /dev/null +++ b/Queueify.Core/Services/IOcr.cs @@ -0,0 +1,19 @@ +namespace Queueify.Services; + +/// A box in the pixels of the recognized image: plain numbers, so it needs no Windows type. +public readonly record struct OcrBox(double X, double Y, double Width, double Height); + +public sealed record OcrTextLine(string Text, OcrBox Bounds); + +/// What was read from one photo, and the size of the image the boxes refer to. +public sealed record OcrReading(IReadOnlyList Lines, int Width, int Height, string Language); + +/// +/// Reads the text on a picture. The desktop app answers with Windows OCR, the web app with Tesseract. +/// +public interface IOcr +{ + /// An encoded image (JPEG, PNG…); the caller keeps ownership of the stream. + /// "auto" (Spanish when available) or a primary language tag such as "es" or "en". + Task RecognizeAsync(Stream image, string language, CancellationToken ct = default); +} diff --git a/Queueify.Core/Services/OcrService.Text.cs b/Queueify.Core/Services/OcrService.Text.cs new file mode 100644 index 0000000..f0f127b --- /dev/null +++ b/Queueify.Core/Services/OcrService.Text.cs @@ -0,0 +1,39 @@ +using System.Globalization; +using System.Text.RegularExpressions; + +namespace Queueify.Services; + +// The plain-text half of OcrService: no Windows API in it, so the web build compiles it too. +public static partial class OcrService +{ + /// + /// Cleans a clicked OCR line: pulls out a release year, drops "(Label, 1983)"-style notes and + /// stray quotes, and turns ALL-CAPS magazine headings into Title Case. + /// + public static (string Text, int? Year) CleanLine(string raw) + { + int? year = null; + var ym = YearPattern().Match(raw); + if (ym.Success) year = int.Parse(ym.Value, CultureInfo.InvariantCulture); + + var text = BracketWithYear().Replace(raw, " "); + text = text.Trim().Trim('"', '“', '”', '«', '»', '\'', '‘', '’', '-', '–', '—', '•', '·', ':', ',', '.', ' '); + text = Whitespace().Replace(text, " "); + + // "Mostly uppercase" rather than "all": OCR often turns one capital (e.g. Í) into a lowercase letter. + var letters = text.Where(char.IsLetter).ToList(); + if (letters.Count >= 3 && letters.Count(char.IsUpper) >= letters.Count * 0.8) + text =CultureInfo.GetCultureInfo("es-AR").TextInfo.ToTitleCase(text.ToLower(CultureInfo.GetCultureInfo("es-AR"))); + + return (text, year); + } + + [GeneratedRegex(@"\b(19[4-9]\d|20[0-4]\d)\b")] + private static partial Regex YearPattern(); + + [GeneratedRegex(@"[\(\[][^\)\]]*\b(19[4-9]\d|20[0-4]\d)\b[^\)\]]*[\)\]]")] + private static partial Regex BracketWithYear(); + + [GeneratedRegex(@"\s+")] + private static partial Regex Whitespace(); +} diff --git a/Queueify.Core/Services/OcrService.cs b/Queueify.Core/Services/OcrService.cs index 2bb93e2..3549de3 100644 --- a/Queueify.Core/Services/OcrService.cs +++ b/Queueify.Core/Services/OcrService.cs @@ -244,35 +244,4 @@ private static (OcrEngine Engine, bool IsSpanish) CreateEngine(string preference } private static bool IsSpanishTag(string tag) => tag.StartsWith("es", StringComparison.OrdinalIgnoreCase); - - /// - /// Cleans a clicked OCR line: pulls out a release year, drops "(Label, 1983)"-style notes and - /// stray quotes, and turns ALL-CAPS magazine headings into Title Case. - /// - public static (string Text, int? Year) CleanLine(string raw) - { - int? year = null; - var ym = YearPattern().Match(raw); - if (ym.Success) year = int.Parse(ym.Value, CultureInfo.InvariantCulture); - - var text = BracketWithYear().Replace(raw, " "); - text = text.Trim().Trim('"', '“', '”', '«', '»', '\'', '‘', '’', '-', '–', '—', '•', '·', ':', ',', '.', ' '); - text = Whitespace().Replace(text, " "); - - // "Mostly uppercase" rather than "all": OCR often turns one capital (e.g. Í) into a lowercase letter. - var letters = text.Where(char.IsLetter).ToList(); - if (letters.Count >= 3 && letters.Count(char.IsUpper) >= letters.Count * 0.8) - text =CultureInfo.GetCultureInfo("es-AR").TextInfo.ToTitleCase(text.ToLower(CultureInfo.GetCultureInfo("es-AR"))); - - return (text, year); - } - - [GeneratedRegex(@"\b(19[4-9]\d|20[0-4]\d)\b")] - private static partial Regex YearPattern(); - - [GeneratedRegex(@"[\(\[][^\)\]]*\b(19[4-9]\d|20[0-4]\d)\b[^\)\]]*[\)\]]")] - private static partial Regex BracketWithYear(); - - [GeneratedRegex(@"\s+")] - private static partial Regex Whitespace(); } diff --git a/Queueify.Core/Services/WindowsOcr.cs b/Queueify.Core/Services/WindowsOcr.cs new file mode 100644 index 0000000..160ab64 --- /dev/null +++ b/Queueify.Core/Services/WindowsOcr.cs @@ -0,0 +1,24 @@ +namespace Queueify.Services; + +/// on the engine built into Windows; the desktop app's reader. +public sealed class WindowsOcr : IOcr +{ + public async Task RecognizeAsync(Stream image, string language, CancellationToken ct = default) + { + var page = await OcrService.RecognizeAsync(image.AsRandomAccessStream(), PreferenceFor(language, OcrService.InstalledTags)); + using var bitmap = page.Bitmap; + var lines = page.Lines + .Select(l => new OcrTextLine(l.Text, new OcrBox(l.Bounds.X, l.Bounds.Y, l.Bounds.Width, l.Bounds.Height))) + .ToList(); + return new OcrReading(lines, bitmap.PixelWidth, bitmap.PixelHeight, page.LanguageName); + } + + /// + /// A primary tag ("en") becomes the first installed Windows language that starts with it; "auto" and + /// anything not installed stay as they are, so falls back to Spanish. + /// + public static string PreferenceFor(string language, IEnumerable installed) => + language.Length is 2 && installed.FirstOrDefault(t => t.StartsWith(language + "-", StringComparison.OrdinalIgnoreCase)) is { } tag + ? tag + : language; +} diff --git a/Queueify.Tests/WindowsOcrTests.cs b/Queueify.Tests/WindowsOcrTests.cs new file mode 100644 index 0000000..0627def --- /dev/null +++ b/Queueify.Tests/WindowsOcrTests.cs @@ -0,0 +1,30 @@ +using Queueify.Services; + +namespace Queueify.Tests; + +public class WindowsOcrTests +{ + [Theory] + [InlineData("en", "en-US")] + [InlineData("es", "es-ES")] + [InlineData("auto", "auto")] // left for OcrLanguages.Choose + [InlineData("fr", "fr")] // not installed: unchanged + [InlineData("en-GB", "en-GB")] // already a full tag + public void PreferenceFor_TurnsAPrimaryTagIntoAnInstalledOne(string language, string expected) => + Assert.Equal(expected, WindowsOcr.PreferenceFor(language, ["es-ES", "en-US"])); + + [Fact] + public async Task RecognizeAsync_ReadsThePageThroughTheSharedInterface() + { + Assert.SkipWhen(OcrService.InstalledTags.Count == 0, "No text recognition language is installed in Windows."); + + IOcr ocr = new WindowsOcr(); + await using var file = File.OpenRead(Path.Combine(AppContext.BaseDirectory, "TestData", "magazine-page.png")); + + var reading = await ocr.RecognizeAsync(file, "auto", TestContext.Current.CancellationToken); + + Assert.Contains(reading.Lines, l => l.Text == "SPINETTA JADE"); + Assert.All(reading.Lines, l => Assert.True(l.Bounds.Width > 0 && l.Bounds.Height > 0)); + Assert.True(reading.Width > 0 && reading.Height > 0); + } +} diff --git a/Queueify.Web.Tests/Ocr/CleanLineTests.cs b/Queueify.Web.Tests/Ocr/CleanLineTests.cs new file mode 100644 index 0000000..0aaabf2 --- /dev/null +++ b/Queueify.Web.Tests/Ocr/CleanLineTests.cs @@ -0,0 +1,15 @@ +using Queueify.Services; + +namespace Queueify.Web.Tests.Ocr; + +/// The line cleanup is plain logic shared with the desktop app; it must exist on plain net10.0 too. +public class CleanLineTests +{ + [Theory] + [InlineData("CHARLY GARCÍA", "Charly García", null)] + [InlineData("Clics modernos (Interdisc, 1983)", "Clics modernos", 1983)] + [InlineData("«Bajo Belgrano»", "Bajo Belgrano", null)] + [InlineData("Año: 1983 - sello: EMI", "Año: 1983 - sello: EMI", 1983)] + public void CleanLine_works_on_the_web_build(string raw, string text, int? year) => + Assert.Equal((text, year), OcrService.CleanLine(raw)); +} From bd59513362ed863d8e4cdfd2f9d2d78ea7053c2e Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:22:15 -0300 Subject: [PATCH 04/66] feat(sync): desktop client for the Queueify web server ServerSync speaks the ADR-0010 contract behind ISyncProvider, next to CloudSync. Sync now offers 'Connect to a Queueify web server'; a PC uses one provider at a time and the web server wins if both are set. Co-Authored-By: Claude Sonnet 5.5 --- Queueify.Core/Models/AppSettings.cs | 70 +++ Queueify.Core/Services/CloudSync.cs | 2 +- Queueify.Core/Services/ISyncProvider.cs | 22 + Queueify.Core/Services/ServerSync.cs | 210 +++++++++ Queueify.Core/Services/Strings.En.cs | 20 + Queueify.Core/Services/Strings.Es.cs | 20 + Queueify.Core/Services/SyncException.cs | 7 + Queueify.Tests/LocTests.cs | 8 +- Queueify.Tests/ServerSyncTests.cs | 547 ++++++++++++++++++++++ Queueify/MainWindow.xaml | 1 + Queueify/MainWindow.xaml.cs | 128 ++++- README.md | 8 + docs/ARCHITECTURE.md | 9 +- docs/TESTING.md | 1 + docs/adr/0010-web-app-and-shared-queue.md | 9 + 15 files changed, 1031 insertions(+), 31 deletions(-) create mode 100644 Queueify.Core/Services/ISyncProvider.cs create mode 100644 Queueify.Core/Services/ServerSync.cs create mode 100644 Queueify.Core/Services/SyncException.cs create mode 100644 Queueify.Tests/ServerSyncTests.cs diff --git a/Queueify.Core/Models/AppSettings.cs b/Queueify.Core/Models/AppSettings.cs index ff8de57..846b774 100644 --- a/Queueify.Core/Models/AppSettings.cs +++ b/Queueify.Core/Models/AppSettings.cs @@ -1,3 +1,6 @@ +using System.Text.Json.Serialization; +using Queueify.Services; + namespace Queueify.Models; public sealed class AppSettings @@ -30,6 +33,20 @@ public sealed class AppSettings /// Server time of the newest change already downloaded; the next sync asks only for newer ones. public DateTime? CloudLastServerTime { get; set; } + // ── Online sync (a Queueify web server, ADR-0010). Per PC, never shared between PCs. ── + + /// The server's address (https, or http on loopback), from the connect text. + public string WebServerUrl { get; set; } = ""; + + /// This PC's personal access token. It lives only here and in the sync request's Authorization header. + public string WebToken { get; set; } = ""; + + /// The server's time of the last answer; the next sync asks only for newer changes. + public DateTime? WebLastServerTime { get; set; } + + /// The shared-settings stamp already in step with the server, so unchanged keys aren't sent again. + public DateTime? WebSettingsSyncedAt { get; set; } + /// A copy to try changes on (e.g. a sync connection) without touching the live settings. public AppSettings Clone() => (AppSettings)MemberwiseClone(); @@ -100,4 +117,57 @@ public AppSettings ForSettingsPage() public bool CloudConfigured => !string.IsNullOrWhiteSpace(CloudProjectId) && !string.IsNullOrWhiteSpace(CloudQueueKey); + + [JsonIgnore] + public bool WebConfigured => + !string.IsNullOrWhiteSpace(WebServerUrl) && !string.IsNullOrWhiteSpace(WebToken); + + [JsonIgnore] + public bool SyncConfigured => WebConfigured || CloudConfigured; + + /// The provider that syncs this PC. A PC uses one; the web server wins if a hand-edited file sets both. + [JsonIgnore] + public SyncKind ActiveSync => WebConfigured ? SyncKind.Web : CloudConfigured ? SyncKind.Cloud : SyncKind.None; + + /// + /// Names the online queue in use, to tell whether a sync that was running still applies. Not saved: it + /// would write the token a second time. + /// + [JsonIgnore] + public string SyncIdentity => ActiveSync switch + { + SyncKind.Web => $"web|{WebServerUrl}|{WebToken}", + SyncKind.Cloud => $"cloud|{CloudProjectId}|{CloudQueueKey}", + _ => "", + }; + + /// Starts using this Firestore queue; a PC syncs with one place, so a web connection is dropped. + public void ConnectCloud(string projectId, string queueKey) + { + DisconnectWeb(); + CloudProjectId = projectId; + CloudQueueKey = queueKey; + CloudLastServerTime = null; + } + + /// Starts using this web server; a Firestore connection is dropped. + public void ConnectWeb(string serverUrl, string token) + { + DisconnectCloud(); + WebServerUrl = serverUrl; + WebToken = token; + WebLastServerTime = WebSettingsSyncedAt = null; + } + + public void DisconnectWeb() + { + WebServerUrl = WebToken = ""; + WebLastServerTime = WebSettingsSyncedAt = null; + } + + public void DisconnectCloud() + { + CloudProjectId = CloudQueueKey = ""; + CloudLastServerTime = null; + } } diff --git a/Queueify.Core/Services/CloudSync.cs b/Queueify.Core/Services/CloudSync.cs index e885147..be3b6ce 100644 --- a/Queueify.Core/Services/CloudSync.cs +++ b/Queueify.Core/Services/CloudSync.cs @@ -20,7 +20,7 @@ public sealed record SyncResult(int Downloaded, int Uploaded, bool SettingsChang /// don't matter for that), then uploads this PC's pending changes. When both sides changed the same /// album, the most recent change wins. /// -public sealed partial class CloudSync(HttpClient http) +public sealed partial class CloudSync(HttpClient http) : ISyncProvider { /// The Firestore security rules to publish (tools/firestore.rules, embedded at build time). public static string SecurityRules { get; } = LoadRules(); diff --git a/Queueify.Core/Services/ISyncProvider.cs b/Queueify.Core/Services/ISyncProvider.cs new file mode 100644 index 0000000..6ffb04a --- /dev/null +++ b/Queueify.Core/Services/ISyncProvider.cs @@ -0,0 +1,22 @@ +using Queueify.Models; + +namespace Queueify.Services; + +/// Which online queue this PC syncs with; only one is used at a time. +public enum SyncKind { None, Cloud, Web } + +/// A way of keeping the queue in step with other PCs (the user's Firestore, or a Queueify web server). +public interface ISyncProvider +{ + Task SyncAsync(BacklogStore store, AppSettings settings, CancellationToken ct); +} + +public static class SyncProviders +{ + public static ISyncProvider For(SyncKind kind, CloudSync cloud, ServerSync web) => kind switch + { + SyncKind.Web => web, + SyncKind.Cloud => cloud, + _ => throw new InvalidOperationException("Sync isn't set up."), + }; +} diff --git a/Queueify.Core/Services/ServerSync.cs b/Queueify.Core/Services/ServerSync.cs new file mode 100644 index 0000000..cdddf3d --- /dev/null +++ b/Queueify.Core/Services/ServerSync.cs @@ -0,0 +1,210 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using Queueify.Models; + +namespace Queueify.Services; + +/// +/// Keeps the queue in step through a Queueify web server (ADR-0010): one POST to /api/sync sends this PC's +/// dirty albums and changed shared settings and brings back what changed on the server since the last +/// answer. Newest UpdatedAt wins per album, as with ; the server's clock only +/// orders its own answers, so PC clocks don't matter for what to download. +/// +/// The HTTP client should not follow redirects (the app's own doesn't); a redirect, or an answer from +/// another host, is refused so the token can't be handed to somebody else. Errors never carry the +/// token, the address or the server's text. +/// +public sealed class ServerSync(HttpClient http, int maxBatch = ServerSync.MaxBatch) : ISyncProvider +{ + /// How long one request may take. + public static readonly TimeSpan Timeout = TimeSpan.FromSeconds(20); + + /// Most albums in one request (ADR-0010); a bigger queue goes up in several rounds. + public const int MaxBatch = 1000; + + /// Longest text the server accepts per field; longer text is shortened on upload. + public const int MaxTextLength = CloudSync.MaxTextLength; + + private const int MaxExtraRounds = 20; + private const long MaxAnswerBytes = 64L * 1024 * 1024; + + public async Task SyncAsync(BacklogStore store, AppSettings s, CancellationToken ct) + { + if (!SyncConnect.TryParse(SyncConnect.Format(s.WebServerUrl, s.WebToken), out var baseUrl, out var token)) + throw new SyncException(Loc.T("webSync.err.not_configured")); + var endpoint = new Uri(baseUrl + "/api/sync"); + + var dirty = store.LoadDirty(); + var since = s.WebLastServerTime; + bool firstConnection = since == null; + var settingsToSend = SettingsToSend(s); + int sent = 0, downloaded = 0, rounds = 0; + bool settingsChanged = false, serverHadSettings = false; + int maxRounds = MaxExtraRounds + dirty.Count / maxBatch; + + while (true) + { + if (++rounds > maxRounds) throw new SyncException(Loc.T("webSync.err.no_end")); + + var batch = dirty.Skip(sent).Take(maxBatch).ToList(); + var answer = await PostAsync(endpoint, token, + new SyncRequest(since, batch.Select(ToWire).ToList(), settingsToSend), ct); + + // The server has the batch now. Rows it kept because its own were newer come back below. + foreach (var item in batch) store.MarkUploaded(item); + sent += batch.Count; + if (settingsToSend != null) + { + s.WebSettingsSyncedAt = settingsToSend.UpdatedAt; + settingsToSend = null; + } + + foreach (var wire in answer.Albums) + { + if (string.IsNullOrEmpty(wire.Uid)) continue; + var remote = ToItem(wire); + var local = store.FindByUid(remote.Uid); + if (local == null && remote.Deleted) continue; // deleted before this PC saw it + if (local != null && local.UpdatedAt >= remote.UpdatedAt) continue; // same or newer here + store.ApplyRemote(remote); + downloaded++; + } + + if (answer.Settings is { } shared) + { + serverHadSettings = true; + if (shared.UpdatedAt > (s.SharedSettingsUpdatedAt ?? DateTime.MinValue)) + { + TakeSettings(s, shared); + settingsChanged = true; + } + } + + since = answer.ServerTime; + s.WebLastServerTime = since; + + bool more = sent < dirty.Count || answer.Albums.Count > 0; + if (!more && firstConnection && !serverHadSettings && s.SharedSettingsUpdatedAt == null + && (s.SpotifyConfigured || s.TidalConfigured)) + { + // A new server with no keys yet: this PC's keys become the shared ones. + s.SharedSettingsUpdatedAt = BacklogStore.Now(); + settingsToSend = SettingsToSend(s); + more = true; + firstConnection = false; + } + if (!more) break; + } + + return new SyncResult(downloaded, dirty.Count, settingsChanged); + } + + private async Task PostAsync(Uri endpoint, string token, SyncRequest body, CancellationToken ct) + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeout.CancelAfter(Timeout); + try + { + using var request = new HttpRequestMessage(HttpMethod.Post, endpoint) + { + Content = new StringContent(JsonSerializer.Serialize(body, SyncJson.Default.SyncRequest), Encoding.UTF8, "application/json"), + }; + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + + using var res = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeout.Token); + + if ((int)res.StatusCode is >= 300 and < 400 + || (res.RequestMessage?.RequestUri is { } final && !SameOrigin(final, endpoint))) + throw new SyncException(Loc.T("webSync.err.redirect")); + if (res.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) + throw new SyncException(Loc.T("webSync.err.unauthorized")); + if (!res.IsSuccessStatusCode) + throw new SyncException(Loc.F("webSync.err.server", (int)res.StatusCode)); + + var text = await ReadBoundedAsync(res, timeout.Token); + return JsonSerializer.Deserialize(text, SyncJson.Default.SyncResponse) is { Albums: not null } answer + ? answer + : throw new SyncException(Loc.T("webSync.err.bad_reply")); + } + catch (OperationCanceledException) when (!ct.IsCancellationRequested) + { + throw new SyncException(Loc.T("webSync.err.timeout")); + } + catch (HttpRequestException) + { + // Not kept as the inner exception: its message can name the address. + throw new SyncException(Loc.T("webSync.err.offline")); + } + catch (JsonException) + { + throw new SyncException(Loc.T("webSync.err.bad_reply")); + } + } + + private static bool SameOrigin(Uri a, Uri b) => + a.Scheme == b.Scheme && a.Host == b.Host && a.Port == b.Port; + + private static async Task ReadBoundedAsync(HttpResponseMessage res, CancellationToken ct) + { + if (res.Content.Headers.ContentLength > MaxAnswerBytes) throw new SyncException(Loc.T("webSync.err.bad_reply")); + await using var stream = await res.Content.ReadAsStreamAsync(ct); + using var buffer = new MemoryStream(); + var chunk = new byte[81920]; + int n; + while ((n = await stream.ReadAsync(chunk, ct)) > 0) + { + if (buffer.Length + n > MaxAnswerBytes) throw new SyncException(Loc.T("webSync.err.bad_reply")); + buffer.Write(chunk, 0, n); + } + return Encoding.UTF8.GetString(buffer.GetBuffer(), 0, (int)buffer.Length); + } + + // ───────────── Mapping ───────────── + + private static SyncSettings? SettingsToSend(AppSettings s) => + s.SharedSettingsUpdatedAt is DateTime stamp && stamp != s.WebSettingsSyncedAt + ? new SyncSettings(Cut(s.SpotifyClientId)!, Cut(s.SpotifyClientSecret)!, Cut(s.TidalClientId)!, Cut(s.TidalClientSecret)!, + Cut(s.PreferredService)!, Cut(s.CountryCode)!, Utc(stamp)) + : null; + + private static void TakeSettings(AppSettings s, SyncSettings shared) + { + s.SpotifyClientId = shared.SpotifyClientId ?? ""; + s.SpotifyClientSecret = shared.SpotifyClientSecret ?? ""; + s.TidalClientId = shared.TidalClientId ?? ""; + s.TidalClientSecret = shared.TidalClientSecret ?? ""; + if (!string.IsNullOrWhiteSpace(shared.PreferredService)) s.PreferredService = shared.PreferredService; + if (!string.IsNullOrWhiteSpace(shared.CountryCode)) s.CountryCode = shared.CountryCode; + s.SharedSettingsUpdatedAt = s.WebSettingsSyncedAt = Utc(shared.UpdatedAt); + } + + private static SyncAlbum ToWire(BacklogItem i) => new( + i.Uid, Cut(i.Artist)!, Cut(i.Album)!, i.Year, Cut(i.Source), Cut(i.CoverUrl), Cut(i.SpotifyId), Cut(i.TidalId), + i.AddedAt.ToUniversalTime(), i.ListenedAt?.ToUniversalTime(), i.Rating, Utc(i.UpdatedAt), i.Deleted); + + private static BacklogItem ToItem(SyncAlbum a) => new() + { + Uid = a.Uid, + Artist = a.Artist ?? "", + Album = a.Album ?? "", + Year = a.Year, + Source = a.Source, + CoverUrl = a.CoverUrl, + SpotifyId = a.SpotifyId, + TidalId = a.TidalId, + AddedAt = Utc(a.AddedAt).ToLocalTime(), + ListenedAt = a.ListenedAt is DateTime l ? Utc(l).ToLocalTime() : null, + Rating = double.IsNaN(a.Rating) || a.Rating < 0 ? -1 : Math.Min(a.Rating, 5), + UpdatedAt = Utc(a.UpdatedAt), + Deleted = a.Deleted, + }; + + private static string? Cut(string? text) => + text is { Length: > MaxTextLength } ? text[..MaxTextLength] : text; + + /// A time with no zone is taken as UTC, the zone every time on the wire is in. + private static DateTime Utc(DateTime t) => + t.Kind == DateTimeKind.Unspecified ? DateTime.SpecifyKind(t, DateTimeKind.Utc) : t.ToUniversalTime(); +} diff --git a/Queueify.Core/Services/Strings.En.cs b/Queueify.Core/Services/Strings.En.cs index 62e0819..ced8215 100644 --- a/Queueify.Core/Services/Strings.En.cs +++ b/Queueify.Core/Services/Strings.En.cs @@ -353,5 +353,25 @@ public static partial class Loc ["tour.3"] = "Photograph a magazine page with your phone and drop the photo into this window. Then click the artist and the album on it.", ["tour.4.title"] = "All your PCs", ["tour.4"] = "Connect Sync once to keep the same queue on every PC. Help (F1) explains everything else.", + ["webSync.setup.option"] = "Connect to a Queueify web server", + ["webSync.setup.text"] = "In your Queueify web app, open Settings → Connect a PC, create a token and copy the connect text. Paste it here. This PC syncs with that server instead of Firebase; to switch later, disconnect first.", + ["webSync.code"] = "Connect text", + ["webSync.code.placeholder"] = "queueify-web|https://…", + ["webSync.bad_code"] = "That doesn't look like a connect text. It starts with \"queueify-web|\" and the address must be https.", + ["webSync.joined"] = "Connected. Your queue now has {0} from the web server.", + ["webSync.this_pc"] = "This PC is synced with the Queueify web server {0}. {1}", + ["webSync.private"] = "The token stays on this PC. To stop it working, revoke it in the web app (Settings → Connect a PC).", + ["webSync.disconnected"] = "This PC no longer syncs. Its queue stays here; the server's copy is untouched.", + ["webSync.tip.at"] = "Synced with the web server at {0:t}", + ["webSync.tip.ok"] = "Synced with the web server", + ["webSync.err.not_configured"] = "The web server's address or token isn't valid. Connect again with a new connect text.", + ["webSync.err.unauthorized"] = "The web server didn't accept this PC's token. It may have been revoked: make a new one in the web app and connect again.", + ["webSync.err.redirect"] = "The web server sent this PC somewhere else, so nothing was sent. Check the address in the connect text.", + ["webSync.err.server"] = "The web server had a problem (error {0}). Your changes are kept and will sync later.", + ["webSync.err.bad_reply"] = "The web server's answer wasn't something Queueify understands. Is the address a Queueify web app?", + ["webSync.err.no_end"] = "The web server kept sending changes and sync stopped. Your changes are kept; try again later.", + ["webSync.err.timeout"] = "The web server didn't answer in time. Your changes will sync later.", + ["webSync.err.offline"] = "Can't reach the web server right now. Your changes are kept and will sync when it's reachable.", + ["webSync.help"] = "Instead of Firebase you can sync with a Queueify web server (yours): in the web app make a token under Settings → Connect a PC, then in Sync choose \"Connect to a Queueify web server\" and paste the connect text. A PC uses one or the other.", }; } diff --git a/Queueify.Core/Services/Strings.Es.cs b/Queueify.Core/Services/Strings.Es.cs index 57645fb..f65c5e7 100644 --- a/Queueify.Core/Services/Strings.Es.cs +++ b/Queueify.Core/Services/Strings.Es.cs @@ -354,5 +354,25 @@ public static partial class Loc ["tour.3"] = "Sacale una foto a una página de revista con el celular y soltala en esta ventana. Después hacé clic en el artista y el álbum.", ["tour.4.title"] = "Todas tus PC", ["tour.4"] = "Conectá Sincronizar una vez para tener la misma lista en todas tus PC. La Ayuda (F1) explica todo lo demás.", + ["webSync.setup.option"] = "Conectarme a un servidor web de Queueify", + ["webSync.setup.text"] = "En tu app web de Queueify, abrí Ajustes → Conectar una PC, creá un token y copiá el texto de conexión. Pegalo acá. Esta PC se sincroniza con ese servidor en lugar de Firebase; para cambiar después, desconectala primero.", + ["webSync.code"] = "Texto de conexión", + ["webSync.code.placeholder"] = "queueify-web|https://…", + ["webSync.bad_code"] = "Eso no parece un texto de conexión. Empieza con \"queueify-web|\" y la dirección tiene que ser https.", + ["webSync.joined"] = "Conectado. Tu lista ahora tiene {0} del servidor web.", + ["webSync.this_pc"] = "Esta PC está sincronizada con el servidor web de Queueify {0}. {1}", + ["webSync.private"] = "El token queda solo en esta PC. Para que deje de funcionar, revocalo en la app web (Ajustes → Conectar una PC).", + ["webSync.disconnected"] = "Esta PC ya no se sincroniza. Su lista queda acá; la copia del servidor no se toca.", + ["webSync.tip.at"] = "Sincronizado con el servidor web a las {0:t}", + ["webSync.tip.ok"] = "Sincronizado con el servidor web", + ["webSync.err.not_configured"] = "La dirección o el token del servidor web no son válidos. Conectate de nuevo con un texto de conexión nuevo.", + ["webSync.err.unauthorized"] = "El servidor web no aceptó el token de esta PC. Puede que lo hayan revocado: creá uno nuevo en la app web y conectate de nuevo.", + ["webSync.err.redirect"] = "El servidor web mandó a esta PC a otro lado, así que no se envió nada. Revisá la dirección del texto de conexión.", + ["webSync.err.server"] = "El servidor web tuvo un problema (error {0}). Tus cambios se conservan y se sincronizan más tarde.", + ["webSync.err.bad_reply"] = "La respuesta del servidor web no es algo que Queueify entienda. ¿La dirección es de una app web de Queueify?", + ["webSync.err.no_end"] = "El servidor web siguió mandando cambios y la sincronización se detuvo. Tus cambios se conservan; probá de nuevo más tarde.", + ["webSync.err.timeout"] = "El servidor web no respondió a tiempo. Tus cambios se sincronizan más tarde.", + ["webSync.err.offline"] = "No se puede llegar al servidor web ahora. Tus cambios se conservan y se sincronizan cuando se pueda.", + ["webSync.help"] = "En lugar de Firebase podés sincronizar con un servidor web de Queueify (el tuyo): en la app web creá un token en Ajustes → Conectar una PC, y en Sincronizar elegí \"Conectarme a un servidor web de Queueify\" y pegá el texto de conexión. Una PC usa una cosa o la otra.", }; } diff --git a/Queueify.Core/Services/SyncException.cs b/Queueify.Core/Services/SyncException.cs new file mode 100644 index 0000000..9c3bf20 --- /dev/null +++ b/Queueify.Core/Services/SyncException.cs @@ -0,0 +1,7 @@ +namespace Queueify.Services; + +/// +/// A sync problem with a message the user can act on. Messages never carry the server's answer, the +/// address or the token, so showing or logging one can't leak the connection. +/// +public sealed class SyncException(string message) : Exception(message); diff --git a/Queueify.Tests/LocTests.cs b/Queueify.Tests/LocTests.cs index 82f788d..dfa3e1f 100644 --- a/Queueify.Tests/LocTests.cs +++ b/Queueify.Tests/LocTests.cs @@ -177,16 +177,16 @@ private static string RepoRoot([CallerFilePath] string here = "") => [GeneratedRegex(@"\{(\d+)(:[^}]*)?\}")] private static partial Regex Placeholder(); - [GeneratedRegex(@"Loc\.[TF]\(""([a-z0-9_.]+)""")] + [GeneratedRegex(@"Loc\.[TF]\(""([A-Za-z0-9_.]+)""")] private static partial Regex CodeKey(); - [GeneratedRegex(@"\{l:Tr Key=([a-z0-9_.]+)\}")] + [GeneratedRegex(@"\{l:Tr Key=([A-Za-z0-9_.]+)\}")] private static partial Regex XamlKey(); - [GeneratedRegex(@"""([a-z]+\.[a-z0-9_.]+)""")] + [GeneratedRegex(@"""([a-zA-Z]+\.[A-Za-z0-9_.]+)""")] private static partial Regex KeyLike(); - [GeneratedRegex(@"\[""([a-z0-9_.]+)""\] =")] + [GeneratedRegex(@"\[""([A-Za-z0-9_.]+)""\] =")] private static partial Regex TableKey(); [GeneratedRegex(@"\.(json|db|rules|log|tmp|exe|ico|svg|png|pri|xbf)$")] diff --git a/Queueify.Tests/ServerSyncTests.cs b/Queueify.Tests/ServerSyncTests.cs new file mode 100644 index 0000000..387f98f --- /dev/null +++ b/Queueify.Tests/ServerSyncTests.cs @@ -0,0 +1,547 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Text; +using System.Text.Json; +using Microsoft.Data.Sqlite; +using Queueify.Models; +using Queueify.Services; + +namespace Queueify.Tests; + +/// The desktop side of the web sync contract (ADR-0010), against an in-memory server. +public sealed class ServerSyncTests : IDisposable +{ + private const string Token = "qw_SECRET-TOKEN-123"; + private const string Url = "https://queue.example.com"; + + private readonly string _dir = Path.Combine(Path.GetTempPath(), "queueify-tests", Guid.NewGuid().ToString("N")); + private BacklogStore NewStore() => new(Path.Combine(_dir, Guid.NewGuid().ToString("N") + ".db")); + + public void Dispose() + { + SqliteConnection.ClearAllPools(); + if (Directory.Exists(_dir)) Directory.Delete(_dir, true); + } + + private static AppSettings Connected() => new() { WebServerUrl = Url, WebToken = Token }; + + private static BacklogItem Item(string album) => new() + { + Uid = Guid.NewGuid().ToString("N"), Artist = "Charly García", Album = album, Year = 1983, + AddedAt = DateTime.Now, + }; + + private static SyncAlbum Wire(string uid, string album, DateTime updated, bool deleted = false) => + new(uid, "Spinetta", album, 1973, "Magazine", null, null, null, updated, null, -1, updated, deleted); + + /// A server that keeps rows by uid, stamps a rising serverTime and answers like ADR-0010. + private sealed class FakeServer : HttpMessageHandler + { + public readonly Dictionary Rows = []; + public SyncSettings? Settings; + public readonly List Requests = []; + public readonly List AuthHeaders = []; + public readonly List Uris = []; + public DateTime Clock = new(2026, 10, 14, 12, 0, 0, DateTimeKind.Utc); + public Func? Override; + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + Uris.Add(request.RequestUri); + AuthHeaders.Add(request.Headers.Authorization?.ToString()); + if (Override?.Invoke(request) is { } custom) return custom; + + var body = await request.Content!.ReadAsStringAsync(ct); + var req = JsonSerializer.Deserialize(body, SyncJson.Default.SyncRequest)!; + Requests.Add(req); + + Clock = Clock.AddSeconds(1); + var accepted = new HashSet(); + foreach (var a in req.Albums) + { + if (Rows.TryGetValue(a.Uid, out var have) && have.Album.UpdatedAt >= a.UpdatedAt) continue; // ties keep the server's row + Rows[a.Uid] = (a, Clock); + accepted.Add(a.Uid); + } + SyncSettings? back = null; + if (req.Settings is { } s && (Settings == null || s.UpdatedAt > Settings.UpdatedAt)) Settings = s; + else if (req.Settings == null) back = Settings; + + var since = req.Since ?? DateTime.MinValue; + var news = Rows.Values.Where(r => r.ServerTime > since && !accepted.Contains(r.Album.Uid)).Select(r => r.Album).ToList(); + var json = JsonSerializer.Serialize(new SyncResponse(Clock, news, back), SyncJson.Default.SyncResponse); + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; + } + } + + private static ServerSync Client(FakeServer server) => new(new HttpClient(server)); + + [Fact] + public async Task Happy_path_uploads_dirty_albums_downloads_others_and_stores_since() + { + var server = new FakeServer(); + var theirs = Wire("remote1", "Artaud", new DateTime(2026, 10, 10, 0, 0, 0, DateTimeKind.Utc)); + server.Rows["remote1"] = (theirs, server.Clock); + var store = NewStore(); + var mine = Item("Clics Modernos"); + store.Insert(mine); + var settings = Connected(); + + var result = await Client(server).SyncAsync(store, settings, CancellationToken.None); + + Assert.Equal(1, result.Uploaded); + Assert.Equal(1, result.Downloaded); + Assert.Contains(server.Rows.Values, r => r.Album.Album == "Clics Modernos"); + Assert.Contains(store.LoadAll(), i => i.Uid == "remote1" && i.Album == "Artaud"); + Assert.Empty(store.LoadDirty()); + Assert.Equal(server.Clock, settings.WebLastServerTime); + Assert.Equal($"Bearer {Token}", server.AuthHeaders[0]); + Assert.Equal(new Uri(Url + "/api/sync"), server.Uris[0]); + Assert.Null(server.Requests[0].Since); + } + + [Fact] + public async Task The_second_sync_asks_only_for_what_is_newer() + { + var server = new FakeServer(); + var store = NewStore(); + var settings = Connected(); + await Client(server).SyncAsync(store, settings, CancellationToken.None); + var first = settings.WebLastServerTime; + + await Client(server).SyncAsync(store, settings, CancellationToken.None); + + Assert.Equal(first, server.Requests[^1].Since); + } + + [Fact] + public async Task The_newest_change_wins_when_both_sides_edited_the_same_album() + { + var server = new FakeServer(); + var store = NewStore(); + var item = Item("Edited here"); + store.Insert(item); // updated "now" + server.Rows[item.Uid] = (Wire(item.Uid, "Server title", BacklogStore.Now().AddHours(1)), server.Clock); + + await Client(server).SyncAsync(store, Connected(), CancellationToken.None); + + Assert.Equal("Server title", store.FindByUid(item.Uid)!.Album); + Assert.Equal("Server title", server.Rows[item.Uid].Album.Album); + } + + [Fact] + public async Task A_newer_local_edit_overwrites_the_servers_row() + { + var server = new FakeServer(); + var store = NewStore(); + var item = Item("New title"); + store.Insert(item); + server.Rows[item.Uid] = (Wire(item.Uid, "Old title", new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc)), server.Clock); + + await Client(server).SyncAsync(store, Connected(), CancellationToken.None); + + Assert.Equal("New title", server.Rows[item.Uid].Album.Album); + Assert.Equal("New title", store.FindByUid(item.Uid)!.Album); + } + + [Fact] + public async Task Deletions_go_up_as_soft_rows_and_come_down_as_removals() + { + var server = new FakeServer(); + var store = NewStore(); + var gone = Item("Gone here"); + var goneThere = Item("Gone there"); + store.Insert(gone); + store.Insert(goneThere); + store.MarkUploaded(goneThere); + store.Delete(gone); + server.Rows[goneThere.Uid] = (Wire(goneThere.Uid, "Gone there", BacklogStore.Now().AddHours(1), deleted: true), server.Clock); + + await Client(server).SyncAsync(store, Connected(), CancellationToken.None); + + Assert.True(server.Rows[gone.Uid].Album.Deleted); + Assert.Null(store.FindByUid(gone.Uid)); // the uploaded deletion is removed for good + Assert.Null(store.FindByUid(goneThere.Uid)); // the other PC's deletion applied + Assert.Empty(store.LoadAll()); + } + + [Fact] + public async Task Repeats_until_the_server_has_nothing_more_and_sends_at_most_1000_albums_per_request() + { + var server = new FakeServer(); + var store = NewStore(); + for (int i = 0; i < 5; i++) store.Insert(Item("Album " + i)); + var settings = Connected(); + + var result = await new ServerSync(new HttpClient(server), maxBatch: 2).SyncAsync(store, settings, CancellationToken.None); + + Assert.Equal(5, result.Uploaded); + Assert.Equal(5, server.Rows.Count); + Assert.Equal([2, 2, 1], server.Requests.Select(r => r.Albums.Count)); + Assert.Empty(store.LoadDirty()); + } + + [Fact] + public void The_default_batch_is_the_contracts_1000() + { + Assert.Equal(1000, ServerSync.MaxBatch); + } + + [Fact] + public async Task Downloads_that_arrive_in_several_rounds_are_all_applied() + { + var server = new FakeServer(); + var calls = 0; + server.Override = _ => + { + calls++; + if (calls > 2) return null; + var album = Wire("page" + calls, "Page " + calls, new DateTime(2026, 10, 10, 0, 0, 0, DateTimeKind.Utc)); + var json = JsonSerializer.Serialize(new SyncResponse(new DateTime(2026, 10, 14, 12, 0, calls, DateTimeKind.Utc), [album], null), SyncJson.Default.SyncResponse); + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; + }; + var store = NewStore(); + + var result = await Client(server).SyncAsync(store, Connected(), CancellationToken.None); + + Assert.Equal(2, result.Downloaded); + Assert.Equal(["Page 1", "Page 2"], store.LoadAll().Select(i => i.Album).Order()); + } + + [Fact] + public async Task A_server_that_never_stops_answering_with_albums_ends_with_an_error() + { + var server = new FakeServer(); + int n = 0; + server.Override = _ => + { + var album = Wire("loop" + n++, "Loop", new DateTime(2026, 10, 10, 0, 0, 0, DateTimeKind.Utc)); + var json = JsonSerializer.Serialize(new SyncResponse(new DateTime(2026, 10, 14, 12, 0, 0, DateTimeKind.Utc), [album], null), SyncJson.Default.SyncResponse); + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; + }; + + await Assert.ThrowsAsync(() => Client(server).SyncAsync(NewStore(), Connected(), CancellationToken.None)); + } + + [Fact] + public async Task A_rejected_token_is_a_clear_message_and_changes_nothing() + { + var server = new FakeServer { Override = _ => new HttpResponseMessage(HttpStatusCode.Unauthorized) }; + var store = NewStore(); + var item = Item("Pending"); + store.Insert(item); + var settings = Connected(); + + var ex = await Assert.ThrowsAsync(() => Client(server).SyncAsync(store, settings, CancellationToken.None)); + + Assert.Equal(Loc.T("webSync.err.unauthorized"), ex.Message); + Assert.Single(store.LoadDirty()); + Assert.Null(settings.WebLastServerTime); + } + + [Fact] + public async Task A_slow_server_times_out_after_twenty_seconds_with_a_sync_exception() + { + var server = new FakeServer + { + Override = r => throw new TaskCanceledException("simulated client timeout", new TimeoutException()), + }; + + var ex = await Assert.ThrowsAsync(() => Client(server).SyncAsync(NewStore(), Connected(), CancellationToken.None)); + + Assert.Equal(Loc.T("webSync.err.timeout"), ex.Message); + Assert.Equal(TimeSpan.FromSeconds(20), ServerSync.Timeout); + } + + [Fact] + public async Task The_callers_own_cancellation_is_not_reported_as_a_timeout() + { + using var cts = new CancellationTokenSource(); + var server = new FakeServer + { + Override = r => { cts.Cancel(); throw new OperationCanceledException(cts.Token); }, + }; + + await Assert.ThrowsAnyAsync(() => Client(server).SyncAsync(NewStore(), Connected(), cts.Token)); + } + + [Theory] + [InlineData(HttpStatusCode.Redirect)] + [InlineData(HttpStatusCode.PermanentRedirect)] + [InlineData(HttpStatusCode.MovedPermanently)] + public async Task A_redirect_is_refused_and_never_followed(HttpStatusCode status) + { + var server = new FakeServer + { + Override = _ => + { + var res = new HttpResponseMessage(status); + res.Headers.Location = new Uri("https://evil.example.net/api/sync"); + return res; + }, + }; + + var ex = await Assert.ThrowsAsync(() => Client(server).SyncAsync(NewStore(), Connected(), CancellationToken.None)); + + Assert.Equal(Loc.T("webSync.err.redirect"), ex.Message); + Assert.Single(server.Uris); + } + + [Fact] + public async Task The_token_is_never_in_an_error_message() + { + string[] bodies = [$"oops {Token}", "{}", "not json"]; + foreach (var status in new[] { HttpStatusCode.Unauthorized, HttpStatusCode.InternalServerError, HttpStatusCode.BadRequest, HttpStatusCode.OK }) + foreach (var body in bodies) + { + var server = new FakeServer { Override = _ => new HttpResponseMessage(status) { Content = new StringContent(body) } }; + try { await Client(server).SyncAsync(NewStore(), Connected(), CancellationToken.None); } + catch (SyncException ex) { Assert.DoesNotContain(Token, ex.ToString()); Assert.DoesNotContain(Token, ex.Message); } + } + + var failing = new FakeServer { Override = _ => throw new HttpRequestException($"connect failed for {Token}") }; + var offline = await Assert.ThrowsAsync(() => Client(failing).SyncAsync(NewStore(), Connected(), CancellationToken.None)); + Assert.DoesNotContain(Token, offline.ToString()); + Assert.Null(offline.InnerException); + } + + [Theory] + [InlineData("http://queue.example.com")] // plain http to a remote host + [InlineData("ftp://queue.example.com")] + [InlineData("")] + public async Task Only_https_servers_are_used_nothing_is_sent_otherwise(string url) + { + var server = new FakeServer(); + + await Assert.ThrowsAsync(() => + Client(server).SyncAsync(NewStore(), new AppSettings { WebServerUrl = url, WebToken = Token }, CancellationToken.None)); + + Assert.Empty(server.Uris); + } + + [Fact] + public async Task Loopback_http_is_allowed_for_local_testing() + { + var server = new FakeServer(); + + await Client(server).SyncAsync(NewStore(), new AppSettings { WebServerUrl = "http://127.0.0.1:5000", WebToken = Token }, CancellationToken.None); + + Assert.Equal(new Uri("http://127.0.0.1:5000/api/sync"), server.Uris.Single()); + } + + [Fact] + public async Task Long_text_is_cut_at_500_characters_on_upload() + { + var server = new FakeServer(); + var store = NewStore(); + store.Insert(Item(new string('x', 900))); + + await Client(server).SyncAsync(store, Connected(), CancellationToken.None); + + Assert.Equal(500, server.Rows.Values.Single().Album.Album.Length); + } + + [Fact] + public async Task Albums_keep_every_field_through_a_round_trip_between_two_pcs() + { + var server = new FakeServer(); + var pcA = NewStore(); + var pcB = NewStore(); + var item = new BacklogItem + { + Artist = "Spinetta", Album = "Artaud", Year = 1973, Source = "Rolling Stone #3", CoverUrl = "https://c/1.jpg", + SpotifyId = "sp1", TidalId = "ti1", AddedAt = new DateTime(2026, 9, 1, 10, 0, 0, DateTimeKind.Local), + ListenedAt = new DateTime(2026, 9, 20, 22, 30, 0, DateTimeKind.Local), Rating = 4.5, + }; + pcA.Insert(item); + + await Client(server).SyncAsync(pcA, Connected(), CancellationToken.None); + await Client(server).SyncAsync(pcB, Connected(), CancellationToken.None); + + var got = pcB.FindByUid(item.Uid)!; + Assert.Equal(("Spinetta", "Artaud", 1973, "Rolling Stone #3", "https://c/1.jpg"), (got.Artist, got.Album, got.Year, got.Source, got.CoverUrl)); + Assert.Equal(("sp1", "ti1", 4.5), (got.SpotifyId, got.TidalId, got.Rating)); + Assert.Equal(item.AddedAt.ToUniversalTime(), got.AddedAt.ToUniversalTime()); + Assert.Equal(item.ListenedAt!.Value.ToUniversalTime(), got.ListenedAt!.Value.ToUniversalTime()); + Assert.False(got.Dirty); + } + + // ───────────── settings ───────────── + + [Fact] + public async Task Changed_shared_settings_go_up_once_and_other_fields_never_do() + { + var server = new FakeServer(); + var settings = Connected(); + settings.SpotifyClientId = "sid"; + settings.SpotifyClientSecret = "ssecret"; + settings.CountryCode = "ES"; + settings.SharedSettingsUpdatedAt = new DateTime(2026, 10, 14, 11, 0, 0, DateTimeKind.Utc); + settings.LastSource = "private note"; + + await Client(server).SyncAsync(NewStore(), settings, CancellationToken.None); + await Client(server).SyncAsync(NewStore(), settings, CancellationToken.None); + + Assert.Equal("sid", server.Requests[0].Settings!.SpotifyClientId); + Assert.Equal("ES", server.Requests[0].Settings!.CountryCode); + Assert.All(server.Requests.Skip(1), r => Assert.Null(r.Settings)); + var wire = JsonSerializer.Serialize(server.Requests[0], SyncJson.Default.SyncRequest); + Assert.DoesNotContain(Token, wire); + Assert.DoesNotContain("private note", wire); + } + + [Fact] + public async Task Newer_settings_from_the_server_are_applied_and_reported() + { + var server = new FakeServer + { + Settings = new SyncSettings("a", "b", "c", "d", "Spotify", "UY", new DateTime(2026, 10, 14, 9, 0, 0, DateTimeKind.Utc)), + }; + var settings = Connected(); + + var result = await Client(server).SyncAsync(NewStore(), settings, CancellationToken.None); + + Assert.True(result.SettingsChanged); + Assert.Equal(("a", "b", "c", "d", "Spotify", "UY"), + (settings.SpotifyClientId, settings.SpotifyClientSecret, settings.TidalClientId, settings.TidalClientSecret, settings.PreferredService, settings.CountryCode)); + Assert.Equal(new DateTime(2026, 10, 14, 9, 0, 0, DateTimeKind.Utc), settings.SharedSettingsUpdatedAt); + Assert.Equal(Token, settings.WebToken); + } + + [Fact] + public async Task Older_settings_from_the_server_do_not_replace_newer_ones_here() + { + var server = new FakeServer + { + Settings = new SyncSettings("old", "old", "", "", "Tidal", "AR", new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc)), + }; + var settings = Connected(); + settings.SpotifyClientId = "mine"; + settings.SharedSettingsUpdatedAt = new DateTime(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc); + settings.WebSettingsSyncedAt = settings.SharedSettingsUpdatedAt; // nothing new to send + + var result = await Client(server).SyncAsync(NewStore(), settings, CancellationToken.None); + + Assert.False(result.SettingsChanged); + Assert.Equal("mine", settings.SpotifyClientId); + } + + [Fact] + public async Task A_first_connection_with_keys_and_an_empty_server_uploads_the_keys() + { + var server = new FakeServer(); + var settings = Connected(); + settings.TidalClientId = "tid"; + settings.TidalClientSecret = "tsec"; + + await Client(server).SyncAsync(NewStore(), settings, CancellationToken.None); + + Assert.Equal("tid", server.Settings!.TidalClientId); + Assert.NotNull(settings.SharedSettingsUpdatedAt); + } + + [Fact] + public async Task A_first_connection_takes_the_servers_keys_instead_of_uploading_its_own() + { + var server = new FakeServer + { + Settings = new SyncSettings("srv", "srv", "", "", "Tidal", "AR", new DateTime(2026, 10, 14, 9, 0, 0, DateTimeKind.Utc)), + }; + var settings = Connected(); + settings.SpotifyClientId = "local"; + settings.SpotifyClientSecret = "local"; + + await Client(server).SyncAsync(NewStore(), settings, CancellationToken.None); + + Assert.Equal("srv", server.Settings!.SpotifyClientId); + Assert.Equal("srv", settings.SpotifyClientId); + } + + [Fact] + public void The_connection_belongs_to_this_pc_and_is_not_shared_with_the_others() + { + var mine = new AppSettings { WebServerUrl = Url, WebToken = Token, WebLastServerTime = DateTime.UtcNow }; + var synced = new AppSettings { SpotifyClientId = "s", SharedSettingsUpdatedAt = DateTime.UtcNow, WebToken = "other" }; + + mine.CopySharedFrom(synced); + var edited = mine.Clone(); + edited.WebToken = "changed"; + var changed = mine.ApplyEdits(mine.Clone(), edited); + + Assert.Equal(Token, mine.WebToken); + Assert.Equal(Url, mine.WebServerUrl); + Assert.False(changed); + Assert.NotNull(mine.WebLastServerTime); + Assert.Equal("changed", edited.Clone().WebToken); // Clone keeps the connection + } + + [Fact] + public void Settings_round_trip_through_settings_json_with_the_token_in_one_place_only() + { + var path = Path.Combine(_dir, "settings.json"); + Directory.CreateDirectory(_dir); + var s = Connected(); + s.WebLastServerTime = new DateTime(2026, 10, 14, 12, 0, 0, DateTimeKind.Utc); + s.SpotifyClientId = "sid"; + + AppData.SaveSettings(s, path); + var text = File.ReadAllText(path); + var back = AppData.LoadSettings(path); + + Assert.Equal(1, text.Split(Token).Length - 1); + Assert.Equal((Url, Token, s.WebLastServerTime), (back.WebServerUrl, back.WebToken, back.WebLastServerTime)); + Assert.True(back.WebConfigured); + Assert.False(back.CloudConfigured); + } + + [Fact] + public void Web_connection_needs_both_the_server_and_the_token() + { + Assert.False(new AppSettings { WebServerUrl = Url }.WebConfigured); + Assert.False(new AppSettings { WebToken = Token }.WebConfigured); + Assert.True(new AppSettings { WebServerUrl = Url, WebToken = Token }.WebConfigured); + } + + [Fact] + public void Connecting_to_one_server_replaces_the_other_provider_and_web_wins_if_both_are_set() + { + var both = new AppSettings + { + CloudProjectId = "queueify-1a2b3", CloudQueueKey = "k", CloudLastServerTime = DateTime.UtcNow, + WebServerUrl = Url, WebToken = Token, + }; + + Assert.True(both.SyncConfigured); + Assert.Equal(SyncKind.Web, both.ActiveSync); + Assert.Equal(SyncKind.Cloud, new AppSettings { CloudProjectId = "queueify-1a2b3", CloudQueueKey = "k" }.ActiveSync); + Assert.Equal(SyncKind.None, new AppSettings().ActiveSync); + + both.ConnectWeb(Url, Token); + Assert.False(both.CloudConfigured); + Assert.Null(both.CloudLastServerTime); + both.ConnectCloud("queueify-1a2b3", "k2"); + Assert.False(both.WebConfigured); + Assert.Null(both.WebLastServerTime); + Assert.Equal("", both.WebToken); + } + + [Fact] + public void Disconnecting_forgets_the_token_and_the_sync_position() + { + var s = Connected(); + s.WebLastServerTime = DateTime.UtcNow; + s.WebSettingsSyncedAt = DateTime.UtcNow; + + s.DisconnectWeb(); + + Assert.Equal(("", "", null, null), (s.WebServerUrl, s.WebToken, s.WebLastServerTime, s.WebSettingsSyncedAt)); + } + + [Fact] + public void The_providers_share_one_interface() + { + Assert.IsAssignableFrom(new ServerSync(new HttpClient())); + Assert.IsAssignableFrom(new CloudSync(new HttpClient())); + Assert.IsType(SyncProviders.For(SyncKind.Web, new CloudSync(new HttpClient()), new ServerSync(new HttpClient()))); + } +} diff --git a/Queueify/MainWindow.xaml b/Queueify/MainWindow.xaml index a295268..62d7550 100644 --- a/Queueify/MainWindow.xaml +++ b/Queueify/MainWindow.xaml @@ -637,6 +637,7 @@ + diff --git a/Queueify/MainWindow.xaml.cs b/Queueify/MainWindow.xaml.cs index 52c883e..ca6a874 100644 --- a/Queueify/MainWindow.xaml.cs +++ b/Queueify/MainWindow.xaml.cs @@ -34,6 +34,7 @@ public sealed partial class MainWindow : Window private readonly SpotifyCatalog _spotify; private readonly TidalCatalog _tidal; private readonly CloudSync _cloud; + private readonly ServerSync _web = new(CreateWebSyncClient()); private readonly Updater _updater = new(Http, UpdateSource.For(Environment.GetEnvironmentVariable("QUEUEIFY_UPDATE_SERVER"))); private bool _updating; @@ -137,6 +138,16 @@ private static HttpClient CreateHttpClient() return http; } + /// The web server gets the token, so this client never follows a redirect to another host. + private static HttpClient CreateWebSyncClient() + { + var http = new HttpClient(new SocketsHttpHandler { AllowAutoRedirect = false }) { Timeout = TimeSpan.FromSeconds(30) }; + http.DefaultRequestHeaders.UserAgent.ParseAdd("Queueify/1.0"); + return http; + } + + private ISyncProvider Provider() => SyncProviders.For(_settings.ActiveSync, _cloud, _web); + // ───────────────────────── Window & layout ───────────────────────── private void UpdateSearchStatusPanel() => @@ -1177,7 +1188,7 @@ private async Task RestartAppAsync() private void ScheduleSync() { - if (!_settings.CloudConfigured) return; + if (!_settings.SyncConfigured) return; _syncDebounce.Stop(); _syncDebounce.Start(); } @@ -1193,7 +1204,7 @@ private void ScheduleSync() /// private Task SyncNowAsync() { - if (!_settings.CloudConfigured) return Task.FromResult(null); + if (!_settings.SyncConfigured) return Task.FromResult(null); if (_syncTask is { IsCompleted: false } running) return _followUpSync ??= AfterAsync(running); return _syncTask = RunSyncAsync(); @@ -1213,14 +1224,17 @@ private void ScheduleSync() // Sync a copy: the UI thread keeps using _settings while the sync runs in the background. var work = _settings.Clone(); + var provider = Provider(); var sharedStampBefore = _settings.SharedSettingsUpdatedAt; string? error = null; try { - var result = await Task.Run(() => _cloud.SyncAsync(_store, work, CancellationToken.None)); - if (_settings.CloudQueueKey == work.CloudQueueKey) // still connected to the same queue + var result = await Task.Run(() => provider.SyncAsync(_store, work, CancellationToken.None)); + if (_settings.SyncIdentity == work.SyncIdentity) // still connected to the same queue { _settings.CloudLastServerTime = work.CloudLastServerTime; + _settings.WebLastServerTime = work.WebLastServerTime; + _settings.WebSettingsSyncedAt = work.WebSettingsSyncedAt; // Take downloaded keys/preferences unless the user saved Settings while this sync ran. bool sharedChanged = _settings.SharedSettingsUpdatedAt == sharedStampBefore && work.SharedSettingsUpdatedAt != sharedStampBefore; @@ -1254,14 +1268,14 @@ private void ScheduleSync() error = DescribeSyncError(ex); } - _syncError = _settings.CloudConfigured ? error : null; + _syncError = _settings.SyncConfigured ? error : null; UpdateSyncButton(); return error; } private static string DescribeSyncError(Exception ex) => ex switch { - CatalogException => ex.Message, + CatalogException or SyncException => ex.Message, HttpRequestException => Loc.T("sync.err.offline"), TaskCanceledException => Loc.T("sync.err.timeout"), IOException or UnauthorizedAccessException => Loc.F("sync.err.disk", ex.Message), @@ -1272,13 +1286,15 @@ private void ScheduleSync() private void UpdateSyncButton() { string label, glyph, tip; - if (!_settings.CloudConfigured) + bool web = _settings.WebConfigured; + if (!_settings.SyncConfigured) (label, glyph, tip) = (Loc.T("nav.sync"), "", Loc.T("sync.tip.off")); else if (_syncError != null) (label, glyph, tip) = (Loc.T("sync.not_synced"), "", Loc.F("sync.tip.error", _syncError)); else (label, glyph, tip) = (Loc.T("sync.synced"), "", - _lastSynced is DateTime t ? Loc.F("sync.tip.at", t) : Loc.T("sync.tip.ok")); + _lastSynced is DateTime t ? web ? Loc.F("webSync.tip.at", t) : Loc.F("sync.tip.at", t) + : web ? Loc.T("webSync.tip.ok") : Loc.T("sync.tip.ok")); SyncNav.Content = label; SyncIcon.Glyph = SettingsSyncIcon.Glyph = glyph; @@ -1289,8 +1305,12 @@ private void UpdateSyncButton() private async void OnSync(object sender, RoutedEventArgs e) { - if (_settings.CloudConfigured) await ShowSyncConnectedAsync(); - else await ShowSyncSetupAsync(); + switch (_settings.ActiveSync) + { + case SyncKind.Web: await ShowWebSyncConnectedAsync(); break; + case SyncKind.Cloud: await ShowSyncConnectedAsync(); break; + default: await ShowSyncSetupAsync(); break; + } } /// First-time setup: create the online queue (first PC) or join it with a sync code. @@ -1298,6 +1318,7 @@ private async Task ShowSyncSetupAsync() { var create = new RadioButton { Content = Loc.T("sync.setup.create"), GroupName = "sync", IsChecked = true }; var join = new RadioButton { Content = Loc.T("sync.setup.join"), GroupName = "sync" }; + var web = new RadioButton { Content = Loc.T("webSync.setup.option"), GroupName = "sync" }; var projectBox = new TextBox { Header = Loc.T("sync.project"), PlaceholderText = Loc.T("sync.project.placeholder") }; var copyRules = new Button { Content = Loc.T("sync.copy_rules") }; @@ -1319,8 +1340,19 @@ private async Task ShowSyncSetupAsync() Loc.T("sync.setup.join_text"))); joinPanel.Children.Add(codeBox); - create.Checked += (_, _) => { createPanel.Visibility = Visibility.Visible; joinPanel.Visibility = Visibility.Collapsed; }; - join.Checked += (_, _) => { createPanel.Visibility = Visibility.Collapsed; joinPanel.Visibility = Visibility.Visible; }; + var webBox = new TextBox { Header = Loc.T("webSync.code"), PlaceholderText = Loc.T("webSync.code.placeholder") }; + var webPanel = new StackPanel { Spacing = 10, Visibility = Visibility.Collapsed }; + webPanel.Children.Add(Paragraph(Loc.T("webSync.setup.text"))); + webPanel.Children.Add(webBox); + + void ShowOnly(StackPanel shown) + { + foreach (var p in new[] { createPanel, joinPanel, webPanel }) + p.Visibility = p == shown ? Visibility.Visible : Visibility.Collapsed; + } + create.Checked += (_, _) => ShowOnly(createPanel); + join.Checked += (_, _) => ShowOnly(joinPanel); + web.Checked += (_, _) => ShowOnly(webPanel); var progress = new ProgressBar { IsIndeterminate = true, Visibility = Visibility.Collapsed }; var error = new InfoBar { Severity = InfoBarSeverity.Error, IsClosable = false, IsOpen = false }; @@ -1329,8 +1361,10 @@ private async Task ShowSyncSetupAsync() panel.Children.Add(Paragraph(Loc.T("sync.setup.intro"))); panel.Children.Add(create); panel.Children.Add(join); + panel.Children.Add(web); panel.Children.Add(createPanel); panel.Children.Add(joinPanel); + panel.Children.Add(webPanel); panel.Children.Add(progress); panel.Children.Add(error); @@ -1344,15 +1378,24 @@ private async Task ShowSyncSetupAsync() XamlRoot = Root.XamlRoot, }; - bool joined = false; + bool joined = false, toWeb = false; dialog.PrimaryButtonClick += async (d, args) => { var deferral = args.GetDeferral(); try { - string project, key; - joined = join.IsChecked == true; - if (joined) + string project = "", key = "", webUrl = "", webToken = ""; + toWeb = web.IsChecked == true; + joined = toWeb || join.IsChecked == true; + if (toWeb) + { + if (!SyncConnect.TryParse(webBox.Text, out webUrl, out webToken)) + { + Fail(Loc.T("webSync.bad_code")); + return; + } + } + else if (joined) { if (!CloudSync.TryParseSyncCode(codeBox.Text, out project, out key)) { @@ -1373,9 +1416,8 @@ private async Task ShowSyncSetupAsync() // Try the connection on a copy; the live settings only change if the first sync works. var trial = _settings.Clone(); - trial.CloudProjectId = project; - trial.CloudQueueKey = key; - trial.CloudLastServerTime = null; + if (toWeb) trial.ConnectWeb(webUrl, webToken); + else trial.ConnectCloud(project, key); // Creating: this PC's keys go up. Joining: the online queue's keys win (or this PC's, // if the queue has none yet). trial.SharedSettingsUpdatedAt = joined ? null @@ -1392,7 +1434,7 @@ private async Task ShowSyncSetupAsync() if (_syncTask is { } previous) await previous; // Albums synced to an earlier queue are marked clean; this queue needs all of them. _store.MarkAllDirty(); - await Task.Run(() => _cloud.SyncAsync(_store, trial, CancellationToken.None)); + await Task.Run(() => SyncProviders.For(trial.ActiveSync, _cloud, _web).SyncAsync(_store, trial, CancellationToken.None)); } catch (Exception ex) { @@ -1434,9 +1476,11 @@ void Fail(string message) } }; - if (await ShowDialogAsync(dialog) != ContentDialogResult.Primary || !_settings.CloudConfigured) return; + if (await ShowDialogAsync(dialog) != ContentDialogResult.Primary || !_settings.SyncConfigured) return; - if (joined) + if (toWeb) + ShowToast(Loc.F("webSync.joined", QueueText.Albums(_all.Count))); + else if (joined) ShowToast(Loc.F("sync.joined", QueueText.Albums(_all.Count))); else await ShowSyncConnectedAsync(justCreated: true); @@ -1483,8 +1527,7 @@ private async Task ShowSyncConnectedAsync(bool justCreated = false) ShowToast(problem ?? Loc.T("sync.ok"), severity: problem == null ? InfoBarSeverity.Success : InfoBarSeverity.Warning); break; case ContentDialogResult.Secondary: - _settings.CloudProjectId = _settings.CloudQueueKey = ""; - _settings.CloudLastServerTime = null; + _settings.DisconnectCloud(); _syncError = null; AppData.SaveSettings(_settings); UpdateSyncButton(); @@ -1494,6 +1537,43 @@ private async Task ShowSyncConnectedAsync(bool justCreated = false) } } + /// Shows which web server this PC syncs with, plus "Sync now" and "Disconnect". + private async Task ShowWebSyncConnectedAsync() + { + // Only the host is shown; the token stays out of the window. + var host = new Uri(_settings.WebServerUrl).Authority; + var status = _syncError ?? (_lastSynced is DateTime t ? Loc.F("sync.last", t) : Loc.T("sync.ok")); + var panel = new StackPanel { Spacing = 12, Width = 480 }; + panel.Children.Add(Paragraph(Loc.F("webSync.this_pc", host, status))); + panel.Children.Add(Paragraph(Loc.T("webSync.private"))); + + var dialog = new ContentDialog + { + Title = Loc.T("sync.title"), + Content = new ScrollViewer { Content = panel, MaxHeight = 560 }, + PrimaryButtonText = Loc.T("sync.now"), + SecondaryButtonText = Loc.T("sync.disconnect"), + CloseButtonText = Loc.T("dialog.close"), + DefaultButton = ContentDialogButton.Close, + XamlRoot = Root.XamlRoot, + }; + + switch (await ShowDialogAsync(dialog)) + { + case ContentDialogResult.Primary: + var problem = await SyncNowAsync(); + ShowToast(problem ?? Loc.T("sync.ok"), severity: problem == null ? InfoBarSeverity.Success : InfoBarSeverity.Warning); + break; + case ContentDialogResult.Secondary: + _settings.DisconnectWeb(); + _syncError = null; + AppData.SaveSettings(_settings); + UpdateSyncButton(); + ShowToast(Loc.T("webSync.disconnected"), severity: InfoBarSeverity.Informational); + break; + } + } + private bool _dialogOpen; /// diff --git a/README.md b/README.md index c524be5..5e4e204 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,14 @@ Keep the sync code private: anyone who has it can see and change your queue. Som Firebase project ID can't read your queue, but could use up its free daily quota; see [SECURITY.md](SECURITY.md). If you published security rules from an earlier version, copy them again from the Sync dialog and publish them in Firebase. +**Or a Queueify web server.** If you run the web app ([ADR-0010](docs/adr/0010-web-app-and-shared-queue.md)), +make a token in its Settings → Connect a PC, click **Sync**, choose *Connect to a Queueify web server* and +paste the connect text (`queueify-web|https://…|token`). The server is then the shared queue, also for your +phone. A PC syncs with one place at a time: to switch between Firebase and a web server, disconnect first +(the queue stays on the PC and the other copy isn't touched). The token stays on that PC; revoke it in the web +app to cut that PC off. The address must be https (plain http only for `localhost`), and the app never follows a +redirect to another host. + ## Magazine photos Take the photo with your phone, get it onto the PC (Phone Link, WhatsApp Web, OneDrive…) and drop it into diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 428b54e..5f2a80d 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -15,13 +15,15 @@ flowchart LR M[Matcher] CAT[SpotifyCatalog
TidalCatalog] CS[CloudSync] + WS[ServerSync] O[OcrService
OcrLanguages] L[Loc + string tables] ST[AppData, UiState] end - MW --> S & M & CAT & CS & O & L & ST + MW --> S & M & CAT & CS & WS & O & L & ST CAT -->|HTTPS| SP[(Spotify Web API)] & TI[(Tidal Open API)] CS -->|HTTPS REST| FS[(Your Firestore)] + WS -->|HTTPS POST /api/sync| WEB[(Queueify web server)] MW --> U[Updater] -->|HTTPS| GH[(GitHub releases)] O --> WOCR[(Windows.Media.Ocr)] ``` @@ -46,6 +48,8 @@ flowchart LR | `Matcher` | Splits a typed line into text and year, merges Spotify and Tidal results, scores them. | | `SpotifyCatalog`, `TidalCatalog` | Album search with the Client Credentials flow; tokens cached per ID and secret. | | `CloudSync` | Firestore REST: uploads dirty rows, downloads rows newer than the last server time, shared settings. | +| `ServerSync` | The second provider ([ADR-0010](adr/0010-web-app-and-shared-queue.md)): one `POST /api/sync` round trip with a personal access token, repeated until nothing more comes. Same rules as `CloudSync` (newest `UpdatedAt` wins, soft deletions); HTTPS only, no redirects, 20 s per request, errors never carry the token. | +| `ISyncProvider`, `SyncProviders` | What `CloudSync` and `ServerSync` share: `SyncAsync(store, settings, ct)`. `AppSettings.ActiveSync` picks one; a PC uses one at a time and the web server wins if a hand-edited `settings.json` sets both. | | `OcrService`, `OcrLanguages` | Windows OCR on a photo; which language reads it; installing languages (elevated, allow-listed). | | `Loc`, `Strings.En/Es` | All texts, the app language and the formats that go with it. | | `AppData`, `UiState` | Where the data folder is; `settings.json` (synced settings, keys) and `ui.json` (per-PC layout, theme, language). | @@ -60,7 +64,8 @@ kept it). Copying the folder copies the queue, the keys and the sync connection. Sync: each PC keeps its own database. Online, a queue is `queues/{key}` in the user's Firestore, where the 40-hex-character key is the capability (the sync code is `queueify:{project}:{key}`). See -[ADR-0003](adr/0003-firestore-rest-sync.md). +[ADR-0003](adr/0003-firestore-rest-sync.md). Or the PC syncs with a Queueify web server instead, using +`WebServerUrl`, `WebToken` (per PC, never shared) and `WebLastServerTime` in `settings.json`. ## Startup diff --git a/docs/TESTING.md b/docs/TESTING.md index be0c89f..9f2669b 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -5,6 +5,7 @@ | Suite | Runs | Where | | --- | --- | --- | | Unit (`Queueify.Tests`) | Core logic: matching, store, sync, catalogs (fake HTTP), OCR, texts, settings | `dotnet test --project Queueify.Tests`; CI | +| Web sync client (inside the unit suite) | `ServerSync` against an in-memory server over a fake `HttpMessageHandler`: round trips, pagination, 401, timeout, redirects, token never in messages | always on | | Sync (inside the unit suite) | Two simulated PCs against the Firestore emulator, and the security rules | with `QUEUEIFY_FIRESTORE_EMULATOR`; CI | | UI (`tests\ui\Queueify.UiTests.ps1`) | The published app through UI Automation: tour, pages, panel, settings, language restart | locally, before merging UI changes | | Sync UI (`tests\ui\Queueify.SyncUiTests.ps1`) | Connecting Sync from the dialog, an album reaching Firestore | locally, with the emulator | diff --git a/docs/adr/0010-web-app-and-shared-queue.md b/docs/adr/0010-web-app-and-shared-queue.md index 991fe24..14d26c7 100644 --- a/docs/adr/0010-web-app-and-shared-queue.md +++ b/docs/adr/0010-web-app-and-shared-queue.md @@ -57,3 +57,12 @@ Deletions stay as soft rows. This is the same shape `CloudSync` already uses, so - The server needs HTTPS and a persistent data folder with backups. - Two sync providers to keep tested; the contract tests run against the in-process server. - Desktop and web share copy and string tables, so both languages stay identical. +- Desktop client (`ServerSync`, behind `ISyncProvider` with `CloudSync`): a PC syncs with **one provider at a + time**. Connecting is only offered while nothing is connected, so switching means disconnecting first; the + queue stays on the PC and the other copy is untouched. If a hand-edited `settings.json` sets both, **the web + server wins**. The token and address (`WebToken`, `WebServerUrl`) are per PC and never part of the shared + settings. The client's HTTP client does not follow redirects, a redirect or an answer from another host is + refused, requests time out after 20 s, and a 401 becomes a plain "token not accepted" message. Errors never + contain the token, the address or the server's text. Shared settings are sent only when they changed on the + PC (`WebSettingsSyncedAt` remembers the stamp already in step); a PC connecting with keys to a server that has + none uploads them, otherwise the server's keys win. From cef9cdb10a5a7756c4a3a465a56d289a4a4ca831 Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:24:09 -0300 Subject: [PATCH 05/66] feat(web): photo reading with Tesseract and encrypted secrets Co-Authored-By: Claude Sonnet 5.5 --- .gitignore | 1 + Queueify.Web.Tests/Ocr/ImageGuardTests.cs | 130 ++++++++++++++ Queueify.Web.Tests/Ocr/PhotoEndpointTests.cs | 159 +++++++++++++++++ Queueify.Web.Tests/Ocr/PhotoReaderTests.cs | 128 ++++++++++++++ .../Ocr/TessdataFetcherTests.cs | 101 +++++++++++ .../Ocr/TesseractGoldenTests.cs | 36 ++++ Queueify.Web.Tests/Ocr/TesseractTsvTests.cs | 81 +++++++++ Queueify.Web.Tests/Queueify.Web.Tests.csproj | 4 + Queueify.Web.Tests/Support/ScratchHost.cs | 48 ++++++ Queueify.Web.Tests/UserStoresSecretsTests.cs | 85 +++++++++ Queueify.Web/Ocr/ImageGuard.cs | 74 ++++++++ Queueify.Web/Ocr/OcrExtensions.cs | 100 +++++++++++ Queueify.Web/Ocr/OcrGate.cs | 32 ++++ Queueify.Web/Ocr/OcrOptions.cs | 29 ++++ Queueify.Web/Ocr/PhotoReader.cs | 47 +++++ Queueify.Web/Ocr/TessdataFetcher.cs | 68 ++++++++ Queueify.Web/Ocr/TesseractOcr.cs | 162 ++++++++++++++++++ Queueify.Web/Program.cs | 6 + Queueify.Web/Queueify.Web.csproj | 1 + .../Services/QueueifyStorageExtensions.cs | 28 +++ Queueify.Web/Storage/UserStores.cs | 58 ++++++- 21 files changed, 1373 insertions(+), 5 deletions(-) create mode 100644 Queueify.Web.Tests/Ocr/ImageGuardTests.cs create mode 100644 Queueify.Web.Tests/Ocr/PhotoEndpointTests.cs create mode 100644 Queueify.Web.Tests/Ocr/PhotoReaderTests.cs create mode 100644 Queueify.Web.Tests/Ocr/TessdataFetcherTests.cs create mode 100644 Queueify.Web.Tests/Ocr/TesseractGoldenTests.cs create mode 100644 Queueify.Web.Tests/Ocr/TesseractTsvTests.cs create mode 100644 Queueify.Web.Tests/Support/ScratchHost.cs create mode 100644 Queueify.Web.Tests/UserStoresSecretsTests.cs create mode 100644 Queueify.Web/Ocr/ImageGuard.cs create mode 100644 Queueify.Web/Ocr/OcrExtensions.cs create mode 100644 Queueify.Web/Ocr/OcrGate.cs create mode 100644 Queueify.Web/Ocr/OcrOptions.cs create mode 100644 Queueify.Web/Ocr/PhotoReader.cs create mode 100644 Queueify.Web/Ocr/TessdataFetcher.cs create mode 100644 Queueify.Web/Ocr/TesseractOcr.cs create mode 100644 Queueify.Web/Services/QueueifyStorageExtensions.cs diff --git a/.gitignore b/.gitignore index 3707cef..faf6791 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ publish/ .vs/ .cache/ dist/ +Queueify.Web/App_Data/ diff --git a/Queueify.Web.Tests/Ocr/ImageGuardTests.cs b/Queueify.Web.Tests/Ocr/ImageGuardTests.cs new file mode 100644 index 0000000..7fdcbfb --- /dev/null +++ b/Queueify.Web.Tests/Ocr/ImageGuardTests.cs @@ -0,0 +1,130 @@ +using System.Text; +using Queueify.Web.Ocr; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Formats.Jpeg; +using SixLabors.ImageSharp.Formats.Png; +using SixLabors.ImageSharp.Formats.Webp; +using SixLabors.ImageSharp.PixelFormats; + +namespace Queueify.Web.Tests.Ocr; + +public class ImageGuardTests +{ + private static readonly OcrOptions Defaults = new(); + + private static byte[] Picture(int w, int h, string format = "png") + { + using var image = new Image(w, h, new Rgb24(200, 30, 30)); + using var ms = new MemoryStream(); + switch (format) + { + case "jpeg": image.SaveAsJpeg(ms); break; + case "webp": image.SaveAsWebp(ms); break; + default: image.SaveAsPng(ms); break; + } + return ms.ToArray(); + } + + private static PhotoProblem ProblemOf(byte[] bytes, OcrOptions? options = null) => + Assert.Throws(() => ImageGuard.Prepare(new MemoryStream(bytes), options ?? Defaults)).Problem; + + [Theory] + [InlineData("png")] + [InlineData("jpeg")] + [InlineData("webp")] + public void Real_pictures_are_re_encoded_as_png(string format) + { + var prepared = ImageGuard.Prepare(new MemoryStream(Picture(40, 30, format)), Defaults); + + Assert.Equal((40, 30), (prepared.Width, prepared.Height)); + Assert.Equal(new byte[] { 0x89, 0x50, 0x4E, 0x47 }, prepared.Png[..4]); + } + + [Fact] + public void Metadata_such_as_GPS_does_not_survive_the_re_encode() + { + using var image = new Image(20, 20); + image.Metadata.ExifProfile = new SixLabors.ImageSharp.Metadata.Profiles.Exif.ExifProfile(); + image.Metadata.ExifProfile.SetValue(SixLabors.ImageSharp.Metadata.Profiles.Exif.ExifTag.Make, "SecretCamera"); + using var jpeg = new MemoryStream(); + image.SaveAsJpeg(jpeg); + Assert.Contains("SecretCamera", Encoding.Latin1.GetString(jpeg.ToArray())); // the test input does carry it + + var prepared = ImageGuard.Prepare(new MemoryStream(jpeg.ToArray()), Defaults); + + Assert.DoesNotContain("SecretCamera", Encoding.Latin1.GetString(prepared.Png)); + Assert.Null(Image.Load(prepared.Png).Metadata.ExifProfile); + } + + [Fact] + public void A_big_photo_is_scaled_down_keeping_its_shape() + { + var prepared = ImageGuard.Prepare(new MemoryStream(Picture(4000, 2000)), new OcrOptions { MaxSide = 1000 }); + Assert.Equal((1000, 500), (prepared.Width, prepared.Height)); + } + + [Fact] + public void A_small_photo_is_not_enlarged() + { + var prepared = ImageGuard.Prepare(new MemoryStream(Picture(300, 200)), new OcrOptions { MaxSide = 1000 }); + Assert.Equal((300, 200), (prepared.Width, prepared.Height)); + } + + [Fact] + public void A_phone_photo_stored_rotated_is_turned_upright() + { + using var image = new Image(60, 20); + image.Metadata.ExifProfile = new SixLabors.ImageSharp.Metadata.Profiles.Exif.ExifProfile(); + image.Metadata.ExifProfile.SetValue(SixLabors.ImageSharp.Metadata.Profiles.Exif.ExifTag.Orientation, (ushort)6); // rotate 90 clockwise + using var jpeg = new MemoryStream(); + image.SaveAsJpeg(jpeg); + + var prepared = ImageGuard.Prepare(new MemoryStream(jpeg.ToArray()), Defaults); + + Assert.Equal((20, 60), (prepared.Width, prepared.Height)); + } + + [Fact] + public void Text_pretending_to_be_a_picture_is_refused() => + Assert.Equal(PhotoProblem.NotAnImage, ProblemOf(Encoding.UTF8.GetBytes(""))); + + [Fact] + public void An_svg_is_refused() => + Assert.Equal(PhotoProblem.NotAnImage, ProblemOf(Encoding.UTF8.GetBytes(""))); + + [Fact] + public void A_gif_or_bmp_is_refused_because_only_photo_formats_are_taken() + { + Assert.Equal(PhotoProblem.NotAnImage, ProblemOf(Encoding.ASCII.GetBytes("GIF89a").Concat(new byte[40]).ToArray())); + Assert.Equal(PhotoProblem.NotAnImage, ProblemOf(Encoding.ASCII.GetBytes("BM").Concat(new byte[60]).ToArray())); + } + + [Fact] + public void An_empty_upload_is_refused() => Assert.Equal(PhotoProblem.NotAnImage, ProblemOf([])); + + [Fact] + public void A_truncated_picture_is_corrupt_not_a_crash() + { + var png = Picture(200, 200); + Assert.Equal(PhotoProblem.Corrupt, ProblemOf(png[..(png.Length / 2)])); + } + + [Fact] + public void Too_many_bytes_are_refused_before_anything_is_decoded() => + Assert.Equal(PhotoProblem.TooLarge, ProblemOf(Picture(100, 100), new OcrOptions { MaxBytes = 50 })); + + [Fact] + public void A_picture_with_too_many_pixels_is_refused_from_its_header_alone() + { + // 100x100 is small in bytes but over this pixel budget: the guard reads the size without decoding. + Assert.Equal(PhotoProblem.TooManyPixels, ProblemOf(Picture(100, 100), new OcrOptions { MaxPixels = 5_000 })); + } + + [Fact] + public void The_input_stream_is_left_to_the_caller() + { + var input = new MemoryStream(Picture(10, 10)); + ImageGuard.Prepare(input, Defaults); + Assert.True(input.CanRead); + } +} diff --git a/Queueify.Web.Tests/Ocr/PhotoEndpointTests.cs b/Queueify.Web.Tests/Ocr/PhotoEndpointTests.cs new file mode 100644 index 0000000..61af090 --- /dev/null +++ b/Queueify.Web.Tests/Ocr/PhotoEndpointTests.cs @@ -0,0 +1,159 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Queueify.Services; +using Queueify.Web.Ocr; +using Queueify.Web.Tests.Support; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.PixelFormats; + +namespace Queueify.Web.Tests.Ocr; + +public sealed class PhotoEndpointTests : IClassFixture>, IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "qw-" + Guid.NewGuid().ToString("N")); + private readonly WebApplicationFactory _factory; + private readonly List _seen = []; + + public PhotoEndpointTests(WebApplicationFactory factory) => + _factory = ScratchHost.On(factory, _root, services => + { + services.RemoveAll(); + services.AddSingleton(new Fake(_seen)); + services.RemoveAll(); + services.AddSingleton(new OcrOptions { MaxBytes = 200_000, MaxPixels = 1_000_000 }); + }); + + public void Dispose() { try { Directory.Delete(_root, true); } catch (IOException) { } } + + private sealed class Fake(List seen) : IOcr + { + public Task RecognizeAsync(Stream image, string language, CancellationToken ct = default) + { + using var ms = new MemoryStream(); + image.CopyTo(ms); + seen.Add(ms.ToArray()); + return Task.FromResult(new OcrReading([new OcrTextLine("SPINETTA JADE", new OcrBox(5, 6, 70, 8))], 100, 50, language)); + } + } + + private static byte[] Png(int w = 100, int h = 50) + { + using var image = new Image(w, h); + using var ms = new MemoryStream(); + image.SaveAsPng(ms); + return ms.ToArray(); + } + + private static ByteArrayContent Body(byte[] bytes, string type = "image/png") + { + var c = new ByteArrayContent(bytes); + c.Headers.ContentType = new(type); + return c; + } + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + [Fact] + public async Task A_signed_in_user_gets_the_lines_with_their_boxes() + { + var response = await _factory.ClientFor("alice").PostAsync("/api/photo?lang=es", Body(Png()), Ct); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("no-store", response.Headers.CacheControl!.ToString()); + using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync(Ct)); + Assert.Equal(100, json.RootElement.GetProperty("width").GetInt32()); + var line = json.RootElement.GetProperty("lines")[0]; + Assert.Equal("SPINETTA JADE", line.GetProperty("text").GetString()); + Assert.Equal(70, line.GetProperty("width").GetDouble()); + Assert.Equal("es", json.RootElement.GetProperty("language").GetString()); + } + + [Fact] + public async Task Nobody_signed_in_is_told_so_not_redirected_to_a_page() + { + var response = await _factory.ClientFor(null).PostAsync("/api/photo", Body(Png()), Ct); + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Empty(_seen); + } + + [Fact] + public async Task A_form_post_from_another_site_cannot_use_a_users_cookie() + { + // A browser form can only send these types; only fetch with a picture type needs CORS approval. + var form = new FormUrlEncodedContent([new("a", "b")]); + var response = await _factory.ClientFor("alice").PostAsync("/api/photo", form, Ct); + Assert.Equal(HttpStatusCode.UnsupportedMediaType, response.StatusCode); + Assert.Empty(_seen); + } + + [Fact] + public async Task A_page_sent_as_a_png_is_refused_by_what_it_really_is() + { + var response = await _factory.ClientFor("alice").PostAsync("/api/photo", Body("hi"u8.ToArray()), Ct); + Assert.Equal(HttpStatusCode.UnsupportedMediaType, response.StatusCode); + Assert.Equal("notAnImage", (await response.Content.ReadFromJsonAsync(Ct)).GetProperty("error").GetString()); + Assert.Empty(_seen); + } + + [Fact] + public async Task An_upload_over_the_size_limit_is_refused_without_being_read() + { + var response = await _factory.ClientFor("alice").PostAsync("/api/photo", Body(new byte[300_000]), Ct); + Assert.Equal(HttpStatusCode.RequestEntityTooLarge, response.StatusCode); + Assert.Equal("tooLarge", (await response.Content.ReadFromJsonAsync(Ct)).GetProperty("error").GetString()); + } + + [Fact] + public async Task A_chunked_upload_without_a_length_is_capped_too() + { + var content = new StreamContent(new MemoryStream(new byte[300_000])); + content.Headers.ContentType = new("image/png"); + var request = new HttpRequestMessage(HttpMethod.Post, "/api/photo") { Content = content }; + request.Headers.TransferEncodingChunked = true; + request.Headers.Add(HeaderUserAuthHandler.Header, "alice"); + + var response = await _factory.CreateClient().SendAsync(request, Ct); + + Assert.Equal(HttpStatusCode.RequestEntityTooLarge, response.StatusCode); + } + + [Fact] + public async Task A_picture_with_too_many_pixels_is_refused() + { + var response = await _factory.ClientFor("alice").PostAsync("/api/photo", Body(Png(1200, 1200)), Ct); + Assert.Equal(HttpStatusCode.RequestEntityTooLarge, response.StatusCode); + Assert.Equal("tooManyPixels", (await response.Content.ReadFromJsonAsync(Ct)).GetProperty("error").GetString()); + } + + [Theory] + [InlineData("fr")] + [InlineData("spa+eng;id")] + public async Task An_unknown_language_is_a_bad_request(string lang) + { + var response = await _factory.ClientFor("alice").PostAsync("/api/photo?lang=" + Uri.EscapeDataString(lang), Body(Png()), Ct); + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + [Fact] + public async Task The_engine_gets_a_fresh_png_not_the_upload() + { + var upload = Png(); + await _factory.ClientFor("alice").PostAsync("/api/photo", Body(upload), Ct); + + var passed = Assert.Single(_seen); + Assert.Equal(new byte[] { 0x89, 0x50, 0x4E, 0x47 }, passed[..4]); + } + + [Fact] + public async Task Nothing_is_left_on_disk_after_a_photo() + { + await _factory.ClientFor("alice").PostAsync("/api/photo", Body(Png()), Ct); + + var files = Directory.Exists(_root) ? Directory.GetFiles(_root, "*", SearchOption.AllDirectories) : []; + Assert.DoesNotContain(files, f => f.EndsWith(".png", StringComparison.OrdinalIgnoreCase) || f.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase)); + } +} diff --git a/Queueify.Web.Tests/Ocr/PhotoReaderTests.cs b/Queueify.Web.Tests/Ocr/PhotoReaderTests.cs new file mode 100644 index 0000000..d806902 --- /dev/null +++ b/Queueify.Web.Tests/Ocr/PhotoReaderTests.cs @@ -0,0 +1,128 @@ +using Queueify.Services; +using Queueify.Web.Ocr; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.PixelFormats; + +namespace Queueify.Web.Tests.Ocr; + +public class PhotoReaderTests +{ + private sealed class FakeOcr(Func>? run = null) : IOcr + { + public List<(byte[] Bytes, string Language)> Calls { get; } = []; + public async Task RecognizeAsync(Stream image, string language, CancellationToken ct = default) + { + using var copy = new MemoryStream(); + await image.CopyToAsync(copy, ct); + Calls.Add((copy.ToArray(), language)); + if (run is not null) return await run(image, language, ct); + return new OcrReading([new OcrTextLine("SPINETTA JADE", new OcrBox(1, 2, 3, 4))], 20, 10, "Español"); + } + } + + private static MemoryStream Photo(int w = 20, int h = 10) + { + using var image = new Image(w, h); + var ms = new MemoryStream(); + image.SaveAsPng(ms); + ms.Position = 0; + return ms; + } + + private static PhotoReader Reader(IOcr ocr, OcrOptions? options = null) => + new(ocr, new OcrGate(options ?? new OcrOptions()), options ?? new OcrOptions()); + + [Fact] + public async Task The_engine_gets_the_clean_png_and_the_language_the_user_chose() + { + var ocr = new FakeOcr(); + var reading = await Reader(ocr).ReadAsync("alice", Photo(), "es", TestContext.Current.CancellationToken); + + var call = Assert.Single(ocr.Calls); + Assert.Equal("es", call.Language); + Assert.Equal(new byte[] { 0x89, 0x50, 0x4E, 0x47 }, call.Bytes[..4]); + Assert.Equal("SPINETTA JADE", Assert.Single(reading.Lines).Text); + } + + [Fact] + public async Task A_file_that_is_not_a_picture_never_reaches_the_engine() + { + var ocr = new FakeOcr(); + await Assert.ThrowsAsync(() => Reader(ocr).ReadAsync("alice", new MemoryStream("hello"u8.ToArray()), "auto", TestContext.Current.CancellationToken)); + Assert.Empty(ocr.Calls); + } + + [Fact] + public async Task A_second_photo_from_the_same_user_is_turned_away_while_the_first_is_read() + { + var release = new TaskCompletionSource(); + var started = new TaskCompletionSource(); + var ocr = new FakeOcr(async (_, _, _) => { started.TrySetResult(); await release.Task; return new OcrReading([], 1, 1, "x"); }); + var reader = Reader(ocr); + + var first = reader.ReadAsync("alice", Photo(), "auto", TestContext.Current.CancellationToken); + await started.Task; + + var ex = await Assert.ThrowsAsync(() => reader.ReadAsync("alice", Photo(), "auto", TestContext.Current.CancellationToken)); + Assert.Equal(PhotoProblem.Busy, ex.Problem); + + // alice can go again once the first is done + release.SetResult(); + await first; + await reader.ReadAsync("alice", Photo(), "auto", TestContext.Current.CancellationToken); + } + + [Fact] + public async Task The_server_wide_limit_applies_across_users() + { + var release = new TaskCompletionSource(); + var started = new TaskCompletionSource(); + var ocr = new FakeOcr(async (_, _, _) => { started.TrySetResult(); await release.Task; return new OcrReading([], 1, 1, "x"); }); + var options = new OcrOptions { MaxConcurrent = 1 }; + var reader = Reader(ocr, options); + + var first = reader.ReadAsync("alice", Photo(), "auto", TestContext.Current.CancellationToken); + await started.Task; + + var ex = await Assert.ThrowsAsync(() => reader.ReadAsync("bob", Photo(), "auto", TestContext.Current.CancellationToken)); + Assert.Equal(PhotoProblem.Busy, ex.Problem); + release.SetResult(); + await first; + } + + [Fact] + public async Task A_reader_that_takes_too_long_is_stopped_and_the_slot_is_freed() + { + var ocr = new FakeOcr(async (_, _, ct) => { await Task.Delay(Timeout.Infinite, ct); return null!; }); + var reader = Reader(ocr, new OcrOptions { Timeout = TimeSpan.FromMilliseconds(100) }); + + var ex = await Assert.ThrowsAsync(() => reader.ReadAsync("alice", Photo(), "auto", TestContext.Current.CancellationToken)); + Assert.Equal(PhotoProblem.Timeout, ex.Problem); + + var again = Reader(new FakeOcr(), new OcrOptions()); // a fresh gate: the point is the first one released theirs + await again.ReadAsync("alice", Photo(), "auto", TestContext.Current.CancellationToken); + } + + [Fact] + public async Task The_slot_is_freed_after_an_error_so_the_user_can_retry() + { + var calls = 0; + var ocr = new FakeOcr((_, _, _) => ++calls == 1 ? throw new PhotoException(PhotoProblem.EngineMissing) : Task.FromResult(new OcrReading([], 1, 1, "x"))); + var reader = Reader(ocr); + + await Assert.ThrowsAsync(() => reader.ReadAsync("alice", Photo(), "auto", TestContext.Current.CancellationToken)); + await reader.ReadAsync("alice", Photo(), "auto", TestContext.Current.CancellationToken); + } + + [Fact] + public async Task Absurdly_many_or_long_lines_from_the_engine_are_trimmed() + { + var lines = Enumerable.Range(0, 1000).Select(i => new OcrTextLine(new string('x', 5000), new OcrBox(0, i, 1, 1))).ToList(); + var ocr = new FakeOcr((_, _, _) => Task.FromResult(new OcrReading(lines, 20, 10, "x"))); + + var reading = await Reader(ocr).ReadAsync("alice", Photo(), "auto", TestContext.Current.CancellationToken); + + Assert.Equal(PhotoReader.MaxLines, reading.Lines.Count); + Assert.All(reading.Lines, l => Assert.Equal(PhotoReader.MaxLineLength, l.Text.Length)); + } +} diff --git a/Queueify.Web.Tests/Ocr/TessdataFetcherTests.cs b/Queueify.Web.Tests/Ocr/TessdataFetcherTests.cs new file mode 100644 index 0000000..19afdbd --- /dev/null +++ b/Queueify.Web.Tests/Ocr/TessdataFetcherTests.cs @@ -0,0 +1,101 @@ +using System.Net; +using System.Security.Cryptography; +using Queueify.Web.Ocr; + +namespace Queueify.Web.Tests.Ocr; + +public sealed class TessdataFetcherTests : IDisposable +{ + private readonly string _dir = Path.Combine(Path.GetTempPath(), "qt-" + Guid.NewGuid().ToString("N")); + public void Dispose() { try { Directory.Delete(_dir, true); } catch (IOException) { } } + + private sealed class FakeHandler(Func serve) : HttpMessageHandler + { + public List Requests { get; } = []; + protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + Requests.Add(request.RequestUri!); + return Task.FromResult(serve(request.RequestUri!) is { } body + ? new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(body) } + : new HttpResponseMessage(HttpStatusCode.NotFound)); + } + } + + private static string Sha(byte[] b) => Convert.ToHexString(SHA256.HashData(b)); + + private static readonly byte[] Spa = "spanish model"u8.ToArray(); + private static readonly byte[] Eng = "english model"u8.ToArray(); + + private (TessdataFetcher Fetcher, FakeHandler Handler) Make(Func? serve = null, string configured = "") + { + var handler = new FakeHandler(serve ?? (u => u.AbsolutePath.EndsWith("spa.traineddata") ? Spa : Eng)); + var files = new[] { new TessdataFile("spa", "https://example.test/spa.traineddata", Sha(Spa)), new TessdataFile("eng", "https://example.test/eng.traineddata", Sha(Eng)) }; + return (new TessdataFetcher(new HttpClient(handler), _dir, configured, files), handler); + } + + [Fact] + public async Task Downloads_both_languages_once_and_returns_the_folder() + { + var (fetcher, handler) = Make(); + + Assert.Equal(_dir, await fetcher.EnsureAsync(TestContext.Current.CancellationToken)); + Assert.Equal(Spa, await File.ReadAllBytesAsync(Path.Combine(_dir, "spa.traineddata"), TestContext.Current.CancellationToken)); + Assert.Equal(2, handler.Requests.Count); + + await fetcher.EnsureAsync(TestContext.Current.CancellationToken); + Assert.Equal(2, handler.Requests.Count); + } + + [Fact] + public async Task A_download_whose_checksum_differs_is_never_kept() + { + var (fetcher, _) = Make(u => "tampered"u8.ToArray()); + + await Assert.ThrowsAsync(() => fetcher.EnsureAsync(TestContext.Current.CancellationToken)); + + Assert.Empty(Directory.Exists(_dir) ? Directory.GetFiles(_dir) : []); + } + + [Fact] + public async Task A_failed_download_is_retried_on_the_next_call() + { + var up = false; + var (fetcher, _) = Make(u => up ? (u.AbsolutePath.EndsWith("spa.traineddata") ? Spa : Eng) : null); + + await Assert.ThrowsAsync(() => fetcher.EnsureAsync(TestContext.Current.CancellationToken)); + up = true; + Assert.Equal(_dir, await fetcher.EnsureAsync(TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task A_damaged_local_copy_is_replaced() + { + Directory.CreateDirectory(_dir); + await File.WriteAllTextAsync(Path.Combine(_dir, "spa.traineddata"), "corrupt", TestContext.Current.CancellationToken); + var (fetcher, _) = Make(); + + await fetcher.EnsureAsync(TestContext.Current.CancellationToken); + + Assert.Equal(Spa, await File.ReadAllBytesAsync(Path.Combine(_dir, "spa.traineddata"), TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task An_administrators_folder_is_used_as_it_is_and_nothing_is_downloaded() + { + var (fetcher, handler) = Make(configured: "/srv/tessdata"); + + Assert.Equal("/srv/tessdata", await fetcher.EnsureAsync(TestContext.Current.CancellationToken)); + Assert.Empty(handler.Requests); + } + + [Fact] + public void The_pinned_downloads_come_from_tessdata_fast_with_a_checksum() + { + Assert.All(TessdataFetcher.Pinned, f => + { + Assert.StartsWith("https://raw.githubusercontent.com/tesseract-ocr/tessdata_fast/", f.Url); + Assert.Equal(64, f.Sha256.Length); + }); + Assert.Equal(["spa", "eng"], TessdataFetcher.Pinned.Select(f => f.Language)); + } +} diff --git a/Queueify.Web.Tests/Ocr/TesseractGoldenTests.cs b/Queueify.Web.Tests/Ocr/TesseractGoldenTests.cs new file mode 100644 index 0000000..36615ef --- /dev/null +++ b/Queueify.Web.Tests/Ocr/TesseractGoldenTests.cs @@ -0,0 +1,36 @@ +using Microsoft.Extensions.Logging.Abstractions; +using Queueify.Services; +using Queueify.Web.Ocr; + +namespace Queueify.Web.Tests.Ocr; + +/// +/// The real engine on the same magazine page the desktop test reads. Needs the tesseract program and the +/// models offline: QUEUEIFY_TESSERACT is the program, QUEUEIFY_TESSDATA the folder with spa and eng. +/// +public class TesseractGoldenTests +{ + [Fact] + public async Task Reads_the_lines_of_the_magazine_page_with_their_boxes() + { + var exe = Environment.GetEnvironmentVariable("QUEUEIFY_TESSERACT"); + var data = Environment.GetEnvironmentVariable("QUEUEIFY_TESSDATA"); + Assert.SkipWhen(exe is not { Length: > 0 } || !File.Exists(exe) || data is not { Length: > 0 } || !File.Exists(Path.Combine(data, "spa.traineddata")), + "Set QUEUEIFY_TESSERACT to the tesseract program and QUEUEIFY_TESSDATA to a folder with spa.traineddata and eng.traineddata."); + + var options = new OcrOptions { TesseractPath = exe!, TessdataPath = data! }; + var ocr = new TesseractOcr(options, new TessdataFetcher(new HttpClient(), "unused", data!), NullLogger.Instance); + var reader = new PhotoReader(ocr, new OcrGate(options), options); + await using var photo = File.OpenRead(Path.Combine(AppContext.BaseDirectory, "TestData", "magazine-page.png")); + + var reading = await reader.ReadAsync("golden", photo, "auto", TestContext.Current.CancellationToken); + + var lines = reading.Lines.Select(l => l.Text).ToList(); + Assert.Contains("Clics modernos (Interdisc, 1983)", lines); + Assert.Contains("SPINETTA JADE", lines); + Assert.Contains("Año: 1983 - Sello: EMI", lines); + Assert.Equal((1600, 1000), (reading.Width, reading.Height)); + Assert.All(reading.Lines, l => Assert.True(l.Bounds.Width > 0 && l.Bounds.Height > 0 && l.Bounds.X + l.Bounds.Width <= 1600)); + Assert.Equal(("Charly García", (int?)null), OcrService.CleanLine(lines.First(l => l.StartsWith("CHARLY")))); + } +} diff --git a/Queueify.Web.Tests/Ocr/TesseractTsvTests.cs b/Queueify.Web.Tests/Ocr/TesseractTsvTests.cs new file mode 100644 index 0000000..618f30a --- /dev/null +++ b/Queueify.Web.Tests/Ocr/TesseractTsvTests.cs @@ -0,0 +1,81 @@ +using Queueify.Web.Ocr; + +namespace Queueify.Web.Tests.Ocr; + +public class TesseractTsvTests +{ + private const string Header = "level\tpage_num\tblock_num\tpar_num\tline_num\tword_num\tleft\ttop\twidth\theight\tconf\ttext\n"; + + private static string Row(int level, int block, int par, int line, int word, int l, int t, int w, int h, double conf, string text) => + $"{level}\t1\t{block}\t{par}\t{line}\t{word}\t{l}\t{t}\t{w}\t{h}\t{conf.ToString(System.Globalization.CultureInfo.InvariantCulture)}\t{text}\n"; + + [Fact] + public void Lines_come_with_their_words_joined_and_their_boxes() + { + var tsv = Header + + Row(1, 0, 0, 0, 0, 0, 0, 1600, 1000, -1, "") + + Row(4, 1, 1, 1, 0, 72, 70, 505, 50, -1, "") + + Row(5, 1, 1, 1, 1, 72, 80, 248, 40, 96.2, "CHARLY") + + Row(5, 1, 1, 1, 2, 343, 70, 234, 50, 96.4, "GARCÍA") + + Row(4, 1, 1, 2, 0, 69, 147, 593, 37, -1, "") + + Row(5, 1, 1, 2, 1, 69, 147, 83, 30, 91.9, "Clics"); + + var reading = TesseractOcr.ParseTsv(tsv, "Español + English"); + + Assert.Equal((1600, 1000), (reading.Width, reading.Height)); + Assert.Equal("Español + English", reading.Language); + Assert.Collection(reading.Lines, + l => { Assert.Equal("CHARLY GARCÍA", l.Text); Assert.Equal(new(72, 70, 505, 50), l.Bounds); }, + l => { Assert.Equal("Clics", l.Text); Assert.Equal(new(69, 147, 593, 37), l.Bounds); }); + } + + [Fact] + public void Blank_words_and_lines_without_words_are_dropped() + { + var tsv = Header + + Row(1, 0, 0, 0, 0, 0, 0, 100, 100, -1, "") + + Row(4, 1, 1, 1, 0, 5, 5, 50, 10, -1, "") + + Row(5, 1, 1, 1, 1, 5, 5, 50, 10, 90, " ") + + Row(4, 1, 1, 2, 0, 5, 20, 50, 10, -1, "") + + Row(5, 1, 1, 2, 1, 5, 20, 50, 10, -1, "ghost"); // conf -1: the engine isn't sure there's a word + + Assert.Empty(TesseractOcr.ParseTsv(tsv, "x").Lines); + } + + [Fact] + public void Garbage_output_gives_an_empty_reading_instead_of_throwing() + { + var reading = TesseractOcr.ParseTsv("not\ttsv\nat all\n1\t2", "x"); + Assert.Empty(reading.Lines); + } + + [Fact] + public void Text_with_odd_characters_survives() + { + var tsv = Header + Row(1, 0, 0, 0, 0, 0, 0, 10, 10, -1, "") + Row(4, 1, 1, 1, 0, 0, 0, 9, 9, -1, "") + + Row(5, 1, 1, 1, 1, 0, 0, 9, 9, 80, "ñandú\""); + Assert.Equal("ñandú\"", TesseractOcr.ParseTsv(tsv, "x").Lines.Single().Text); + } + + [Theory] + [InlineData("auto", "spa+eng")] + [InlineData("es", "spa")] + [InlineData("en", "eng")] + public void The_language_choices_map_to_tesseract_languages(string choice, string expected) => + Assert.Equal(expected, TesseractOcr.LanguagesFor(choice)); + + [Theory] + [InlineData("spa+eng; rm -rf /")] + [InlineData("../../etc")] + [InlineData("fr")] + [InlineData("")] + public void Nothing_else_reaches_the_command_line(string choice) => + Assert.Throws(() => TesseractOcr.LanguagesFor(choice)); + + [Fact] + public void The_arguments_read_stdin_and_write_tsv_without_any_file() + { + var args = TesseractOcr.ArgumentsFor("spa", "/data/tessdata"); + Assert.Equal(["stdin", "stdout", "--tessdata-dir", "/data/tessdata", "-l", "spa", "-c", "tessedit_create_tsv=1"], args); + } +} diff --git a/Queueify.Web.Tests/Queueify.Web.Tests.csproj b/Queueify.Web.Tests/Queueify.Web.Tests.csproj index e5094f2..5ee8d10 100644 --- a/Queueify.Web.Tests/Queueify.Web.Tests.csproj +++ b/Queueify.Web.Tests/Queueify.Web.Tests.csproj @@ -18,6 +18,10 @@ + + + + diff --git a/Queueify.Web.Tests/Support/ScratchHost.cs b/Queueify.Web.Tests/Support/ScratchHost.cs new file mode 100644 index 0000000..4bd140d --- /dev/null +++ b/Queueify.Web.Tests/Support/ScratchHost.cs @@ -0,0 +1,48 @@ +using System.Security.Claims; +using System.Text.Encodings.Web; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +namespace Queueify.Web.Tests.Support; + +/// Signs a request in as the user named by its X-Test-User header, with no cookies or passwords. +public sealed class HeaderUserAuthHandler(IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder) + : AuthenticationHandler(options, logger, encoder) +{ + public const string Scheme = "HeaderUser"; + public const string Header = "X-Test-User"; + + protected override Task HandleAuthenticateAsync() + { + if (!Request.Headers.TryGetValue(Header, out var user) || user.Count == 0) return Task.FromResult(AuthenticateResult.NoResult()); + var identity = new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, user.ToString()), new Claim(ClaimTypes.Name, user.ToString() + "@example.test")], Scheme); + return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), Scheme))); + } +} + +/// The web app on a scratch data folder, with header-based sign-in and any services swapped. +public static class ScratchHost +{ + public static WebApplicationFactory On(WebApplicationFactory factory, string dataRoot, Action? swap = null) => + factory.WithWebHostBuilder(builder => + { + builder.UseSetting("Queueify:DataRoot", dataRoot); + builder.ConfigureTestServices(services => + { + services.AddAuthentication(o => o.DefaultScheme = HeaderUserAuthHandler.Scheme) + .AddScheme(HeaderUserAuthHandler.Scheme, _ => { }); + swap?.Invoke(services); + }); + }); + + public static HttpClient ClientFor(this WebApplicationFactory host, string? user) + { + var client = host.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); + if (user is not null) client.DefaultRequestHeaders.Add(HeaderUserAuthHandler.Header, user); + return client; + } +} diff --git a/Queueify.Web.Tests/UserStoresSecretsTests.cs b/Queueify.Web.Tests/UserStoresSecretsTests.cs new file mode 100644 index 0000000..ca75b96 --- /dev/null +++ b/Queueify.Web.Tests/UserStoresSecretsTests.cs @@ -0,0 +1,85 @@ +using Microsoft.AspNetCore.DataProtection; +using Queueify.Models; +using Queueify.Web.Storage; + +namespace Queueify.Web.Tests; + +public sealed class UserStoresSecretsTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "qw-" + Guid.NewGuid().ToString("N")); + private readonly IDataProtector _protector = new EphemeralDataProtectionProvider().CreateProtector("test"); + public void Dispose() { try { Directory.Delete(_root, true); } catch (IOException) { } } + + private string SettingsFile => Path.Combine(_root, "alice", "settings.json"); + + [Fact] + public void Client_secrets_are_encrypted_on_disk_and_come_back_readable() + { + var stores = new UserStores(_root, _protector); + stores.SaveSettings("alice", new AppSettings { SpotifyClientId = "sid", SpotifyClientSecret = "spot-s3cret", TidalClientSecret = "tidal-s3cret" }); + + var onDisk = File.ReadAllText(SettingsFile); + Assert.DoesNotContain("spot-s3cret", onDisk); + Assert.DoesNotContain("tidal-s3cret", onDisk); + Assert.Contains("sid", onDisk); // an id is not a secret + + var loaded = stores.LoadSettings("alice"); + Assert.Equal("spot-s3cret", loaded.SpotifyClientSecret); + Assert.Equal("tidal-s3cret", loaded.TidalClientSecret); + } + + [Fact] + public void A_plain_settings_file_is_still_read_and_gets_encrypted_on_the_next_save() + { + Directory.CreateDirectory(Path.GetDirectoryName(SettingsFile)!); + File.WriteAllText(SettingsFile, """{"SpotifyClientSecret":"old-plain"}"""); + var stores = new UserStores(_root, _protector); + + var loaded = stores.LoadSettings("alice"); + Assert.Equal("old-plain", loaded.SpotifyClientSecret); + + stores.SaveSettings("alice", loaded); + Assert.DoesNotContain("old-plain", File.ReadAllText(SettingsFile)); + } + + [Fact] + public void A_secret_that_cannot_be_decrypted_reads_as_empty_instead_of_failing() + { + new UserStores(_root, _protector).SaveSettings("alice", new AppSettings { SpotifyClientSecret = "x" }); + var otherKeys = new EphemeralDataProtectionProvider().CreateProtector("test"); + + Assert.Equal("", new UserStores(_root, otherKeys).LoadSettings("alice").SpotifyClientSecret); + } + + [Fact] + public void Saving_does_not_change_the_callers_settings_object() + { + var settings = new AppSettings { SpotifyClientSecret = "keep" }; + new UserStores(_root, _protector).SaveSettings("alice", settings); + Assert.Equal("keep", settings.SpotifyClientSecret); + } + + [Fact] + public void Deleting_a_user_removes_their_whole_folder_and_nobody_elses() + { + var stores = new UserStores(_root, _protector); + stores.QueueOf("alice").Insert(new BacklogItem { Artist = "A", Album = "One" }); + stores.QueueOf("bob").Insert(new BacklogItem { Artist = "B", Album = "Two" }); + + stores.Delete("alice"); + + Assert.False(Directory.Exists(Path.Combine(_root, "alice"))); + Assert.Single(stores.QueueOf("bob").LoadAll()); + } + + [Fact] + public void Deleting_a_user_who_has_no_data_is_fine() => new UserStores(_root, _protector).Delete("nobody"); + + [Fact] + public void FileOf_stays_inside_the_users_folder() + { + var stores = new UserStores(_root); + Assert.Equal(Path.Combine(_root, "alice", "prefs.json"), stores.FileOf("alice", "prefs.json")); + Assert.Throws(() => stores.FileOf("alice", "../x.json")); + } +} diff --git a/Queueify.Web/Ocr/ImageGuard.cs b/Queueify.Web/Ocr/ImageGuard.cs new file mode 100644 index 0000000..74cda50 --- /dev/null +++ b/Queueify.Web/Ocr/ImageGuard.cs @@ -0,0 +1,74 @@ +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Formats; +using SixLabors.ImageSharp.Formats.Png; +using SixLabors.ImageSharp.Processing; + +namespace Queueify.Web.Ocr; + +/// Why a photo was not read; the page turns each into a message the user can act on. +public enum PhotoProblem { TooLarge, NotAnImage, TooManyPixels, Corrupt, Busy, Timeout, EngineMissing } + +public sealed class PhotoException(PhotoProblem problem) : Exception(problem.ToString()) +{ + public PhotoProblem Problem { get; } = problem; +} + +/// A photo checked, turned upright, scaled down and re-encoded as a plain PNG (no metadata). +public sealed record PreparedImage(byte[] Png, int Width, int Height); + +/// +/// An upload is untrusted: the declared type means nothing, so the bytes are sniffed, the pixel count is +/// read from the header before anything is decoded, and what leaves is a fresh PNG built by us. +/// +public static class ImageGuard +{ + public static PreparedImage Prepare(Stream input, OcrOptions options) + { + var bytes = ReadCapped(input, options.MaxBytes); + if (!LooksLikeAPhoto(bytes)) throw new PhotoException(PhotoProblem.NotAnImage); + + try + { + var info = Image.Identify(bytes); + if ((long)info.Width * info.Height > options.MaxPixels) throw new PhotoException(PhotoProblem.TooManyPixels); + + using var image = Image.Load(new DecoderOptions { MaxFrames = 1 }, bytes); + image.Mutate(x => + { + x.AutoOrient(); + if (Math.Max(image.Width, image.Height) > options.MaxSide) + x.Resize(new ResizeOptions { Mode = ResizeMode.Max, Size = new Size(options.MaxSide, options.MaxSide) }); + }); + image.Metadata.ExifProfile = null; + image.Metadata.IccProfile = null; + image.Metadata.XmpProfile = null; + + using var png = new MemoryStream(); + image.Save(png, new PngEncoder()); + return new PreparedImage(png.ToArray(), image.Width, image.Height); + } + catch (Exception ex) when (ex is ImageFormatException or InvalidOperationException or NotSupportedException or EndOfStreamException or IOException) + { + throw new PhotoException(PhotoProblem.Corrupt); + } + } + + private static byte[] ReadCapped(Stream input, long max) + { + using var buffer = new MemoryStream(); + var chunk = new byte[81920]; + int n; + while ((n = input.Read(chunk, 0, chunk.Length)) > 0) + { + if (buffer.Length + n > max) throw new PhotoException(PhotoProblem.TooLarge); + buffer.Write(chunk, 0, n); + } + return buffer.ToArray(); + } + + /// JPEG, PNG or WebP by their first bytes; everything else (SVG, HTML, GIF, BMP…) is refused. + private static bool LooksLikeAPhoto(ReadOnlySpan b) => + b.StartsWith(new byte[] { 0xFF, 0xD8, 0xFF }) + || b.StartsWith(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }) + || (b.Length >= 12 && b[..4].SequenceEqual("RIFF"u8) && b.Slice(8, 4).SequenceEqual("WEBP"u8)); +} diff --git a/Queueify.Web/Ocr/OcrExtensions.cs b/Queueify.Web/Ocr/OcrExtensions.cs new file mode 100644 index 0000000..19ee7af --- /dev/null +++ b/Queueify.Web/Ocr/OcrExtensions.cs @@ -0,0 +1,100 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Http.Features; +using Queueify.Services; +using Queueify.Web.Services; + +namespace Queueify.Web.Ocr; + +public static class OcrExtensions +{ + /// Tesseract as the web app's , with the limits from the "Ocr" configuration section. + public static IServiceCollection AddQueueifyOcr(this IServiceCollection services, IConfiguration config, IHostEnvironment env) + { + var options = config.GetSection("Ocr").Get() ?? new OcrOptions(); + services.AddSingleton(options); + services.AddHttpClient(nameof(TessdataFetcher), c => c.Timeout = TimeSpan.FromMinutes(2)); + services.AddSingleton(sp => new TessdataFetcher( + sp.GetRequiredService().CreateClient(nameof(TessdataFetcher)), + Path.Combine(QueueifyStorageExtensions.DataRootOf(config, env), "tessdata"), + options.TessdataPath)); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + return services; + } + + /// POST /api/photo?lang=auto|es|en with the picture as the body. + public static IEndpointRouteBuilder MapQueueifyPhoto(this IEndpointRouteBuilder app) + { + app.MapPost("/api/photo", ReadPhotoAsync).DisableAntiforgery(); + return app; + } + + private static async Task ReadPhotoAsync(HttpContext ctx, PhotoReader reader, OcrOptions options, string? lang, CancellationToken ct) + { + if (ctx.User.FindFirstValue(ClaimTypes.NameIdentifier) is not { Length: > 0 } user || ctx.User.Identity?.IsAuthenticated != true) + return Results.Json(new { error = "unauthorized" }, statusCode: StatusCodes.Status401Unauthorized); // with a body, so the status-code page doesn't replace it + + ctx.Response.Headers.CacheControl = "no-store"; + + // Only a fetch() carrying a picture type gets here from a browser: a cross-site form can't send one, + // and without CORS (none is configured) a cross-site fetch is stopped before the request goes out. + // That, plus SameSite cookies, is the CSRF defence; the real format is still sniffed from the bytes. + if (ctx.Request.ContentType?.StartsWith("image/", StringComparison.OrdinalIgnoreCase) != true) + return Problem(PhotoProblem.NotAnImage); + if ((lang ?? "auto") is not ("auto" or "es" or "en")) return Results.BadRequest(new { error = "language" }); + if (ctx.Request.ContentLength > options.MaxBytes) return Problem(PhotoProblem.TooLarge); + + var limit = ctx.Features.Get(); + if (limit is { IsReadOnly: false }) limit.MaxRequestBodySize = options.MaxBytes; + + try + { + // Kestrel forbids synchronous reads, so the (capped) body is buffered here, not inside the guard. + using var upload = await BufferAsync(ctx.Request.Body, options.MaxBytes, ct); + var reading = await reader.ReadAsync(user, upload, lang ?? "auto", ct); + return Results.Json(new + { + width = reading.Width, + height = reading.Height, + language = lang ?? "auto", + languageName = reading.Language, + lines = reading.Lines.Select(l => new { text = l.Text, x = l.Bounds.X, y = l.Bounds.Y, width = l.Bounds.Width, height = l.Bounds.Height }), + }); + } + catch (PhotoException ex) + { + return Problem(ex.Problem); + } + catch (BadHttpRequestException) + { + return Problem(PhotoProblem.TooLarge); + } + } + + private static async Task BufferAsync(Stream body, long max, CancellationToken ct) + { + var buffer = new MemoryStream(); + var chunk = new byte[81920]; + int n; + while ((n = await body.ReadAsync(chunk, ct)) > 0) + { + if (buffer.Length + n > max) throw new PhotoException(PhotoProblem.TooLarge); + buffer.Write(chunk, 0, n); + } + buffer.Position = 0; + return buffer; + } + + private static IResult Problem(PhotoProblem problem) => Results.Json( + new { error = char.ToLowerInvariant(problem.ToString()[0]) + problem.ToString()[1..] }, + statusCode: problem switch + { + PhotoProblem.TooLarge or PhotoProblem.TooManyPixels => StatusCodes.Status413PayloadTooLarge, + PhotoProblem.NotAnImage => StatusCodes.Status415UnsupportedMediaType, + PhotoProblem.Corrupt => StatusCodes.Status422UnprocessableEntity, + PhotoProblem.Busy => StatusCodes.Status429TooManyRequests, + PhotoProblem.Timeout => StatusCodes.Status504GatewayTimeout, + _ => StatusCodes.Status503ServiceUnavailable, + }); +} diff --git a/Queueify.Web/Ocr/OcrGate.cs b/Queueify.Web/Ocr/OcrGate.cs new file mode 100644 index 0000000..ba607a6 --- /dev/null +++ b/Queueify.Web/Ocr/OcrGate.cs @@ -0,0 +1,32 @@ +namespace Queueify.Web.Ocr; + +/// +/// Admission for reading photos: one at a time per user, and a cap across the server. A reader costs +/// seconds of CPU, so a turned-away request is cheaper than a queue that grows without bound. +/// +public sealed class OcrGate(OcrOptions options) +{ + private readonly HashSet _users = new(StringComparer.Ordinal); + private readonly Lock _lock = new(); + + /// A slot to dispose when the photo is done, or null when this user (or the server) is busy. + public IDisposable? TryEnter(string userId) + { + lock (_lock) + { + if (_users.Count >= options.MaxConcurrent || !_users.Add(userId)) return null; + } + return new Slot(this, userId); + } + + private sealed class Slot(OcrGate gate, string userId) : IDisposable + { + private int _released; + + public void Dispose() + { + if (Interlocked.Exchange(ref _released, 1) != 0) return; + lock (gate._lock) gate._users.Remove(userId); + } + } +} diff --git a/Queueify.Web/Ocr/OcrOptions.cs b/Queueify.Web/Ocr/OcrOptions.cs new file mode 100644 index 0000000..5d89b67 --- /dev/null +++ b/Queueify.Web/Ocr/OcrOptions.cs @@ -0,0 +1,29 @@ +namespace Queueify.Web.Ocr; + +/// Limits and locations for reading magazine photos; the "Ocr" configuration section. +public sealed class OcrOptions +{ + /// The biggest upload accepted, in bytes (a phone photo is 2 to 8 MB). + public long MaxBytes { get; set; } = 12 * 1024 * 1024; + + /// The most pixels an upload may hold: a decompression-bomb guard, checked before decoding. + public long MaxPixels { get; set; } = 60_000_000; + + /// The photo is scaled down to this many pixels on its longest side before reading. + public int MaxSide { get; set; } = 3000; + + /// How long one photo may take before the reader is stopped. + public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(40); + + /// Photos being read at the same time on the whole server, across users. + public int MaxConcurrent { get; set; } = 2; + + /// The tesseract program: a full path, or a name found on PATH. + public string TesseractPath { get; set; } = "tesseract"; + + /// + /// A folder of *.traineddata that an administrator manages. Empty means Queueify keeps its own copy + /// under the data folder and downloads the two languages once, checking their checksums. + /// + public string TessdataPath { get; set; } = ""; +} diff --git a/Queueify.Web/Ocr/PhotoReader.cs b/Queueify.Web/Ocr/PhotoReader.cs new file mode 100644 index 0000000..772ca69 --- /dev/null +++ b/Queueify.Web/Ocr/PhotoReader.cs @@ -0,0 +1,47 @@ +using Queueify.Services; + +namespace Queueify.Web.Ocr; + +/// +/// Reads one uploaded photo: admission, check and re-encode, the engine, a time limit. The photo only +/// ever exists in memory, as the bytes of the upload and then of the clean PNG, both wiped afterwards; +/// nothing is written to disk. +/// +public sealed class PhotoReader(IOcr ocr, OcrGate gate, OcrOptions options) +{ + public const int MaxLines = 300; + public const int MaxLineLength = 300; + + public async Task ReadAsync(string userId, Stream upload, string language, CancellationToken ct) + { + using var slot = gate.TryEnter(userId) ?? throw new PhotoException(PhotoProblem.Busy); + using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct); + limit.CancelAfter(options.Timeout); + + PreparedImage? prepared = null; + try + { + prepared = await Task.Run(() => ImageGuard.Prepare(upload, options), limit.Token); + using var png = new MemoryStream(prepared.Png, writable: false); + var reading = await ocr.RecognizeAsync(png, language, limit.Token); + return Trim(reading); + } + catch (OperationCanceledException) when (!ct.IsCancellationRequested) + { + throw new PhotoException(PhotoProblem.Timeout); + } + finally + { + if (prepared is not null) Array.Clear(prepared.Png); + } + } + + /// The engine's answer is data too: bounded in count and length before it reaches a page. + private static OcrReading Trim(OcrReading reading) => reading with + { + Lines = reading.Lines + .Take(MaxLines) + .Select(l => l.Text.Length > MaxLineLength ? l with { Text = l.Text[..MaxLineLength] } : l) + .ToList(), + }; +} diff --git a/Queueify.Web/Ocr/TessdataFetcher.cs b/Queueify.Web/Ocr/TessdataFetcher.cs new file mode 100644 index 0000000..9b09068 --- /dev/null +++ b/Queueify.Web/Ocr/TessdataFetcher.cs @@ -0,0 +1,68 @@ +using System.Security.Cryptography; + +namespace Queueify.Web.Ocr; + +public sealed record TessdataFile(string Language, string Url, string Sha256); + +/// +/// Makes sure the Spanish and English models are on disk. Left alone, it keeps its own copy under the data +/// folder, downloaded once from tessdata_fast at a pinned release and accepted only when the SHA-256 +/// matches; Ocr:TessdataPath hands the job to an administrator instead. +/// +public sealed class TessdataFetcher(HttpClient http, string managedFolder, string configuredFolder, IReadOnlyList? files = null) +{ + // tessdata_fast release 4.1.0: the small, quick models, enough for printed magazine text. + public static IReadOnlyList Pinned { get; } = + [ + new("spa", "https://raw.githubusercontent.com/tesseract-ocr/tessdata_fast/4.1.0/spa.traineddata", "6F2E04D02774A18F01BED44B1111F2CD7F3BA7AC9DC4373CD3F898A40EA6B464"), + new("eng", "https://raw.githubusercontent.com/tesseract-ocr/tessdata_fast/4.1.0/eng.traineddata", "7D4322BD2A7749724879683FC3912CB542F19906C83BCC1A52132556427170B2"), + ]; + + private readonly SemaphoreSlim _once = new(1, 1); + private bool _ready; + + /// The folder holding the models, downloading what's missing the first time. + public async Task EnsureAsync(CancellationToken ct) + { + if (configuredFolder.Length > 0) return configuredFolder; + if (_ready) return managedFolder; + + await _once.WaitAsync(ct); + try + { + if (_ready) return managedFolder; + Directory.CreateDirectory(managedFolder); + foreach (var file in files ?? Pinned) await EnsureFileAsync(file, ct); + _ready = true; + return managedFolder; + } + finally + { + _once.Release(); + } + } + + private async Task EnsureFileAsync(TessdataFile file, CancellationToken ct) + { + var path = Path.Combine(managedFolder, file.Language + ".traineddata"); + if (File.Exists(path) && Matches(await File.ReadAllBytesAsync(path, ct), file)) return; + + byte[] body; + try + { + body = await http.GetByteArrayAsync(file.Url, ct); + } + catch (HttpRequestException) + { + throw new PhotoException(PhotoProblem.EngineMissing); + } + if (!Matches(body, file)) throw new PhotoException(PhotoProblem.EngineMissing); + + var partial = path + ".part"; + await File.WriteAllBytesAsync(partial, body, ct); + File.Move(partial, path, overwrite: true); + } + + private static bool Matches(byte[] body, TessdataFile file) => + Convert.ToHexString(SHA256.HashData(body)).Equals(file.Sha256, StringComparison.OrdinalIgnoreCase); +} diff --git a/Queueify.Web/Ocr/TesseractOcr.cs b/Queueify.Web/Ocr/TesseractOcr.cs new file mode 100644 index 0000000..ecf8b06 --- /dev/null +++ b/Queueify.Web/Ocr/TesseractOcr.cs @@ -0,0 +1,162 @@ +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.Text; +using Microsoft.Extensions.Logging; +using Queueify.Services; + +namespace Queueify.Web.Ocr; + +/// +/// with the tesseract program, run as a child process: the picture goes in through stdin +/// and the answer (TSV, one row per word with its box) comes out of stdout, so no file is ever written. A +/// separate process can be killed on a timeout and can't take the web server down with it. +/// +public sealed class TesseractOcr(OcrOptions options, TessdataFetcher tessdata, ILogger log) : IOcr +{ + private const int MaxOutputChars = 4_000_000; + + public async Task RecognizeAsync(Stream image, string language, CancellationToken ct = default) + { + var languages = LanguagesFor(language); + var folder = await tessdata.EnsureAsync(ct); + + var start = new ProcessStartInfo(options.TesseractPath) + { + RedirectStandardInput = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + StandardOutputEncoding = Encoding.UTF8, + UseShellExecute = false, + CreateNoWindow = true, + }; + foreach (var arg in ArgumentsFor(languages, folder)) start.ArgumentList.Add(arg); + start.Environment["OMP_THREAD_LIMIT"] = "1"; // one core per photo: several users share the server + + Process process; + try + { + process = Process.Start(start) ?? throw new PhotoException(PhotoProblem.EngineMissing); + } + catch (Win32Exception ex) + { + log.LogError("Can't start {Program}: {Message}", options.TesseractPath, ex.Message); + throw new PhotoException(PhotoProblem.EngineMissing); + } + + using (process) + using (ct.Register(() => TryKill(process))) + { + var errors = process.StandardError.ReadToEndAsync(ct); + var output = ReadCappedAsync(process.StandardOutput, ct); + try + { + await image.CopyToAsync(process.StandardInput.BaseStream, ct); + process.StandardInput.Close(); + } + catch (IOException) + { + // The engine closed its input early; its exit code below says why. + } + + var tsv = await output; + await process.WaitForExitAsync(ct); + if (process.ExitCode != 0) + { + log.LogError("tesseract exited with {Code}: {Errors}", process.ExitCode, Truncate(await errors)); + throw new PhotoException(PhotoProblem.EngineMissing); + } + return ParseTsv(tsv, NameOf(languages)); + } + } + + /// "auto", "es" or "en", and nothing else: the value ends up on a command line. + public static string LanguagesFor(string choice) => choice switch + { + "auto" => "spa+eng", + "es" => "spa", + "en" => "eng", + _ => throw new ArgumentException("Not an offered language.", nameof(choice)), + }; + + public static IReadOnlyList ArgumentsFor(string languages, string tessdataFolder) => + ["stdin", "stdout", "--tessdata-dir", tessdataFolder, "-l", languages, "-c", "tessedit_create_tsv=1"]; + + /// Lines (level 4 rows, with their box) and their words (level 5), from tesseract's TSV. + public static OcrReading ParseTsv(string tsv, string language) + { + int width = 0, height = 0; + var lines = new List(); + OcrBox? box = null; + var words = new List(); + + void Finish() + { + if (box is { } b && words.Count > 0) lines.Add(new OcrTextLine(string.Join(' ', words), b)); + box = null; + words.Clear(); + } + + foreach (var row in tsv.Split('\n')) + { + var cells = row.TrimEnd('\r').Split('\t'); + if (cells.Length < 11 || !int.TryParse(cells[0], out var level)) continue; + switch (level) + { + case 1 when TryBox(cells, out var page): + width = (int)page.Width; + height = (int)page.Height; + break; + case 4 when TryBox(cells, out var line): + Finish(); + box = line; + break; + case 5 when cells.Length >= 12 && box is not null + && double.TryParse(cells[10], NumberStyles.Float, CultureInfo.InvariantCulture, out var conf) && conf >= 0 + && cells[11].Trim() is { Length: > 0 } word: + words.Add(word); + break; + } + } + Finish(); + return new OcrReading(lines, width, height, language); + } + + private static bool TryBox(string[] cells, out OcrBox box) + { + var ok = double.TryParse(cells[6], NumberStyles.Float, CultureInfo.InvariantCulture, out var x) + & double.TryParse(cells[7], NumberStyles.Float, CultureInfo.InvariantCulture, out var y) + & double.TryParse(cells[8], NumberStyles.Float, CultureInfo.InvariantCulture, out var w) + & double.TryParse(cells[9], NumberStyles.Float, CultureInfo.InvariantCulture, out var h); + box = new OcrBox(x, y, w, h); + return ok; + } + + private static string NameOf(string languages) => languages switch + { + "spa" => "Español", + "eng" => "English", + _ => "Español + English", + }; + + private static async Task ReadCappedAsync(StreamReader reader, CancellationToken ct) + { + var text = new StringBuilder(); + var buffer = new char[8192]; + int n; + while ((n = await reader.ReadAsync(buffer.AsMemory(), ct)) > 0) + { + if (text.Length + n > MaxOutputChars) break; + text.Append(buffer, 0, n); + } + return text.ToString(); + } + + private static void TryKill(Process process) + { + try { if (!process.HasExited) process.Kill(entireProcessTree: true); } + catch (Exception ex) when (ex is InvalidOperationException or Win32Exception) { } + } + + private static string Truncate(string s) => s.Length > 500 ? s[..500] : s; +} diff --git a/Queueify.Web/Program.cs b/Queueify.Web/Program.cs index 6fa04c5..0f37dee 100644 --- a/Queueify.Web/Program.cs +++ b/Queueify.Web/Program.cs @@ -4,6 +4,8 @@ using Queueify.Web.Components; using Queueify.Web.Components.Account; using Queueify.Web.Data; +using Queueify.Web.Ocr; +using Queueify.Web.Services; var builder = WebApplication.CreateBuilder(args); @@ -37,6 +39,8 @@ .AddDefaultTokenProviders(); builder.Services.AddSingleton, IdentityNoOpEmailSender>(); +builder.Services.AddQueueifyStorage(builder.Configuration, builder.Environment); +builder.Services.AddQueueifyOcr(builder.Configuration, builder.Environment); var app = builder.Build(); @@ -63,6 +67,8 @@ // Add additional endpoints required by the Identity /Account Razor components. app.MapAdditionalIdentityEndpoints(); +app.MapQueueifyPhoto(); + app.MapGet("/healthz", () => Results.Ok("ok")).AllowAnonymous(); app.Run(); diff --git a/Queueify.Web/Queueify.Web.csproj b/Queueify.Web/Queueify.Web.csproj index 7aee75d..d1ef63a 100644 --- a/Queueify.Web/Queueify.Web.csproj +++ b/Queueify.Web/Queueify.Web.csproj @@ -20,6 +20,7 @@ + diff --git a/Queueify.Web/Services/QueueifyStorageExtensions.cs b/Queueify.Web/Services/QueueifyStorageExtensions.cs new file mode 100644 index 0000000..77f7419 --- /dev/null +++ b/Queueify.Web/Services/QueueifyStorageExtensions.cs @@ -0,0 +1,28 @@ +using Microsoft.AspNetCore.DataProtection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Queueify.Web.Storage; + +namespace Queueify.Web.Services; + +public static class QueueifyStorageExtensions +{ + /// + /// The data folder: Queueify:DataRoot, or "App_Data" beside the app ("Data" already holds the account + /// database). Holds one folder per user (their ids are GUIDs) plus "keys" and "tessdata". + /// + public static string DataRootOf(IConfiguration config, IHostEnvironment env) => + Path.GetFullPath(config["Queueify:DataRoot"] is { Length: > 0 } root ? root : Path.Combine(env.ContentRootPath, "App_Data")); + + /// + /// The per-user stores, with the Spotify/Tidal secrets encrypted by Data Protection. Its key ring lives + /// in the data folder, so it travels with the backups and survives restarts. + /// + public static IServiceCollection AddQueueifyStorage(this IServiceCollection services, IConfiguration config, IHostEnvironment env) + { + var root = DataRootOf(config, env); + services.AddDataProtection().SetApplicationName("Queueify").PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(root, "keys"))); + services.TryAddSingleton(sp => + new UserStores(root, sp.GetRequiredService().CreateProtector("Queueify.UserSecrets.v1"))); + return services; + } +} diff --git a/Queueify.Web/Storage/UserStores.cs b/Queueify.Web/Storage/UserStores.cs index d4a2e7c..66ab2dc 100644 --- a/Queueify.Web/Storage/UserStores.cs +++ b/Queueify.Web/Storage/UserStores.cs @@ -1,11 +1,18 @@ +using Microsoft.AspNetCore.DataProtection; using Queueify.Models; using Queueify.Services; namespace Queueify.Web.Storage; -/// One folder per user under the data root, holding their queue (queueify.db) and settings.json. -public sealed class UserStores(string root) +/// +/// One folder per user under the data root, holding their queue (queueify.db) and settings.json. With a +/// the two client secrets are encrypted in settings.json (ASP.NET Data +/// Protection); callers always see them in clear text, and nothing else is encrypted. +/// +public sealed class UserStores(string root, IDataProtector? protector = null) { + private const string Prefix = "dp1:"; + private string FolderOf(string userId) { if (userId.Length == 0 || userId.IndexOfAny(['/', '\\', ':']) >= 0 || userId.Contains("..")) @@ -13,10 +20,51 @@ private string FolderOf(string userId) return Path.Combine(root, userId); } + /// A file in the user's folder, by a plain name (no folders). + public string FileOf(string userId, string name) + { + if (name.Length == 0 || name.IndexOfAny(['/', '\\', ':']) >= 0 || name.Contains("..")) + throw new ArgumentException("Not a valid file name.", nameof(name)); + return Path.Combine(FolderOf(userId), name); + } + public BacklogStore QueueOf(string userId) => new(Path.Combine(FolderOf(userId), "queueify.db")); - public AppSettings LoadSettings(string userId) => AppData.LoadSettings(Path.Combine(FolderOf(userId), "settings.json")); + public AppSettings LoadSettings(string userId) + { + var settings = AppData.LoadSettings(FileOf(userId, "settings.json")); + settings.SpotifyClientSecret = Reveal(settings.SpotifyClientSecret); + settings.TidalClientSecret = Reveal(settings.TidalClientSecret); + return settings; + } - public void SaveSettings(string userId, AppSettings settings) => - AppData.SaveSettings(settings, Path.Combine(FolderOf(userId), "settings.json")); + public void SaveSettings(string userId, AppSettings settings) + { + var stored = settings.Clone(); + stored.SpotifyClientSecret = Hide(stored.SpotifyClientSecret); + stored.TidalClientSecret = Hide(stored.TidalClientSecret); + AppData.SaveSettings(stored, FileOf(userId, "settings.json")); + } + + /// Removes everything stored for the user: queue, settings, preferences. + public void Delete(string userId) + { + var folder = FolderOf(userId); + if (Directory.Exists(folder)) Directory.Delete(folder, recursive: true); + } + + private string Hide(string secret) => protector is null || secret.Length == 0 ? secret : Prefix + protector.Protect(secret); + + private string Reveal(string stored) + { + if (!stored.StartsWith(Prefix, StringComparison.Ordinal)) return stored; + try + { + return protector?.Unprotect(stored[Prefix.Length..]) ?? ""; + } + catch (System.Security.Cryptography.CryptographicException) + { + return ""; // keys were lost or replaced: the user types the secret again + } + } } From 707c8f71d57c05dccecfd6e89367d2fc07241aae Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:24:31 -0300 Subject: [PATCH 06/66] feat(web): sync server, personal access tokens and the connect page Co-Authored-By: Claude Sonnet 5.5 --- Queueify.Core/Services/Strings.En.cs | 16 + Queueify.Core/Services/Strings.Es.cs | 16 + Queueify.Web.Tests/Sync/ConnectPcTests.cs | 88 ++++ .../Sync/PersonalAccessTokenTests.cs | 106 +++++ Queueify.Web.Tests/Sync/SyncContractTests.cs | 64 +++ Queueify.Web.Tests/Sync/SyncEndpointTests.cs | 364 ++++++++++++++++ Queueify.Web.Tests/Sync/SyncFactory.cs | 69 +++ Queueify.Web/Components/Pages/ConnectPc.razor | 114 +++++ Queueify.Web/Data/ApplicationDbContext.cs | 8 + ...120000_AddPersonalAccessTokens.Designer.cs | 398 ++++++++++++++++++ .../20261014120000_AddPersonalAccessTokens.cs | 56 +++ .../ApplicationDbContextModelSnapshot.cs | 48 +++ Queueify.Web/Program.cs | 4 + Queueify.Web/Storage/UserStores.cs | 68 ++- Queueify.Web/Sync/PersonalAccessToken.cs | 28 ++ Queueify.Web/Sync/PersonalAccessTokens.cs | 73 ++++ Queueify.Web/Sync/SyncEngine.cs | 291 +++++++++++++ Queueify.Web/Sync/SyncExtensions.cs | 101 +++++ Queueify.Web/Sync/TokenAuthentication.cs | 73 ++++ SECURITY.md | 6 +- docs/ARCHITECTURE.md | 24 ++ docs/TESTING.md | 3 + 22 files changed, 2011 insertions(+), 7 deletions(-) create mode 100644 Queueify.Web.Tests/Sync/ConnectPcTests.cs create mode 100644 Queueify.Web.Tests/Sync/PersonalAccessTokenTests.cs create mode 100644 Queueify.Web.Tests/Sync/SyncContractTests.cs create mode 100644 Queueify.Web.Tests/Sync/SyncEndpointTests.cs create mode 100644 Queueify.Web.Tests/Sync/SyncFactory.cs create mode 100644 Queueify.Web/Components/Pages/ConnectPc.razor create mode 100644 Queueify.Web/Data/Migrations/20261014120000_AddPersonalAccessTokens.Designer.cs create mode 100644 Queueify.Web/Data/Migrations/20261014120000_AddPersonalAccessTokens.cs create mode 100644 Queueify.Web/Sync/PersonalAccessToken.cs create mode 100644 Queueify.Web/Sync/PersonalAccessTokens.cs create mode 100644 Queueify.Web/Sync/SyncEngine.cs create mode 100644 Queueify.Web/Sync/SyncExtensions.cs create mode 100644 Queueify.Web/Sync/TokenAuthentication.cs diff --git a/Queueify.Core/Services/Strings.En.cs b/Queueify.Core/Services/Strings.En.cs index 62e0819..c7ae399 100644 --- a/Queueify.Core/Services/Strings.En.cs +++ b/Queueify.Core/Services/Strings.En.cs @@ -353,5 +353,21 @@ public static partial class Loc ["tour.3"] = "Photograph a magazine page with your phone and drop the photo into this window. Then click the artist and the album on it.", ["tour.4.title"] = "All your PCs", ["tour.4"] = "Connect Sync once to keep the same queue on every PC. Help (F1) explains everything else.", + + // ── Connect a PC (web) ── + ["connect.title"] = "Connect a PC", + ["connect.intro"] = "Give each PC its own access token. Paste the connect text into Queueify's Sync settings on that PC.", + ["connect.name"] = "Name of the PC", + ["connect.create"] = "Create token", + ["connect.once"] = "Copy this now: it is shown only once.", + ["connect.text"] = "Connect text", + ["connect.tokens"] = "Your tokens", + ["connect.empty"] = "No tokens yet.", + ["connect.created"] = "Created", + ["connect.last_used"] = "Last used", + ["connect.never"] = "Never", + ["connect.revoked"] = "Revoked", + ["connect.revoke"] = "Revoke", + ["connect.limit"] = "You have reached the limit of tokens. Revoke one to create another.", }; } diff --git a/Queueify.Core/Services/Strings.Es.cs b/Queueify.Core/Services/Strings.Es.cs index 57645fb..024518a 100644 --- a/Queueify.Core/Services/Strings.Es.cs +++ b/Queueify.Core/Services/Strings.Es.cs @@ -354,5 +354,21 @@ public static partial class Loc ["tour.3"] = "Sacale una foto a una página de revista con el celular y soltala en esta ventana. Después hacé clic en el artista y el álbum.", ["tour.4.title"] = "Todas tus PC", ["tour.4"] = "Conectá Sincronizar una vez para tener la misma lista en todas tus PC. La Ayuda (F1) explica todo lo demás.", + + // ── Conectar una PC (web) ── + ["connect.title"] = "Conectar una PC", + ["connect.intro"] = "Dale a cada PC su propia ficha de acceso. Pegá el texto de conexión en los ajustes de Sincronizar de Queueify en esa PC.", + ["connect.name"] = "Nombre de la PC", + ["connect.create"] = "Crear ficha", + ["connect.once"] = "Copialo ahora: se muestra una sola vez.", + ["connect.text"] = "Texto de conexión", + ["connect.tokens"] = "Tus fichas", + ["connect.empty"] = "Todavía no hay fichas.", + ["connect.created"] = "Creada", + ["connect.last_used"] = "Último uso", + ["connect.never"] = "Nunca", + ["connect.revoked"] = "Revocada", + ["connect.revoke"] = "Revocar", + ["connect.limit"] = "Llegaste al límite de fichas. Revocá una para crear otra.", }; } diff --git a/Queueify.Web.Tests/Sync/ConnectPcTests.cs b/Queueify.Web.Tests/Sync/ConnectPcTests.cs new file mode 100644 index 0000000..477478d --- /dev/null +++ b/Queueify.Web.Tests/Sync/ConnectPcTests.cs @@ -0,0 +1,88 @@ +using System.Net; +using System.Security.Claims; +using System.Text.RegularExpressions; +using Bunit; +using Microsoft.AspNetCore.Components.Authorization; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Queueify.Services; +using Queueify.Web.Components.Pages; +using Queueify.Web.Data; +using Queueify.Web.Sync; + +namespace Queueify.Web.Tests.Sync; + +public sealed class ConnectPcTests : BunitContext +{ + private sealed class SignedIn(string id) : AuthenticationStateProvider + { + public override Task GetAuthenticationStateAsync() => + Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, id)], "test")))); + } + + private readonly SqliteConnection _db = new("DataSource=:memory:"); + + private IRenderedComponent Open(string userId) + { + _db.Open(); + Services.AddDbContext(o => o.UseSqlite(_db)); + Services.AddSingleton(TimeProvider.System); + Services.AddScoped(); + Services.AddSingleton(new SignedIn(userId)); + using (var scope = Services.BuildServiceProvider().CreateScope()) + { + var context = scope.ServiceProvider.GetRequiredService(); + context.Database.EnsureCreated(); + context.Users.Add(new ApplicationUser { Id = userId, UserName = "u", NormalizedUserName = "U", SecurityStamp = "s" }); + context.SaveChanges(); + } + return Render(); + } + + [Fact] + public void Creating_a_token_shows_the_connect_text_once_and_lists_it() + { + var page = Open("user-1"); + page.Find("#token-name").Input("Studio PC"); + page.Find("form").Submit(); + + var text = page.Find("#connect-text").GetAttribute("value")!; + Assert.Matches("^queueify-web\\|http://localhost\\|qw_[A-Za-z0-9_-]{43}$", text); + Assert.Contains("Studio PC", page.Markup); + + page.Find("button.btn-outline-danger").Click(); + Assert.Empty(page.FindAll("#connect-text")); + Assert.Empty(page.FindAll("button.btn-outline-danger")); + Assert.Contains(Loc.T("connect.revoked"), page.Markup); + Assert.DoesNotContain("qw_", page.Markup); + } + + [Fact] + public void Every_text_on_the_page_exists_in_both_languages() + { + var razor = File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "Queueify.Web", "Components", "Pages", "ConnectPc.razor")); + var keys = Regex.Matches(razor, "Loc\\.T\\(\"(connect\\.[a-z_.]+)\"\\)").Select(m => m.Groups[1].Value).Distinct().ToList(); + Assert.NotEmpty(keys); + Assert.All(keys, k => { Assert.True(Loc.English.ContainsKey(k), k); Assert.True(Loc.Spanish.ContainsKey(k), k); }); + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + _db.Dispose(); + } +} + +public sealed class ConnectPageAccessTests(SyncFactory app) : IClassFixture +{ + [Fact] + public async Task Anonymous_visitors_never_get_the_token_form() + { + var client = app.CreateClient(new Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); + using var response = await client.GetAsync("/connect"); + var body = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("token-name", body); + Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode); + } +} diff --git a/Queueify.Web.Tests/Sync/PersonalAccessTokenTests.cs b/Queueify.Web.Tests/Sync/PersonalAccessTokenTests.cs new file mode 100644 index 0000000..fce30e3 --- /dev/null +++ b/Queueify.Web.Tests/Sync/PersonalAccessTokenTests.cs @@ -0,0 +1,106 @@ +using System.Security.Cryptography; +using System.Text; +using Microsoft.Extensions.DependencyInjection; +using Queueify.Web.Data; +using Queueify.Web.Sync; + +namespace Queueify.Web.Tests.Sync; + +public sealed class PersonalAccessTokenTests(SyncFactory app) : IClassFixture +{ + private async Task WithTokens(Func> body) + { + using var scope = app.Services.CreateScope(); + return await body(scope.ServiceProvider.GetRequiredService(), scope.ServiceProvider.GetRequiredService()); + } + + [Fact] + public async Task A_token_is_qw_and_32_random_bytes_in_base64url() + { + var (userId, token) = await app.NewUserAsync("format"); + Assert.Matches("^qw_[A-Za-z0-9_-]{43}$", token); + Assert.Equal(32, Convert.FromBase64String(token[3..].Replace('-', '+').Replace('_', '/') + "=").Length); + Assert.NotEqual(token, (await app.NewUserAsync("format2")).Token); + Assert.NotEmpty(userId); + } + + [Fact] + public async Task Only_the_hash_is_stored_and_the_token_is_never_listed() + { + var (userId, token) = await app.NewUserAsync("hash"); + await WithTokens(async (tokens, db) => + { + var row = (await tokens.ListAsync(userId)).Single(); + Assert.Equal(SHA256.HashData(Encoding.UTF8.GetBytes(token)), row.TokenHash); + Assert.Equal("test PC", row.Name); + Assert.Null(row.LastUsedAt); + Assert.Null(row.RevokedAt); + return 0; + }); + // nothing on disk holds the token itself + foreach (var file in Directory.EnumerateFiles(app.Dir, "*", SearchOption.AllDirectories)) + { + await using var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + using var copy = new MemoryStream(); + await stream.CopyToAsync(copy); + Assert.DoesNotContain(token, Encoding.Latin1.GetString(copy.ToArray())); + } + } + + [Fact] + public async Task Using_a_token_records_when() + { + var (userId, token) = await app.NewUserAsync("last-used"); + await app.SyncAsync(token, new Queueify.Services.SyncRequest(null, [], null)); + Assert.NotNull(await WithTokens(async (tokens, _) => (await tokens.ListAsync(userId)).Single().LastUsedAt)); + } + + [Fact] + public async Task Tokens_are_revoked_only_by_their_owner() + { + var (aliceId, aliceToken) = await app.NewUserAsync("own-a"); + var (bobId, _) = await app.NewUserAsync("own-b"); + await WithTokens(async (tokens, _) => + { + var id = (await tokens.ListAsync(aliceId)).Single().Id; + Assert.False(await tokens.RevokeAsync(bobId, id)); + Assert.Equal(aliceId, await tokens.ValidateAsync(aliceToken)); + Assert.True(await tokens.RevokeAsync(aliceId, id)); + Assert.Null(await tokens.ValidateAsync(aliceToken)); + Assert.NotNull((await tokens.ListAsync(aliceId)).Single().RevokedAt); + return 0; + }); + } + + [Theory] + [InlineData("")] + [InlineData("qw_")] + [InlineData("qw_short")] + [InlineData("xx_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")] + public async Task Things_that_are_not_tokens_never_validate(string text) => + Assert.Null(await WithTokens((tokens, _) => tokens.ValidateAsync(text))); + + [Fact] + public async Task A_user_can_have_only_so_many_tokens_and_names_are_trimmed_and_limited() + { + var (userId, _) = await app.NewUserAsync("limit"); + await WithTokens(async (tokens, _) => + { + var created = await tokens.CreateAsync(userId, " " + new string('n', 300) + " "); + Assert.Equal(100, created.Info.Name.Length); + for (int i = 0; i < PersonalAccessTokens.MaxPerUser - 2; i++) await tokens.CreateAsync(userId, "t" + i); + await Assert.ThrowsAsync(() => tokens.CreateAsync(userId, "one too many")); + return 0; + }); + } + + [Fact] + public async Task Deleting_a_user_removes_their_tokens() + { + var (userId, token) = await app.NewUserAsync("gone"); + using var scope = app.Services.CreateScope(); + var users = scope.ServiceProvider.GetRequiredService>(); + await users.DeleteAsync((await users.FindByIdAsync(userId))!); + Assert.Null(await scope.ServiceProvider.GetRequiredService().ValidateAsync(token)); + } +} diff --git a/Queueify.Web.Tests/Sync/SyncContractTests.cs b/Queueify.Web.Tests/Sync/SyncContractTests.cs new file mode 100644 index 0000000..cba4a08 --- /dev/null +++ b/Queueify.Web.Tests/Sync/SyncContractTests.cs @@ -0,0 +1,64 @@ +using System.Text.Json; +using Queueify.Models; +using Queueify.Services; + +namespace Queueify.Web.Tests.Sync; + +/// The wire format of ADR-0010 with the real Core types, as a desktop client would use it. +public sealed class SyncContractTests(SyncFactory app) : IClassFixture +{ + private static SyncAlbum ToWire(BacklogItem i) => new(i.Uid, i.Artist, i.Album, i.Year, i.Source, i.CoverUrl, i.SpotifyId, + i.TidalId, i.AddedAt.ToUniversalTime(), i.ListenedAt?.ToUniversalTime(), i.Rating, i.UpdatedAt, i.Deleted); + + private static BacklogItem FromWire(SyncAlbum a) => new() + { + Uid = a.Uid, Artist = a.Artist, Album = a.Album, Year = a.Year, Source = a.Source, CoverUrl = a.CoverUrl, + SpotifyId = a.SpotifyId, TidalId = a.TidalId, AddedAt = a.AddedAt, ListenedAt = a.ListenedAt, Rating = a.Rating, + UpdatedAt = a.UpdatedAt, Deleted = a.Deleted, + }; + + [Fact] + public async Task A_PC_pushes_its_queue_and_another_PC_ends_up_with_the_same_albums() + { + var (_, token) = await app.NewUserAsync("contract"); + var dir = Path.Combine(Path.GetTempPath(), "qw-contract-" + Guid.NewGuid().ToString("N")); + try + { + var pc1 = new BacklogStore(Path.Combine(dir, "pc1.db")); + var pc2 = new BacklogStore(Path.Combine(dir, "pc2.db")); + pc1.Insert(new BacklogItem { Artist = "Sonic Youth", Album = "Daydream Nation", Year = 1988, Source = "Rolling Stone", SpotifyId = "sp1", TidalId = "ti1", CoverUrl = "https://example.org/c.jpg", AddedAt = DateTime.UtcNow }); + pc1.Insert(new BacklogItem { Artist = "Luis Alberto Spinetta", Album = "Artaud", Year = 1973, AddedAt = DateTime.UtcNow, Rating = 4.5 }); + var gone = new BacklogItem { Artist = "Gone", Album = "Soon", AddedAt = DateTime.UtcNow }; + pc1.Insert(gone); + pc1.Delete(gone); + + // PC 1 uploads what is dirty, the way CloudSync does + var dirty = pc1.LoadDirty(); + var (status, up) = await app.SyncAsync(token, new SyncRequest(null, [.. dirty.Select(ToWire)], null)); + Assert.Equal(System.Net.HttpStatusCode.OK, status); + foreach (var item in dirty) pc1.MarkUploaded(item); + + // PC 2 downloads + var (_, down) = await app.SyncAsync(token, new SyncRequest(null, [], null)); + foreach (var album in down!.Albums) pc2.ApplyRemote(FromWire(album)); + + Assert.Equal(pc1.LoadAll().OrderBy(i => i.Uid).Select(i => (i.Uid, i.Artist, i.Album, i.Year, i.Source, i.SpotifyId, i.TidalId, i.CoverUrl, i.Rating, i.UpdatedAt)), + pc2.LoadAll().OrderBy(i => i.Uid).Select(i => (i.Uid, i.Artist, i.Album, i.Year, i.Source, i.SpotifyId, i.TidalId, i.CoverUrl, i.Rating, i.UpdatedAt))); + Assert.Equal(2, pc2.LoadAll().Count); + Assert.Empty(pc2.LoadDirty()); + Assert.Empty(up!.Albums); + Assert.Empty((await app.SyncAsync(token, new SyncRequest(down.ServerTime, [], null))).Body!.Albums); + } + finally { try { Directory.Delete(dir, true); } catch (IOException) { } } + } + + [Fact] + public async Task The_documented_json_shape_is_what_goes_over_the_wire() + { + var (_, token) = await app.NewUserAsync("shape"); + using var response = await app.CreateClient().SendAsync(SyncFactory.Post(token, """{"since":null,"albums":[],"settings":null}""")); + using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + Assert.Equal(["serverTime", "albums", "settings"], json.RootElement.EnumerateObject().Select(p => p.Name)); + Assert.EndsWith("Z", json.RootElement.GetProperty("serverTime").GetString()); + } +} diff --git a/Queueify.Web.Tests/Sync/SyncEndpointTests.cs b/Queueify.Web.Tests/Sync/SyncEndpointTests.cs new file mode 100644 index 0000000..e3c15a0 --- /dev/null +++ b/Queueify.Web.Tests/Sync/SyncEndpointTests.cs @@ -0,0 +1,364 @@ +using System.Net; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.DependencyInjection; +using Queueify.Models; +using Queueify.Services; + +namespace Queueify.Web.Tests.Sync; + +public sealed class SyncEndpointTests(SyncFactory app) : IClassFixture +{ + private static readonly DateTime T0 = new(2026, 10, 1, 12, 0, 0, DateTimeKind.Utc); + + private static SyncAlbum Album(string uid, DateTime? updated = null, string artist = "Artist", bool deleted = false) => + new(uid, artist, "Album " + uid, 1999, "Mag", null, null, null, T0, null, -1, updated ?? DateTime.UtcNow.AddMinutes(-5), deleted); + + private static SyncRequest Req(DateTime? since = null, params SyncAlbum[] albums) => new(since, [.. albums], null); + + // ── Authentication ── + + [Fact] + public async Task No_token_is_401_with_an_empty_body() + { + using var response = await app.CreateClient().SendAsync(SyncFactory.Post(null, "{}")); + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("", await response.Content.ReadAsStringAsync()); + } + + [Theory] + [InlineData("qw_" + "A234567890123456789012345678901234567890123")] + [InlineData("not-a-token")] + [InlineData("")] + public async Task A_bad_token_is_401_with_an_empty_body(string token) + { + using var response = await app.CreateClient().SendAsync(SyncFactory.Post(token, "{}")); + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("", await response.Content.ReadAsStringAsync()); + } + + [Fact] + public async Task Basic_auth_with_a_valid_token_is_not_accepted() + { + var (_, token) = await app.NewUserAsync("basic"); + var request = SyncFactory.Post(null, "{}"); + request.Headers.TryAddWithoutValidation("Authorization", "Basic " + token); + using var response = await app.CreateClient().SendAsync(request); + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + public async Task A_revoked_token_is_401() + { + var (userId, token) = await app.NewUserAsync("revoked"); + Assert.Equal(HttpStatusCode.OK, (await app.SyncAsync(token, Req())).Status); + + using (var scope = app.Services.CreateScope()) + { + var tokens = scope.ServiceProvider.GetRequiredService(); + var id = (await tokens.ListAsync(userId)).Single().Id; + Assert.True(await tokens.RevokeAsync(userId, id)); + } + + Assert.Equal(HttpStatusCode.Unauthorized, (await app.SyncAsync(token, Req())).Status); + } + + [Fact] + public void The_endpoint_accepts_only_the_token_scheme_so_the_cookie_is_not_enough() + { + var endpoint = app.Services.GetServices().SelectMany(s => s.Endpoints) + .Single(e => e is RouteEndpoint r && r.RoutePattern.RawText == "/api/sync"); + var schemes = endpoint.Metadata.GetOrderedMetadata().Select(a => a.AuthenticationSchemes).ToList(); + var policy = app.Services.GetRequiredService() + .GetPolicyAsync(endpoint.Metadata.GetMetadata()!.Policy!).Result!; + Assert.Equal(["QueueifyToken"], policy.AuthenticationSchemes); + Assert.NotEmpty(schemes); + } + + // ── Basics and isolation ── + + [Fact] + public async Task A_first_sync_with_nothing_answers_an_empty_response() + { + var (_, token) = await app.NewUserAsync("empty"); + var (status, body) = await app.SyncAsync(token, Req()); + Assert.Equal(HttpStatusCode.OK, status); + Assert.Empty(body!.Albums); + Assert.Null(body.Settings); + } + + [Fact] + public async Task An_album_pushed_from_one_PC_reaches_another_but_never_comes_back_to_the_sender() + { + var (_, token) = await app.NewUserAsync("two-pcs"); + var (_, first) = await app.SyncAsync(token, Req(null, Album("a1"))); + Assert.Empty(first!.Albums); + + var (_, second) = await app.SyncAsync(token, Req()); + Assert.Equal("a1", second!.Albums.Single().Uid); + Assert.Equal("Album a1", second.Albums.Single().Album); + + var (_, third) = await app.SyncAsync(token, Req(second.ServerTime)); + Assert.Empty(third!.Albums); + } + + [Fact] + public async Task The_server_time_only_moves_forward() + { + var (_, token) = await app.NewUserAsync("monotonic"); + var times = new List(); + for (int i = 0; i < 5; i++) times.Add((await app.SyncAsync(token, Req(null, Album("m" + i)))).Body!.ServerTime); + Assert.Equal(times.OrderBy(t => t), times); + Assert.Equal(5, times.Distinct().Count()); + } + + [Fact] + public async Task One_users_token_never_sees_or_changes_another_users_data() + { + var (_, alice) = await app.NewUserAsync("iso-a"); + var (_, bob) = await app.NewUserAsync("iso-b"); + await app.SyncAsync(alice, Req(null, Album("same", artist: "Alice's"))); + await app.SyncAsync(bob, Req(null, Album("same", artist: "Bob's"), Album("only-bob"))); + + var (_, aliceView) = await app.SyncAsync(alice, Req()); + var (_, bobView) = await app.SyncAsync(bob, Req()); + + Assert.Equal(["same"], aliceView!.Albums.Select(a => a.Uid)); + Assert.Equal("Alice's", aliceView.Albums.Single().Artist); + Assert.Equal(["only-bob", "same"], bobView!.Albums.Select(a => a.Uid).Order()); + Assert.Equal("Bob's", bobView.Albums.Single(a => a.Uid == "same").Artist); + } + + [Fact] + public async Task Albums_added_on_the_web_side_reach_the_PCs() + { + var (userId, token) = await app.NewUserAsync("web-side"); + app.Stores.QueueOf(userId).Insert(new BacklogItem { Artist = "Phone", Album = "Added away from home", AddedAt = T0 }); + + var (_, body) = await app.SyncAsync(token, Req()); + Assert.Equal("Phone", body!.Albums.Single().Artist); + + // a deletion made on the web side travels too + var store = app.Stores.QueueOf(userId); + store.Delete(store.LoadAll().Single()); + var (_, later) = await app.SyncAsync(token, Req(body.ServerTime)); + Assert.True(later!.Albums.Single().Deleted); + } + + // ── Conflicts and deletes ── + + [Fact] + public async Task The_newest_change_wins_and_an_older_one_is_answered_with_the_servers_row() + { + var (_, token) = await app.NewUserAsync("conflict"); + await app.SyncAsync(token, Req(null, Album("c", T0.AddHours(2), "Newer"))); + + var (_, response) = await app.SyncAsync(token, Req(null, Album("c", T0.AddHours(1), "Older"))); + Assert.Equal("Newer", response!.Albums.Single().Artist); + + var (_, view) = await app.SyncAsync(token, Req()); + Assert.Equal("Newer", view!.Albums.Single().Artist); + } + + [Fact] + public async Task A_newer_change_replaces_an_older_one() + { + var (_, token) = await app.NewUserAsync("newer"); + await app.SyncAsync(token, Req(null, Album("n", T0, "Old"))); + await app.SyncAsync(token, Req(null, Album("n", T0.AddMinutes(1), "New"))); + Assert.Equal("New", (await app.SyncAsync(token, Req())).Body!.Albums.Single().Artist); + } + + [Fact] + public async Task On_a_tie_the_server_keeps_its_row() + { + var (_, token) = await app.NewUserAsync("tie"); + await app.SyncAsync(token, Req(null, Album("t", T0, "First"))); + var (_, answer) = await app.SyncAsync(token, Req(null, Album("t", T0, "Second"))); + + Assert.Equal("First", answer!.Albums.Single().Artist); + Assert.Equal("First", (await app.SyncAsync(token, Req())).Body!.Albums.Single().Artist); + } + + [Fact] + public async Task A_deletion_is_a_soft_row_other_PCs_receive_and_an_older_deletion_is_ignored() + { + var (_, token) = await app.NewUserAsync("deletes"); + await app.SyncAsync(token, Req(null, Album("d", T0.AddHours(1)))); + await app.SyncAsync(token, Req(null, Album("d", T0, deleted: true))); // older: ignored + Assert.False((await app.SyncAsync(token, Req())).Body!.Albums.Single().Deleted); + + await app.SyncAsync(token, Req(null, Album("d", T0.AddHours(2), deleted: true))); + var (_, view) = await app.SyncAsync(token, Req()); + Assert.True(view!.Albums.Single().Deleted); + + await app.SyncAsync(token, Req(null, Album("d", T0.AddHours(3)))); // newer change brings it back + Assert.False((await app.SyncAsync(token, Req())).Body!.Albums.Single().Deleted); + } + + // ── Limits ── + + [Fact] + public async Task More_than_a_thousand_albums_in_a_request_is_a_400() + { + var (_, token) = await app.NewUserAsync("too-many"); + var albums = Enumerable.Range(0, 1001).Select(i => Album("x" + i)).ToArray(); + Assert.Equal(HttpStatusCode.BadRequest, (await app.SyncAsync(token, Req(null, albums))).Status); + } + + [Fact] + public async Task A_response_holds_at_most_a_thousand_albums_and_the_client_can_resume() + { + var (_, uploader) = await app.NewUserAsync("page-up"); + for (int batch = 0; batch < 3; batch++) + Assert.Equal(HttpStatusCode.OK, (await app.SyncAsync(uploader, Req(null, + Enumerable.Range(0, batch == 2 ? 500 : 1000).Select(i => Album($"p{batch}-{i}")).ToArray()))).Status); + + var (_, puller) = (0, uploader); // same user, another PC (no since) + var seen = new HashSet(); + DateTime? since = null; + int pages = 0; + while (true) + { + var (_, body) = await app.SyncAsync(puller, Req(since)); + Assert.InRange(body!.Albums.Count, 0, 1000); + if (body.Albums.Count == 0) break; + foreach (var a in body.Albums) seen.Add(a.Uid); + since = body.ServerTime; + Assert.InRange(++pages, 1, 10); + } + Assert.Equal(2500, seen.Count); + Assert.True(pages >= 3); + } + + [Fact] + public async Task Text_is_cut_at_500_characters() + { + var (_, token) = await app.NewUserAsync("cut"); + var album = Album("long") with { Artist = new string('a', 900), Source = new string('b', 501), CoverUrl = "https://x/" + new string('c', 600) }; + await app.SyncAsync(token, Req(null, album)); + var stored = (await app.SyncAsync(token, Req())).Body!.Albums.Single(); + Assert.Equal(500, stored.Artist.Length); + Assert.Equal(500, stored.Source!.Length); + Assert.Equal(500, stored.CoverUrl!.Length); + } + + [Fact] + public async Task Unknown_fields_are_ignored() + { + var (_, token) = await app.NewUserAsync("unknown"); + const string json = """ + {"since":null,"future":{"a":1},"albums":[{"uid":"u1","artist":"A","album":"B","year":2000,"source":null,"coverUrl":null, + "spotifyId":null,"tidalId":null,"addedAt":"2026-10-01T12:00:00Z","listenedAt":null,"rating":-1, + "updatedAt":"2026-10-02T12:00:00Z","deleted":false,"extra":"x"}],"settings":null} + """; + using var response = await app.CreateClient().SendAsync(SyncFactory.Post(token, json)); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("u1", (await app.SyncAsync(token, Req())).Body!.Albums.Single().Uid); + } + + [Theory] + [InlineData("not json")] + [InlineData("[]")] + [InlineData("""{"albums":[{"uid":"../evil","artist":"a","album":"b","addedAt":"2026-10-01T12:00:00Z","updatedAt":"2026-10-01T12:00:00Z","rating":-1,"deleted":false}]}""")] + [InlineData("""{"albums":[{"uid":"","artist":"a","album":"b","addedAt":"2026-10-01T12:00:00Z","updatedAt":"2026-10-01T12:00:00Z","rating":-1,"deleted":false}]}""")] + public async Task Malformed_requests_are_a_400_with_an_empty_body(string json) + { + var (_, token) = await app.NewUserAsync("bad-json"); + using var response = await app.CreateClient().SendAsync(SyncFactory.Post(token, json)); + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Equal("", await response.Content.ReadAsStringAsync()); + } + + [Fact] + public async Task A_change_dated_far_in_the_future_cannot_win_forever() + { + var (_, token) = await app.NewUserAsync("future"); + await app.SyncAsync(token, Req(null, Album("f", DateTime.UtcNow.AddYears(50), "Poison"))); + await app.SyncAsync(token, Req(null, Album("f", DateTime.UtcNow.AddHours(1), "Fixed"))); + Assert.Equal("Fixed", (await app.SyncAsync(token, Req())).Body!.Albums.Single().Artist); + } + + [Fact] + public async Task Ratings_and_years_outside_their_range_are_made_valid() + { + var (_, token) = await app.NewUserAsync("range"); + await app.SyncAsync(token, Req(null, Album("r") with { Rating = 99, Year = -5 })); + var stored = (await app.SyncAsync(token, Req())).Body!.Albums.Single(); + Assert.Equal(5, stored.Rating); + Assert.Null(stored.Year); + } + + // ── Settings ── + + [Fact] + public async Task Settings_sync_newest_wins_and_the_secrets_are_not_plain_on_disk() + { + var (userId, token) = await app.NewUserAsync("settings"); + var mine = new SyncSettings("sp-id", "SPOTIFY-SECRET-VALUE-123", "ti-id", "TIDAL-SECRET-VALUE-456", "Spotify", "ES", T0.AddHours(2)); + await app.SyncAsync(token, new SyncRequest(null, [], mine)); + + var older = mine with { SpotifyClientSecret = "OLD", UpdatedAt = T0 }; + var (_, answer) = await app.SyncAsync(token, new SyncRequest(null, [], older)); + Assert.Equal("SPOTIFY-SECRET-VALUE-123", answer!.Settings!.SpotifyClientSecret); // rejected: the server's come back + + var (_, other) = await app.SyncAsync(token, Req()); + Assert.Equal(mine, other!.Settings); + + foreach (var file in Directory.EnumerateFiles(app.DataDir, "*", SearchOption.AllDirectories)) + { + var text = System.Text.Encoding.Latin1.GetString(File.ReadAllBytes(file)); + Assert.DoesNotContain("SPOTIFY-SECRET-VALUE-123", text); + Assert.DoesNotContain("TIDAL-SECRET-VALUE-456", text); + } + Assert.Equal("SPOTIFY-SECRET-VALUE-123", app.Stores.LoadSettings(userId).SpotifyClientSecret); + } + + [Fact] + public async Task Settings_saved_on_the_web_side_reach_the_PCs() + { + var (userId, token) = await app.NewUserAsync("web-settings"); + app.Stores.SaveSettings(userId, new AppSettings { CountryCode = "UY", SharedSettingsUpdatedAt = T0 }); + var (_, body) = await app.SyncAsync(token, Req()); + Assert.Equal("UY", body!.Settings!.CountryCode); + } +} + +public sealed class SyncLimitTests +{ + private sealed class Tiny() : SyncFactory(new() { ["Queueify:Sync:MaxBodyBytes"] = "2000" }); + private sealed class Throttled() : SyncFactory(new() { ["Queueify:Sync:RequestsPerMinute"] = "3" }); + + [Fact] + public async Task A_body_over_the_size_limit_is_413() + { + await using var app = new Tiny(); + var (_, token) = await app.NewUserAsync(); + using var response = await app.CreateClient().SendAsync(SyncFactory.Post(token, """{"albums":[],"pad":"%s"}""".Replace("%s", new string('x', 5000)))); + Assert.Equal(HttpStatusCode.RequestEntityTooLarge, response.StatusCode); + } + + [Fact] + public async Task Too_many_requests_in_a_minute_are_429() + { + await using var app = new Throttled(); + var (_, token) = await app.NewUserAsync(); + var statuses = new List(); + for (int i = 0; i < 5; i++) statuses.Add((await app.SyncAsync(token, new SyncRequest(null, [], null))).Status); + Assert.Equal(HttpStatusCode.OK, statuses[0]); + Assert.Contains(HttpStatusCode.TooManyRequests, statuses); + } + + [Fact] + public async Task Guessing_tokens_is_throttled_too() + { + await using var app = new Throttled(); + var statuses = new List(); + for (int i = 0; i < 6; i++) + { + using var response = await app.CreateClient().SendAsync(SyncFactory.Post("qw_wrong" + i, "{}")); + statuses.Add(response.StatusCode); + } + Assert.Contains(HttpStatusCode.TooManyRequests, statuses); + } +} diff --git a/Queueify.Web.Tests/Sync/SyncFactory.cs b/Queueify.Web.Tests/Sync/SyncFactory.cs new file mode 100644 index 0000000..fc43a5d --- /dev/null +++ b/Queueify.Web.Tests/Sync/SyncFactory.cs @@ -0,0 +1,69 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Text; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Queueify.Services; +using Queueify.Web.Data; +using Queueify.Web.Storage; +using Queueify.Web.Sync; + +namespace Queueify.Web.Tests.Sync; + +/// The real app on a scratch data folder and a scratch Identity database; nothing of the user's is touched. +public class SyncFactory : WebApplicationFactory +{ + private readonly Dictionary _settings; + + public SyncFactory() : this([]) { } + + protected SyncFactory(Dictionary settings) => _settings = settings; + + public string Dir { get; } = Path.Combine(Path.GetTempPath(), "qw-sync-" + Guid.NewGuid().ToString("N")); + public string DataDir => Path.Combine(Dir, "data"); + + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.UseSetting("Queueify:DataDir", DataDir); + builder.UseSetting("ConnectionStrings:DefaultConnection", $"DataSource={Path.Combine(Dir, "identity.db")};Pooling=False"); + // Every test request comes from the same address, so the limit is lifted unless a test is about it. + builder.UseSetting("Queueify:Sync:RequestsPerMinute", "100000"); + foreach (var (key, value) in _settings) builder.UseSetting(key, value); + } + + /// A confirmed user with one token; returns the user id and the token text. + public async Task<(string UserId, string Token)> NewUserAsync(string name = "alice") + { + name += Guid.NewGuid().ToString("N")[..6]; + using var scope = Services.CreateScope(); + var users = scope.ServiceProvider.GetRequiredService>(); + var user = new ApplicationUser { UserName = name + "@example.org", Email = name + "@example.org", EmailConfirmed = true }; + Assert.True((await users.CreateAsync(user, "Passw0rd!-" + name)).Succeeded); + var created = await scope.ServiceProvider.GetRequiredService().CreateAsync(user.Id, "test PC"); + return (user.Id, created.Token); + } + + public UserStores Stores => Services.GetRequiredService(); + + public static HttpRequestMessage Post(string? token, string json, string path = "/api/sync") + { + var request = new HttpRequestMessage(HttpMethod.Post, path) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; + if (token != null) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + return request; + } + + public async Task<(HttpStatusCode Status, SyncResponse? Body)> SyncAsync(string? token, SyncRequest request) + { + using var response = await CreateClient().SendAsync(Post(token, System.Text.Json.JsonSerializer.Serialize(request, SyncJson.Default.SyncRequest))); + var text = await response.Content.ReadAsStringAsync(); + return (response.StatusCode, response.IsSuccessStatusCode ? System.Text.Json.JsonSerializer.Deserialize(text, SyncJson.Default.SyncResponse) : null); + } + + public override async ValueTask DisposeAsync() + { + await base.DisposeAsync(); + try { Directory.Delete(Dir, true); } catch (IOException) { } catch (UnauthorizedAccessException) { } + } +} diff --git a/Queueify.Web/Components/Pages/ConnectPc.razor b/Queueify.Web/Components/Pages/ConnectPc.razor new file mode 100644 index 0000000..21639c2 --- /dev/null +++ b/Queueify.Web/Components/Pages/ConnectPc.razor @@ -0,0 +1,114 @@ +@page "/connect" +@attribute [Authorize] +@rendermode InteractiveServer +@using Microsoft.AspNetCore.Authorization +@using Queueify.Services +@using Queueify.Web.Sync +@inject PersonalAccessTokens Tokens +@inject AuthenticationStateProvider Auth +@inject NavigationManager Navigation + +@Loc.T("connect.title") + +

@Loc.T("connect.title")

+

@Loc.T("connect.intro")

+ +@if (_connectText != null) +{ + +} + +@if (_limitReached) +{ +

@Loc.T("connect.limit")

+} + +
+ + + +
+ +

@Loc.T("connect.tokens")

+@if (_tokens.Count == 0) +{ +

@Loc.T("connect.empty")

+} +else +{ + + + + + + + + + + + @foreach (var token in _tokens) + { + + + + + + + } + +
@Loc.T("connect.name")@Loc.T("connect.created")@Loc.T("connect.last_used")
@token.Name@token.CreatedAt.ToString("yyyy-MM-dd HH:mm") UTC@(token.LastUsedAt is DateTime used ? used.ToString("yyyy-MM-dd HH:mm") + " UTC" : Loc.T("connect.never")) + @if (token.RevokedAt != null) + { + @Loc.T("connect.revoked") + } + else + { + + } +
+} + +@code { + private IReadOnlyList _tokens = []; + private string _name = ""; + private string? _connectText; + private bool _limitReached; + private string? _userId; + + protected override async Task OnInitializedAsync() + { + _userId = (await Auth.GetAuthenticationStateAsync()).User.UserId(); + await LoadAsync(); + } + + private async Task LoadAsync() => _tokens = _userId == null ? [] : await Tokens.ListAsync(_userId); + + private async Task CreateAsync() + { + if (_userId == null || string.IsNullOrWhiteSpace(_name)) return; + _limitReached = false; + try + { + var created = await Tokens.CreateAsync(_userId, _name); + _connectText = SyncConnect.Format(Navigation.BaseUri, created.Token); + _name = ""; + } + catch (InvalidOperationException) + { + _limitReached = true; + } + await LoadAsync(); + } + + private async Task RevokeAsync(Guid id) + { + if (_userId == null) return; + await Tokens.RevokeAsync(_userId, id); + _connectText = null; + await LoadAsync(); + } +} diff --git a/Queueify.Web/Data/ApplicationDbContext.cs b/Queueify.Web/Data/ApplicationDbContext.cs index a726eaa..6a312d1 100644 --- a/Queueify.Web/Data/ApplicationDbContext.cs +++ b/Queueify.Web/Data/ApplicationDbContext.cs @@ -1,8 +1,16 @@ using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; +using Queueify.Web.Sync; namespace Queueify.Web.Data; public class ApplicationDbContext(DbContextOptions options) : IdentityDbContext(options) { + public DbSet PersonalAccessTokens => Set(); + + protected override void OnModelCreating(ModelBuilder builder) + { + base.OnModelCreating(builder); + PersonalAccessToken.Configure(builder); + } } diff --git a/Queueify.Web/Data/Migrations/20261014120000_AddPersonalAccessTokens.Designer.cs b/Queueify.Web/Data/Migrations/20261014120000_AddPersonalAccessTokens.Designer.cs new file mode 100644 index 0000000..f39ae0c --- /dev/null +++ b/Queueify.Web/Data/Migrations/20261014120000_AddPersonalAccessTokens.Designer.cs @@ -0,0 +1,398 @@ +// +using System; +using Queueify.Web.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Queueify.Web.Migrations +{ + [DbContext(typeof(ApplicationDbContext))] + [Migration("20261014120000_AddPersonalAccessTokens")] + partial class AddPersonalAccessTokens + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.0"); + + modelBuilder.Entity("Queueify.Web.Data.ApplicationUser", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PhoneNumber") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserPasskey", b => + { + b.Property("CredentialId") + .HasMaxLength(1024) + .HasColumnType("BLOB"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("CredentialId"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserPasskeys", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("LoginProvider") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("Queueify.Web.Sync.PersonalAccessToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("LastUsedAt") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RevokedAt") + .HasColumnType("TEXT"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("BLOB"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("PersonalAccessTokens", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Queueify.Web.Data.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Queueify.Web.Data.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserPasskey", b => + { + b.HasOne("Queueify.Web.Data.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsOne("Microsoft.AspNetCore.Identity.IdentityPasskeyData", "Data", b1 => + { + b1.Property("IdentityUserPasskeyCredentialId") + .HasColumnType("BLOB"); + + b1.Property("AttestationObject") + .IsRequired() + .HasColumnType("BLOB"); + + b1.Property("ClientDataJson") + .IsRequired() + .HasColumnType("BLOB"); + + b1.Property("CreatedAt") + .HasColumnType("TEXT"); + + b1.Property("IsBackedUp") + .HasColumnType("INTEGER"); + + b1.Property("IsBackupEligible") + .HasColumnType("INTEGER"); + + b1.Property("IsUserVerified") + .HasColumnType("INTEGER"); + + b1.Property("Name") + .HasColumnType("TEXT"); + + b1.Property("PublicKey") + .IsRequired() + .HasColumnType("BLOB"); + + b1.Property("SignCount") + .HasColumnType("INTEGER"); + + b1.PrimitiveCollection("Transports") + .HasColumnType("TEXT"); + + b1.HasKey("IdentityUserPasskeyCredentialId"); + + b1.ToTable("AspNetUserPasskeys"); + + b1.ToJson("Data"); + + b1.WithOwner() + .HasForeignKey("IdentityUserPasskeyCredentialId"); + }); + + b.Navigation("Data") + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Queueify.Web.Data.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Queueify.Web.Data.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Queueify.Web.Sync.PersonalAccessToken", b => + { + b.HasOne("Queueify.Web.Data.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Queueify.Web/Data/Migrations/20261014120000_AddPersonalAccessTokens.cs b/Queueify.Web/Data/Migrations/20261014120000_AddPersonalAccessTokens.cs new file mode 100644 index 0000000..451e344 --- /dev/null +++ b/Queueify.Web/Data/Migrations/20261014120000_AddPersonalAccessTokens.cs @@ -0,0 +1,56 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Queueify.Web.Migrations +{ + /// + public partial class AddPersonalAccessTokens : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "PersonalAccessTokens", + columns: table => new + { + Id = table.Column(type: "TEXT", nullable: false), + UserId = table.Column(type: "TEXT", nullable: false), + Name = table.Column(type: "TEXT", maxLength: 100, nullable: false), + TokenHash = table.Column(type: "BLOB", maxLength: 32, nullable: false), + CreatedAt = table.Column(type: "TEXT", nullable: false), + LastUsedAt = table.Column(type: "TEXT", nullable: true), + RevokedAt = table.Column(type: "TEXT", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_PersonalAccessTokens", x => x.Id); + table.ForeignKey( + name: "FK_PersonalAccessTokens_AspNetUsers_UserId", + column: x => x.UserId, + principalTable: "AspNetUsers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_PersonalAccessTokens_TokenHash", + table: "PersonalAccessTokens", + column: "TokenHash", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_PersonalAccessTokens_UserId", + table: "PersonalAccessTokens", + column: "UserId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "PersonalAccessTokens"); + } + } +} diff --git a/Queueify.Web/Data/Migrations/ApplicationDbContextModelSnapshot.cs b/Queueify.Web/Data/Migrations/ApplicationDbContextModelSnapshot.cs index d697e1e..d22fa3b 100644 --- a/Queueify.Web/Data/Migrations/ApplicationDbContextModelSnapshot.cs +++ b/Queueify.Web/Data/Migrations/ApplicationDbContextModelSnapshot.cs @@ -231,6 +231,45 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.ToTable("AspNetUserTokens", (string)null); }); + modelBuilder.Entity("Queueify.Web.Sync.PersonalAccessToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("LastUsedAt") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RevokedAt") + .HasColumnType("TEXT"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("BLOB"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("PersonalAccessTokens", (string)null); + }); + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) @@ -341,6 +380,15 @@ protected override void BuildModel(ModelBuilder modelBuilder) .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); + + modelBuilder.Entity("Queueify.Web.Sync.PersonalAccessToken", b => + { + b.HasOne("Queueify.Web.Data.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); #pragma warning restore 612, 618 } } diff --git a/Queueify.Web/Program.cs b/Queueify.Web/Program.cs index 6fa04c5..4fcae93 100644 --- a/Queueify.Web/Program.cs +++ b/Queueify.Web/Program.cs @@ -4,6 +4,7 @@ using Queueify.Web.Components; using Queueify.Web.Components.Account; using Queueify.Web.Data; +using Queueify.Web.Sync; var builder = WebApplication.CreateBuilder(args); @@ -37,6 +38,7 @@ .AddDefaultTokenProviders(); builder.Services.AddSingleton, IdentityNoOpEmailSender>(); +builder.Services.AddQueueifySync(); var app = builder.Build(); @@ -63,6 +65,8 @@ // Add additional endpoints required by the Identity /Account Razor components. app.MapAdditionalIdentityEndpoints(); +app.MapQueueifySync(); + app.MapGet("/healthz", () => Results.Ok("ok")).AllowAnonymous(); app.Run(); diff --git a/Queueify.Web/Storage/UserStores.cs b/Queueify.Web/Storage/UserStores.cs index d4a2e7c..d8ad06c 100644 --- a/Queueify.Web/Storage/UserStores.cs +++ b/Queueify.Web/Storage/UserStores.cs @@ -1,10 +1,17 @@ +using System.Security.Cryptography; +using System.Text.Json; +using Microsoft.AspNetCore.DataProtection; using Queueify.Models; using Queueify.Services; namespace Queueify.Web.Storage; -/// One folder per user under the data root, holding their queue (queueify.db) and settings.json. -public sealed class UserStores(string root) +/// +/// One folder per user under the data root, holding their queue (queueify.db) and settings.json. +/// With a the Spotify and Tidal secrets are kept encrypted in secrets.dat, +/// bound to the user, and never written to settings.json. +/// +public sealed class UserStores(string root, IDataProtector? protector = null) { private string FolderOf(string userId) { @@ -13,10 +20,59 @@ private string FolderOf(string userId) return Path.Combine(root, userId); } - public BacklogStore QueueOf(string userId) => new(Path.Combine(FolderOf(userId), "queueify.db")); + public string QueuePathOf(string userId) => Path.Combine(FolderOf(userId), "queueify.db"); - public AppSettings LoadSettings(string userId) => AppData.LoadSettings(Path.Combine(FolderOf(userId), "settings.json")); + public BacklogStore QueueOf(string userId) => new(QueuePathOf(userId)); - public void SaveSettings(string userId, AppSettings settings) => - AppData.SaveSettings(settings, Path.Combine(FolderOf(userId), "settings.json")); + public AppSettings LoadSettings(string userId) + { + var folder = FolderOf(userId); + var settings = AppData.LoadSettings(Path.Combine(folder, "settings.json")); + var secretsPath = Path.Combine(folder, "secrets.dat"); + if (protector != null && File.Exists(secretsPath)) + { + try + { + var secrets = JsonSerializer.Deserialize>( + protector.CreateProtector(userId).Unprotect(File.ReadAllText(secretsPath))) ?? []; + settings.SpotifyClientSecret = secrets.GetValueOrDefault(nameof(AppSettings.SpotifyClientSecret), ""); + settings.TidalClientSecret = secrets.GetValueOrDefault(nameof(AppSettings.TidalClientSecret), ""); + } + catch (Exception ex) when (ex is CryptographicException or JsonException or IOException) + { + // Lost keys or a damaged file: the user enters the secrets again. + settings.SpotifyClientSecret = settings.TidalClientSecret = ""; + } + } + return settings; + } + + public void SaveSettings(string userId, AppSettings settings) + { + var folder = FolderOf(userId); + if (protector == null) + { + AppData.SaveSettings(settings, Path.Combine(folder, "settings.json")); + return; + } + + Directory.CreateDirectory(folder); + var secrets = JsonSerializer.Serialize(new Dictionary + { + [nameof(AppSettings.SpotifyClientSecret)] = settings.SpotifyClientSecret, + [nameof(AppSettings.TidalClientSecret)] = settings.TidalClientSecret, + }); + WriteAtomically(Path.Combine(folder, "secrets.dat"), protector.CreateProtector(userId).Protect(secrets)); + + var plain = settings.Clone(); + plain.SpotifyClientSecret = plain.TidalClientSecret = ""; + AppData.SaveSettings(plain, Path.Combine(folder, "settings.json")); + } + + private static void WriteAtomically(string path, string text) + { + var temp = path + ".tmp"; + File.WriteAllText(temp, text); + File.Move(temp, path, overwrite: true); + } } diff --git a/Queueify.Web/Sync/PersonalAccessToken.cs b/Queueify.Web/Sync/PersonalAccessToken.cs new file mode 100644 index 0000000..24d86f8 --- /dev/null +++ b/Queueify.Web/Sync/PersonalAccessToken.cs @@ -0,0 +1,28 @@ +using Microsoft.EntityFrameworkCore; +using Queueify.Web.Data; + +namespace Queueify.Web.Sync; + +/// A token a PC uses to sync one user's queue. Only its SHA-256 hash is kept; the token itself is shown once. +public sealed class PersonalAccessToken +{ + public Guid Id { get; set; } + public string UserId { get; set; } = ""; + public string Name { get; set; } = ""; + public byte[] TokenHash { get; set; } = []; + public DateTime CreatedAt { get; set; } + public DateTime? LastUsedAt { get; set; } + public DateTime? RevokedAt { get; set; } + + internal static void Configure(ModelBuilder model) => + model.Entity(t => + { + t.ToTable("PersonalAccessTokens"); + t.HasKey(x => x.Id); + t.Property(x => x.Name).HasMaxLength(100); + t.Property(x => x.TokenHash).HasMaxLength(32); + t.HasIndex(x => x.TokenHash).IsUnique(); + t.HasIndex(x => x.UserId); + t.HasOne().WithMany().HasForeignKey(x => x.UserId).OnDelete(DeleteBehavior.Cascade); + }); +} diff --git a/Queueify.Web/Sync/PersonalAccessTokens.cs b/Queueify.Web/Sync/PersonalAccessTokens.cs new file mode 100644 index 0000000..a0ef72e --- /dev/null +++ b/Queueify.Web/Sync/PersonalAccessTokens.cs @@ -0,0 +1,73 @@ +using System.Security.Cryptography; +using System.Text; +using Microsoft.EntityFrameworkCore; +using Queueify.Web.Data; + +namespace Queueify.Web.Sync; + +public sealed record NewToken(PersonalAccessToken Info, string Token); + +/// Creates, lists, revokes and checks the personal access tokens that let a PC sync one user's queue. +public sealed class PersonalAccessTokens(ApplicationDbContext db, TimeProvider clock) +{ + public const int MaxPerUser = 20; + public const int MaxNameLength = 100; + private const string Prefix = "qw_"; + private const int TokenLength = 3 + 43; // "qw_" + 32 bytes in base64url + + public static byte[] Hash(string token) => SHA256.HashData(Encoding.UTF8.GetBytes(token)); + + private static bool LooksLikeToken(string token) => + token.Length == TokenLength && token.StartsWith(Prefix, StringComparison.Ordinal) + && token.AsSpan(Prefix.Length).IndexOfAnyExcept("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_") < 0; + + /// The token text is returned here and nowhere else: only its hash is stored. + public async Task CreateAsync(string userId, string name) + { + name = name.Trim(); + if (name.Length > MaxNameLength) name = name[..MaxNameLength]; + if (await db.PersonalAccessTokens.CountAsync(t => t.UserId == userId && t.RevokedAt == null) >= MaxPerUser) + throw new InvalidOperationException("Too many tokens."); + + var token = Prefix + Base64Url(RandomNumberGenerator.GetBytes(32)); + var row = new PersonalAccessToken + { + Id = Guid.NewGuid(), UserId = userId, Name = name, TokenHash = Hash(token), CreatedAt = clock.GetUtcNow().UtcDateTime, + }; + db.PersonalAccessTokens.Add(row); + await db.SaveChangesAsync(); + return new NewToken(row, token); + } + + public async Task> ListAsync(string userId) => + await db.PersonalAccessTokens.AsNoTracking().Where(t => t.UserId == userId).OrderBy(t => t.CreatedAt).ToListAsync(); + + /// Revokes one of the user's own tokens; false when it isn't theirs or doesn't exist. + public async Task RevokeAsync(string userId, Guid id) + { + var row = await db.PersonalAccessTokens.FirstOrDefaultAsync(t => t.Id == id && t.UserId == userId); + if (row == null) return false; + row.RevokedAt ??= clock.GetUtcNow().UtcDateTime; + await db.SaveChangesAsync(); + return true; + } + + /// The id of the user a live token belongs to, or null for anything else. + public async Task ValidateAsync(string token) + { + if (!LooksLikeToken(token)) return null; + var hash = Hash(token); + var row = await db.PersonalAccessTokens.FirstOrDefaultAsync(t => t.TokenHash == hash); + if (row == null || !CryptographicOperations.FixedTimeEquals(row.TokenHash, hash) || row.RevokedAt != null) return null; + + var now = clock.GetUtcNow().UtcDateTime; + if (row.LastUsedAt == null || now - row.LastUsedAt > TimeSpan.FromMinutes(1)) + { + // Only the timestamp changes, so a revocation made meanwhile is never undone. + await db.PersonalAccessTokens.Where(t => t.Id == row.Id).ExecuteUpdateAsync(s => s.SetProperty(t => t.LastUsedAt, now)); + } + return row.UserId; + } + + private static string Base64Url(byte[] bytes) => Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); +} diff --git a/Queueify.Web/Sync/SyncEngine.cs b/Queueify.Web/Sync/SyncEngine.cs new file mode 100644 index 0000000..0d69f7f --- /dev/null +++ b/Queueify.Web/Sync/SyncEngine.cs @@ -0,0 +1,291 @@ +using System.Collections.Concurrent; +using System.Globalization; +using System.Text.RegularExpressions; +using Microsoft.Data.Sqlite; +using Queueify.Models; +using Queueify.Services; +using Queueify.Web.Storage; + +namespace Queueify.Web.Sync; + +/// +/// The server side of POST /api/sync (ADR-0010) on one user's queue. The queue is the same SQLite file +/// writes, plus a server_time column and a sync_meta table that desktop +/// databases never have. Rows changed through by the web pages are flagged dirty; +/// each sync stamps them, so they reach the PCs without the pages knowing about sync. +/// +public sealed partial class SyncEngine(UserStores stores, TimeProvider clock) +{ + public const int MaxAlbums = 1000; + public const int MaxText = 500; + private static readonly TimeSpan MaxClockAhead = TimeSpan.FromMinutes(10); + + private const string Columns = + "uid, artist, album, year, source, cover_url, spotify_id, tidal_id, added_at, listened_at, rating, updated_at, deleted, server_time"; + + private readonly ConcurrentDictionary _gates = new(); + private readonly ConcurrentDictionary _prepared = new(); + + [GeneratedRegex("^[A-Za-z0-9_-]{1,64}$")] + private static partial Regex UidPattern(); + + /// The answer to a sync, or null when the request is malformed (the endpoint answers 400). + public async Task RunAsync(string userId, SyncRequest request) + { + var clean = Clean(request); + if (clean == null) return null; + + var gate = _gates.GetOrAdd(userId, _ => new SemaphoreSlim(1, 1)); + await gate.WaitAsync(); + try { return await Task.Run(() => Apply(userId, clean)); } + finally { gate.Release(); } + } + + private sealed record Cleaned(long SinceTicks, List Albums, SyncSettings? Settings); + + private Cleaned? Clean(SyncRequest request) + { + var albums = request.Albums ?? []; + if (albums.Count > MaxAlbums) return null; + var latest = clock.GetUtcNow().UtcDateTime + MaxClockAhead; + + var clean = new List(albums.Count); + foreach (var a in albums) + { + if (a == null || a.Uid == null || !UidPattern().IsMatch(a.Uid)) return null; + clean.Add(new SyncAlbum( + a.Uid, Cut(a.Artist), Cut(a.Album), a.Year is >= 1 and <= 9999 ? a.Year : null, + CutOrNull(a.Source), CutOrNull(a.CoverUrl), CutOrNull(a.SpotifyId), CutOrNull(a.TidalId), + Utc(a.AddedAt), a.ListenedAt is DateTime l ? Utc(l) : null, Rating(a.Rating), + Min(Utc(a.UpdatedAt), latest), a.Deleted)); + } + + SyncSettings? settings = null; + if (request.Settings is { } s) + { + var shared = new AppSettings + { + SpotifyClientId = Cut(s.SpotifyClientId), SpotifyClientSecret = Cut(s.SpotifyClientSecret), + TidalClientId = Cut(s.TidalClientId), TidalClientSecret = Cut(s.TidalClientSecret), + PreferredService = Cut(s.PreferredService), CountryCode = Cut(s.CountryCode), + }; + shared.Normalize(); + settings = new SyncSettings(shared.SpotifyClientId, shared.SpotifyClientSecret, shared.TidalClientId, + shared.TidalClientSecret, shared.PreferredService, shared.CountryCode, Min(Utc(s.UpdatedAt), latest)); + } + + return new Cleaned(request.Since is DateTime since ? Utc(since).Ticks : 0, clean, settings); + } + + private SyncResponse Apply(string userId, Cleaned request) + { + var path = stores.QueuePathOf(userId); + Prepare(path); + using var db = Open(path); + using var tx = db.BeginTransaction(); + + // Takes the write lock before anything is read, so two writers can't deadlock on an upgrade. + Execute(db, "INSERT OR IGNORE INTO sync_meta (key, value) VALUES ('last_stamp', 0)"); + long last = Meta(db, "last_stamp"); + long nowTicks = clock.GetUtcNow().UtcDateTime.Ticks / 10 * 10; + long Next() => last = Math.Max(last + 10, nowTicks); + + // Changes made through BacklogStore (the web pages) get their stamp now. + foreach (var uid in Strings(db, "SELECT uid FROM items WHERE dirty = 1")) + Execute(db, "UPDATE items SET server_time = $t, dirty = 0 WHERE uid = $uid AND dirty = 1", ("$t", Next()), ("$uid", uid)); + + var settings = stores.LoadSettings(userId); + long settingsTicks = settings.SharedSettingsUpdatedAt is DateTime su ? Utc(su).Ticks : 0; + if (settingsTicks != 0 && settingsTicks != Meta(db, "settings_seen")) + { + SetMeta(db, "settings_stamp", Next()); + SetMeta(db, "settings_seen", settingsTicks); + } + + // Newest wins; on a tie the server keeps its row. A row the server refuses is stamped again, so it + // goes back to the sender in this very response and the PC converges. + var accepted = new HashSet(); + foreach (var incoming in request.Albums) + { + var existing = Get(db, incoming.Uid); + if (existing == null || incoming.UpdatedAt > existing.UpdatedAt) + { + Upsert(db, incoming, Next()); + accepted.Add(incoming.Uid); + } + else if (existing != incoming) + Execute(db, "UPDATE items SET server_time = $t WHERE uid = $uid", ("$t", Next()), ("$uid", incoming.Uid)); + } + + bool settingsAccepted = false; + if (request.Settings is { } sent) + { + if (sent.UpdatedAt.Ticks > settingsTicks) + { + settings.CopySharedFrom(ToSettings(sent)); + settings.SharedSettingsUpdatedAt = sent.UpdatedAt; + stores.SaveSettings(userId, settings); + SetMeta(db, "settings_stamp", Next()); + SetMeta(db, "settings_seen", sent.UpdatedAt.Ticks); + settingsAccepted = true; + } + else if (ToWire(settings) != sent) + SetMeta(db, "settings_stamp", Next()); + } + + var albums = new List(); + bool truncated = false; + long lastRowStamp = 0; + using (var cmd = db.CreateCommand()) + { + cmd.CommandText = $"SELECT {Columns} FROM items WHERE server_time > $since ORDER BY server_time"; + cmd.Parameters.AddWithValue("$since", request.SinceTicks); + using var r = cmd.ExecuteReader(); + while (r.Read()) + { + var album = ReadAlbum(r); + if (accepted.Contains(album.Uid)) continue; + if (albums.Count == MaxAlbums) { truncated = true; break; } + albums.Add(album); + lastRowStamp = r.GetInt64(13); + } + } + + // A full page ends where it ends, and the client asks again from there; otherwise this sync is the new "now". + long serverTime = truncated ? lastRowStamp : Next(); + long settingsStamp = Meta(db, "settings_stamp"); + SyncSettings? settingsOut = !settingsAccepted && settingsStamp > request.SinceTicks && settingsStamp <= serverTime + ? ToWire(stores.LoadSettings(userId)) + : null; + + SetMeta(db, "last_stamp", last); + tx.Commit(); + return new SyncResponse(new DateTime(serverTime, DateTimeKind.Utc), albums, settingsOut); + } + + private static AppSettings ToSettings(SyncSettings s) => new() + { + SpotifyClientId = s.SpotifyClientId, SpotifyClientSecret = s.SpotifyClientSecret, + TidalClientId = s.TidalClientId, TidalClientSecret = s.TidalClientSecret, + PreferredService = s.PreferredService, CountryCode = s.CountryCode, + }; + + private static SyncSettings ToWire(AppSettings s) => new(s.SpotifyClientId, s.SpotifyClientSecret, s.TidalClientId, + s.TidalClientSecret, s.PreferredService, s.CountryCode, Utc(s.SharedSettingsUpdatedAt ?? DateTime.MinValue)); + + // ── Cleaning ── + + private static string Cut(string? text) + { + if (text == null) return ""; + if (text.Length <= MaxText) return text; + return char.IsHighSurrogate(text[MaxText - 1]) ? text[..(MaxText - 1)] : text[..MaxText]; + } + + private static string? CutOrNull(string? text) => text == null ? null : Cut(text); + + private static double Rating(double rating) => double.IsNaN(rating) ? -1 : Math.Clamp(rating, -1, 5); + + private static DateTime Utc(DateTime d) => d.Kind switch + { + DateTimeKind.Utc => d, + DateTimeKind.Local => d.ToUniversalTime(), + _ => DateTime.SpecifyKind(d, DateTimeKind.Utc), + }; + + private static DateTime Min(DateTime a, DateTime b) => a < b ? a : b; + + // ── SQLite ── + + private static SqliteConnection Open(string path) + { + var db = new SqliteConnection(new SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString()); + db.Open(); + return db; + } + + private void Prepare(string path) + { + if (_prepared.ContainsKey(path)) return; + _ = new BacklogStore(path); // creates the folder and the desktop schema + using var db = Open(path); + bool has = false; + using (var cmd = db.CreateCommand()) + { + cmd.CommandText = "PRAGMA table_info(items)"; + using var r = cmd.ExecuteReader(); + while (r.Read()) has |= r.GetString(1) == "server_time"; + } + if (!has) Execute(db, "ALTER TABLE items ADD COLUMN server_time INTEGER NOT NULL DEFAULT 0"); + Execute(db, "CREATE INDEX IF NOT EXISTS items_server_time ON items(server_time)"); + Execute(db, "CREATE TABLE IF NOT EXISTS sync_meta (key TEXT PRIMARY KEY, value INTEGER NOT NULL)"); + _prepared[path] = true; + } + + private static void Execute(SqliteConnection db, string sql, params (string Name, object Value)[] parameters) + { + using var cmd = db.CreateCommand(); + cmd.CommandText = sql; + foreach (var (name, value) in parameters) cmd.Parameters.AddWithValue(name, value); + cmd.ExecuteNonQuery(); + } + + private static List Strings(SqliteConnection db, string sql) + { + using var cmd = db.CreateCommand(); + cmd.CommandText = sql; + using var r = cmd.ExecuteReader(); + var list = new List(); + while (r.Read()) list.Add(r.GetString(0)); + return list; + } + + private static long Meta(SqliteConnection db, string key) + { + using var cmd = db.CreateCommand(); + cmd.CommandText = "SELECT value FROM sync_meta WHERE key = $key"; + cmd.Parameters.AddWithValue("$key", key); + return cmd.ExecuteScalar() is long v ? v : 0; + } + + private static void SetMeta(SqliteConnection db, string key, long value) => + Execute(db, "INSERT INTO sync_meta (key, value) VALUES ($key, $value) ON CONFLICT(key) DO UPDATE SET value = excluded.value", + ("$key", key), ("$value", value)); + + private static SyncAlbum? Get(SqliteConnection db, string uid) + { + using var cmd = db.CreateCommand(); + cmd.CommandText = $"SELECT {Columns} FROM items WHERE uid = $uid"; + cmd.Parameters.AddWithValue("$uid", uid); + using var r = cmd.ExecuteReader(); + return r.Read() ? ReadAlbum(r) : null; + } + + private static void Upsert(SqliteConnection db, SyncAlbum a, long stamp) => + Execute(db, """ + INSERT INTO items (uid, artist, album, year, source, cover_url, spotify_id, tidal_id, added_at, listened_at, rating, updated_at, dirty, deleted, server_time) + VALUES ($uid, $artist, $album, $year, $source, $cover, $spotify, $tidal, $added, $listened, $rating, $updated, 0, $deleted, $t) + ON CONFLICT(uid) DO UPDATE SET artist = excluded.artist, album = excluded.album, year = excluded.year, + source = excluded.source, cover_url = excluded.cover_url, spotify_id = excluded.spotify_id, + tidal_id = excluded.tidal_id, added_at = excluded.added_at, listened_at = excluded.listened_at, + rating = excluded.rating, updated_at = excluded.updated_at, dirty = 0, deleted = excluded.deleted, + server_time = excluded.server_time + """, + ("$uid", a.Uid), ("$artist", a.Artist), ("$album", a.Album), ("$year", (object?)a.Year ?? DBNull.Value), + ("$source", (object?)a.Source ?? DBNull.Value), ("$cover", (object?)a.CoverUrl ?? DBNull.Value), + ("$spotify", (object?)a.SpotifyId ?? DBNull.Value), ("$tidal", (object?)a.TidalId ?? DBNull.Value), + ("$added", Stamp(a.AddedAt)), ("$listened", a.ListenedAt is DateTime l ? Stamp(l) : DBNull.Value), + ("$rating", a.Rating), ("$updated", Stamp(a.UpdatedAt)), ("$deleted", a.Deleted ? 1 : 0), ("$t", stamp)); + + // The same fixed-width UTC text BacklogStore writes, so desktop code could read the file. + private static string Stamp(DateTime d) => d.ToString("O", CultureInfo.InvariantCulture); + + private static DateTime Parse(string s) => DateTime.Parse(s, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind).ToUniversalTime(); + + private static SyncAlbum ReadAlbum(SqliteDataReader r) => new( + r.GetString(0), r.GetString(1), r.GetString(2), r.IsDBNull(3) ? null : r.GetInt32(3), + r.IsDBNull(4) ? null : r.GetString(4), r.IsDBNull(5) ? null : r.GetString(5), + r.IsDBNull(6) ? null : r.GetString(6), r.IsDBNull(7) ? null : r.GetString(7), + Parse(r.GetString(8)), r.IsDBNull(9) ? null : Parse(r.GetString(9)), r.GetDouble(10), + Parse(r.GetString(11)), r.GetInt64(12) != 0); +} diff --git a/Queueify.Web/Sync/SyncExtensions.cs b/Queueify.Web/Sync/SyncExtensions.cs new file mode 100644 index 0000000..eab69cd --- /dev/null +++ b/Queueify.Web/Sync/SyncExtensions.cs @@ -0,0 +1,101 @@ +using System.Security.Claims; +using System.Text.Json; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using Queueify.Services; +using Queueify.Web.Data; +using Queueify.Web.Storage; + +namespace Queueify.Web.Sync; + +public static class SyncExtensions +{ + private const string Policy = "QueueifySync"; + + /// Per-user stores under Queueify:DataDir, persisted Data Protection keys, tokens and the sync engine. + public static IServiceCollection AddQueueifySync(this IServiceCollection services) + { + // Resolved late, from the final configuration, so tests and hosts can set the folder as they like. + services.AddSingleton(sp => new DataLocation(Path.GetFullPath(sp.GetRequiredService()["Queueify:DataDir"] ?? "./data"))); + + services.AddDataProtection().SetApplicationName("Queueify"); + services.AddOptions() + .Configure((options, data) => + options.XmlRepository = new Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository( + Directory.CreateDirectory(Path.Combine(data.Root, "keys")), NullLoggerFactory.Instance)); + + services.AddSingleton(sp => new UserStores(sp.GetRequiredService().Root, + sp.GetRequiredService().CreateProtector("Queueify.UserSecrets.v1"))); + services.AddSingleton(TimeProvider.System); + services.AddSingleton(); + services.AddSingleton(); + services.AddScoped(); + services.AddHostedService(); + + services.AddAuthentication().AddScheme(TokenAuthenticationHandler.Scheme, null); + services.AddAuthorizationBuilder().AddPolicy(Policy, p => p.AddAuthenticationSchemes(TokenAuthenticationHandler.Scheme).RequireAuthenticatedUser()); + return services; + } + + public static IEndpointRouteBuilder MapQueueifySync(this IEndpointRouteBuilder app) + { + app.MapPost("/api/sync", SyncAsync).RequireAuthorization(Policy).DisableAntiforgery(); + return app; + } + + /// The signed-in user's id (the Identity user id), or null when nobody is signed in. + public static string? UserId(this ClaimsPrincipal user) => user.FindFirstValue(ClaimTypes.NameIdentifier); + + /// Keeps the site's "not found" page out of the API's answers: an error here has no body. + internal static void Quiet(HttpContext http) + { + if (http.Features.Get() is { } pages) pages.Enabled = false; + } + + private static async Task SyncAsync(HttpContext http, SyncEngine engine, SyncLimits limits) + { + Quiet(http); + if (http.User.UserId() is not { } userId) return Results.StatusCode(StatusCodes.Status401Unauthorized); + if (http.Features.Get() is { IsReadOnly: false } cap) + cap.MaxRequestBodySize = limits.MaxBodyBytes; + if (http.Request.ContentLength > limits.MaxBodyBytes) return Results.StatusCode(StatusCodes.Status413PayloadTooLarge); + + // Read through a cap: the header can be missing or wrong (chunked uploads). + using var body = new MemoryStream(); + var buffer = new byte[16 * 1024]; + int read; + while ((read = await http.Request.Body.ReadAsync(buffer)) > 0) + { + body.Write(buffer, 0, read); + if (body.Length > limits.MaxBodyBytes) return Results.StatusCode(StatusCodes.Status413PayloadTooLarge); + } + + SyncRequest? request; + try { request = JsonSerializer.Deserialize(body.GetBuffer().AsSpan(0, (int)body.Length), SyncJson.Default.SyncRequest); } + catch (JsonException) { return Results.StatusCode(StatusCodes.Status400BadRequest); } + if (request == null) return Results.StatusCode(StatusCodes.Status400BadRequest); + + var response = await engine.RunAsync(userId, request); + return response == null + ? Results.StatusCode(StatusCodes.Status400BadRequest) + : Results.Text(JsonSerializer.Serialize(response, SyncJson.Default.SyncResponse), "application/json"); + } +} + +/// The root folder that holds every user's data and the Data Protection keys. +public sealed record DataLocation(string Root); + +/// Brings the Identity database up to date at startup, so a new token table exists before the first request. +internal sealed class IdentityMigrator(IServiceProvider services) : IHostedService +{ + public async Task StartAsync(CancellationToken cancellationToken) + { + using var scope = services.CreateScope(); + await scope.ServiceProvider.GetRequiredService().Database.MigrateAsync(cancellationToken); + } + + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; +} diff --git a/Queueify.Web/Sync/TokenAuthentication.cs b/Queueify.Web/Sync/TokenAuthentication.cs new file mode 100644 index 0000000..3ab3005 --- /dev/null +++ b/Queueify.Web/Sync/TokenAuthentication.cs @@ -0,0 +1,73 @@ +using System.Security.Claims; +using System.Text.Encodings.Web; +using System.Threading.RateLimiting; +using Microsoft.AspNetCore.Authentication; +using Microsoft.Extensions.Options; + +namespace Queueify.Web.Sync; + +/// Bearer personal access tokens, the only way into /api/sync. It never answers with a body. +public sealed class TokenAuthenticationHandler( + IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder, + PersonalAccessTokens tokens, SyncLimits limits) + : AuthenticationHandler(options, logger, encoder) +{ + public const string Scheme = "QueueifyToken"; + private const string ThrottledKey = "queueify.throttled"; + + protected override async Task HandleAuthenticateAsync() + { + // Counted before the token is looked at, so guessing tokens is throttled like real syncing. + using var lease = await limits.Limiter.AcquireAsync(Context, 1); + if (!lease.IsAcquired) + { + Context.Items[ThrottledKey] = true; + return AuthenticateResult.Fail("throttled"); + } + + var header = Request.Headers.Authorization.ToString(); + const string bearer = "Bearer "; + if (!header.StartsWith(bearer, StringComparison.Ordinal)) return AuthenticateResult.NoResult(); + + var userId = await tokens.ValidateAsync(header[bearer.Length..].Trim()); + if (userId == null) return AuthenticateResult.Fail("bad token"); + + var identity = new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, userId)], Scheme); + return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), Scheme)); + } + + protected override Task HandleChallengeAsync(AuthenticationProperties properties) + { + SyncExtensions.Quiet(Context); + Response.StatusCode = Context.Items.ContainsKey(ThrottledKey) ? StatusCodes.Status429TooManyRequests : StatusCodes.Status401Unauthorized; + return Task.CompletedTask; + } + + protected override Task HandleForbiddenAsync(AuthenticationProperties properties) + { + SyncExtensions.Quiet(Context); + Response.StatusCode = StatusCodes.Status401Unauthorized; + return Task.CompletedTask; + } +} + +/// The endpoint's limits, read once from Queueify:Sync. +public sealed class SyncLimits : IDisposable +{ + public SyncLimits(IConfiguration configuration) + { + var section = configuration.GetSection("Queueify:Sync"); + MaxBodyBytes = Math.Max(1, section.GetValue("MaxBodyBytes", 8 * 1024 * 1024)); + var perMinute = Math.Max(1, section.GetValue("RequestsPerMinute", 120)); + Limiter = PartitionedRateLimiter.Create(c => + RateLimitPartition.GetFixedWindowLimiter(c.Connection.RemoteIpAddress?.ToString() ?? "", _ => new FixedWindowRateLimiterOptions + { + PermitLimit = perMinute, Window = TimeSpan.FromMinutes(1), QueueLimit = 0, + })); + } + + public int MaxBodyBytes { get; } + public PartitionedRateLimiter Limiter { get; } + + public void Dispose() => Limiter.Dispose(); +} diff --git a/SECURITY.md b/SECURITY.md index f2ad104..7a7a8c4 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -12,7 +12,8 @@ Only the latest release receives fixes. ## Threat model -Queueify runs with the user's rights on their own PC. It has no servers of its own. +The desktop app runs with the user's rights on their own PC and has no servers of its own. The optional +web server (`Queueify.Web`, [ADR-0010](docs/adr/0010-web-app-and-shared-queue.md)) is run by the user; its rows are marked below. | Asset / boundary | Threat | Mitigation | | --- | --- | --- | @@ -24,6 +25,9 @@ Queueify runs with the user's rights on their own PC. It has no servers of its o | Cover addresses (from the services and from other PCs through sync) | A file or network path reading local files or sending the Windows login to another machine | Only `http` and `https` addresses are loaded (`CoverUrls`, tested). | | The app's unpacked copy (`%LOCALAPPDATA%\Queueify\app`) | Changed files run as Queueify | Only the user (or an admin) can write there, as with any per-user app. The starter is native code and loads its imports from System32 only; the app's working folder is its own. A version's folder is used only once fully unpacked and checked against the SHA-256 in the download. | | Updates (the exe itself) | A tampered or broken download replacing Queueify | Offered only from Queueify's GitHub releases over HTTPS; the download must match the SHA-256 GitHub lists for it, or it's thrown away and the exe left as it was; it's always written to a new file, never into one someone left next to the exe; installing waits for the user's click ([ADR-0009](docs/adr/0009-update-from-github-releases.md)). Not covered: a release published from a taken-over maintainer account (the exe isn't signed). | +| Personal access tokens (the web server's `/connect` page) | A stolen database or backup yields usable tokens; a token leaks from a PC | Only the SHA-256 hash is stored (the tokens are 256 random bits, so a fast hash is enough), compared in constant time. A token is shown once, can be revoked at any time (a revoked token is refused at once), is bound to one user and is limited to `/api/sync`. At most 20 live tokens per user. Not covered: a token stolen from a PC works until the user revokes it. | +| `POST /api/sync` on the web server | Unauthenticated access; guessing tokens; reading or changing another user's queue; oversized or malformed bodies; a PC with a wrong clock overwriting everything | Bearer tokens only (the login cookie is not accepted, so no CSRF); a bad, missing or revoked token is 401 with an empty body; every attempt counts against a per-address limit (429); the user comes from the token, never from the request, and each user has their own folder and database (ids are checked never to leave the data folder); bodies are capped (413) and read through a cap; at most 1,000 albums per request, text cut at 500 characters, ids limited to `[A-Za-z0-9_-]{1,64}`; an `updatedAt` more than ten minutes ahead of the server is pulled back. Behind a reverse proxy the per-address limit needs forwarded headers configured, or all users share one address. Deleted rows are kept (they are how other PCs delete), so a user's database only grows. | +| Spotify and Tidal secrets on the web server | Someone reads `settings.json` or a backup of a user's folder | The secrets are encrypted with ASP.NET Data Protection (per-user purpose) into `secrets.dat`, never written to `settings.json`, and never sent to a browser; they are sent to the user's own PCs over HTTPS when those sync. Not covered: the Data Protection keys sit in `DataDir\keys` (unencrypted on Linux), so a copy of the whole data folder opens the secrets: back up and protect it as one. | | Clipboard | Leaking data | Written only on explicit "Copy" clicks (sync code, security rules); read only on Ctrl+V or Paste. | | Network | Exfiltration | Only Spotify, Tidal, the user's own Firebase project, Windows Update and GitHub (the update check at each start: GitHub sees the address and that Queueify is starting, nothing else; it can be turned off). No telemetry. | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 428b54e..af10371 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -62,6 +62,30 @@ Sync: each PC keeps its own database. Online, a queue is `queues/{key}` in the u 40-hex-character key is the capability (the sync code is `queueify:{project}:{key}`). See [ADR-0003](adr/0003-firestore-rest-sync.md). +## Web server and the sync endpoint + +`Queueify.Web` is the shared database for people who use the web app ([ADR-0010](adr/0010-web-app-and-shared-queue.md)). +Its sync code lives in `Queueify.Web\Sync\` and is wired by `AddQueueifySync` / `MapQueueifySync`. + +| Part | Responsibility | +| --- | --- | +| `UserStores` | One folder per user under `Queueify:DataDir` (default `./data`): `queueify.db` (a `BacklogStore` file), `settings.json` and `secrets.dat`. The Spotify and Tidal secrets are encrypted with Data Protection (bound to the user) into `secrets.dat` and never written to `settings.json`. The Data Protection keys are in `DataDir\keys`. | +| `PersonalAccessTokens` | Tokens `qw_` + 32 random bytes in base64url, shown once. Only the SHA-256 hash, name, created, last-used and revoked time are stored (Identity database, table `PersonalAccessTokens`). At most 20 live tokens per user. | +| `TokenAuthenticationHandler` | The `QueueifyToken` scheme: `Authorization: Bearer`. A missing, bad or revoked token is 401 with an empty body; the cookie is not accepted on `/api/sync`. It also counts every attempt against a per-address limit (`Queueify:Sync:RequestsPerMinute`, 120), so guessing is throttled (429). | +| `SyncEngine` | `POST /api/sync`: one SQLite transaction per request, one request at a time per user. | +| `ConnectPc.razor` | `/connect`: create, list and revoke tokens; the connect text (`SyncConnect.Format`) is shown once. | + +How a sync works: rows changed through `BacklogStore` by the web pages are flagged `dirty`; the next sync stamps +them with a `server_time` (a column `BacklogStore` doesn't know, next to a `sync_meta` table; desktop databases +never get either) and clears the flag. Stamps are strictly increasing per user, so `since` pagination never skips +a row. Incoming rows win when their `updatedAt` is newer than the server's (a tie keeps the server's row); a row +the server refuses is stamped again, so it comes back to the sender in the same response and the PC converges. +Deletions stay as soft rows. Text is cut at 500 characters, ratings and years are made valid, and an `updatedAt` +more than ten minutes ahead of the server's clock is pulled back to that, so a wrong PC clock can't win forever. +A request holds at most 1,000 albums (400 otherwise) and `Queueify:Sync:MaxBodyBytes` (8 MB, 413); a response +holds at most 1,000 albums, and when it is full its `serverTime` is the stamp of its last album, so the client +repeats until the response is empty. Settings follow the same rule with their own stamp. + ## Startup `App.OnLaunched` reads `ui.json`, sets the language (`Loc.Use` and WinUI's diff --git a/docs/TESTING.md b/docs/TESTING.md index be0c89f..33444cd 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -7,6 +7,7 @@ | Unit (`Queueify.Tests`) | Core logic: matching, store, sync, catalogs (fake HTTP), OCR, texts, settings | `dotnet test --project Queueify.Tests`; CI | | Sync (inside the unit suite) | Two simulated PCs against the Firestore emulator, and the security rules | with `QUEUEIFY_FIRESTORE_EMULATOR`; CI | | UI (`tests\ui\Queueify.UiTests.ps1`) | The published app through UI Automation: tour, pages, panel, settings, language restart | locally, before merging UI changes | +| Web (`Queueify.Web.Tests`) | The sync server and tokens through `WebApplicationFactory`: auth, user isolation, conflicts, limits, secrets on disk, and a round trip with the real Core types | `dotnet test --project Queueify.Web.Tests`; CI | | Sync UI (`tests\ui\Queueify.SyncUiTests.ps1`) | Connecting Sync from the dialog, an album reaching Firestore | locally, with the emulator | | Update UI (`tests\ui\Queueify.UpdateUiTests.ps1`) | A copy of the download updating itself from a release served on this PC: offer, refusing a bad download, the setting, the swap and restart | locally | | Release tool (`tests\tools\Release.Tests.ps1`) | Version bump, changelog and notes | locally; CI | @@ -55,4 +56,6 @@ folder, keeps its data in local app data (default mode), and a taskbar pin would decisions that would start something (an install) are pure functions tested on their own. - Texts asserted in English run under `Loc.Override("en")` when they contain numbers or dates, so the machine's regional format can't change them. +- Web tests never touch real data: `SyncFactory` points `Queueify:DataDir` and the Identity database at a scratch + folder and gives every test its own user, so tests share one server without seeing each other's data. - Could the test pass with a wrong implementation? Flip a comparison mentally; a test should fail. From 6a6d91ea09a07fe069f819dfe1ff12e89148ca64 Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:05:14 -0300 Subject: [PATCH 07/66] feat(web): queue view, play links, user queue, search and prefs services Core gets QueueView and PlayLinks as tested pure functions; the web app gets per-user queue, album search, language/theme prefs, the UI registration extension, PWA icons, stylesheet and design plan. Co-Authored-By: Claude Sonnet 5.5 --- Queueify.Core/Services/ExternalLinks.cs | 12 +- Queueify.Core/Services/PlayLinks.cs | 34 ++ Queueify.Core/Services/QueueView.cs | 56 +++ Queueify.Tests/PlayLinksTests.cs | 47 ++ Queueify.Tests/QueueViewTests.cs | 106 +++++ Queueify.Web.Tests/AlbumSearchTests.cs | 129 ++++++ Queueify.Web.Tests/PrefsTests.cs | 48 ++ Queueify.Web.Tests/UserQueueTests.cs | 149 ++++++ Queueify.Web/Components/Shared/Cover.razor | 35 ++ Queueify.Web/Components/Shared/Ico.razor | 40 ++ Queueify.Web/Program.cs | 3 + Queueify.Web/Services/AlbumSearch.cs | 103 ++++ Queueify.Web/Services/Prefs.cs | 35 ++ Queueify.Web/Services/QueueifyUi.cs | 90 ++++ Queueify.Web/Services/Toasts.cs | 25 + Queueify.Web/Services/UserQueue.cs | 127 +++++ .../wwwroot/icons/apple-touch-icon.png | Bin 0 -> 14264 bytes Queueify.Web/wwwroot/icons/icon-192.png | Bin 0 -> 20109 bytes Queueify.Web/wwwroot/icons/icon-512.png | Bin 0 -> 79546 bytes .../wwwroot/icons/icon-maskable-512.png | Bin 0 -> 60194 bytes Queueify.Web/wwwroot/icons/icon.svg | 28 ++ Queueify.Web/wwwroot/queueify.css | 438 ++++++++++++++++++ docs/WEB_DESIGN.md | 104 +++++ 23 files changed, 1603 insertions(+), 6 deletions(-) create mode 100644 Queueify.Core/Services/PlayLinks.cs create mode 100644 Queueify.Core/Services/QueueView.cs create mode 100644 Queueify.Tests/PlayLinksTests.cs create mode 100644 Queueify.Tests/QueueViewTests.cs create mode 100644 Queueify.Web.Tests/AlbumSearchTests.cs create mode 100644 Queueify.Web.Tests/PrefsTests.cs create mode 100644 Queueify.Web.Tests/UserQueueTests.cs create mode 100644 Queueify.Web/Components/Shared/Cover.razor create mode 100644 Queueify.Web/Components/Shared/Ico.razor create mode 100644 Queueify.Web/Services/AlbumSearch.cs create mode 100644 Queueify.Web/Services/Prefs.cs create mode 100644 Queueify.Web/Services/QueueifyUi.cs create mode 100644 Queueify.Web/Services/Toasts.cs create mode 100644 Queueify.Web/Services/UserQueue.cs create mode 100644 Queueify.Web/wwwroot/icons/apple-touch-icon.png create mode 100644 Queueify.Web/wwwroot/icons/icon-192.png create mode 100644 Queueify.Web/wwwroot/icons/icon-512.png create mode 100644 Queueify.Web/wwwroot/icons/icon-maskable-512.png create mode 100644 Queueify.Web/wwwroot/icons/icon.svg create mode 100644 Queueify.Web/wwwroot/queueify.css create mode 100644 docs/WEB_DESIGN.md diff --git a/Queueify.Core/Services/ExternalLinks.cs b/Queueify.Core/Services/ExternalLinks.cs index 4e3510a..87c5fad 100644 --- a/Queueify.Core/Services/ExternalLinks.cs +++ b/Queueify.Core/Services/ExternalLinks.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using Queueify.Models; using Windows.System; namespace Queueify.Services; @@ -6,14 +7,13 @@ namespace Queueify.Services; /// Opens albums in the installed Spotify / Tidal app, falling back to the web player. public static class ExternalLinks { - public static Task OpenSpotifyAsync(string id) => - OpenAsync(new Uri($"spotify:album:{id}"), new Uri($"https://open.spotify.com/album/{id}")); + public static Task OpenSpotifyAsync(string id) => OpenAsync(PlayLinks.For(MusicService.Spotify, id)); - public static Task OpenTidalAsync(string id) => - OpenAsync(new Uri($"tidal://album/{id}"), new Uri($"https://tidal.com/album/{id}")); + public static Task OpenTidalAsync(string id) => OpenAsync(PlayLinks.For(MusicService.Tidal, id)); - private static async Task OpenAsync(Uri app, Uri web) + private static async Task OpenAsync(PlayLink link) { + var app = new Uri(link.App); try { var support = await Launcher.QueryUriSupportAsync(app, LaunchQuerySupportType.Uri); @@ -24,6 +24,6 @@ private static async Task OpenAsync(Uri app, Uri web) { // Launcher can be unavailable in some unpackaged contexts; the browser fallback still works. } - Process.Start(new ProcessStartInfo(web.AbsoluteUri) { UseShellExecute = true }); + Process.Start(new ProcessStartInfo(new Uri(link.Web).AbsoluteUri) { UseShellExecute = true }); } } diff --git a/Queueify.Core/Services/PlayLinks.cs b/Queueify.Core/Services/PlayLinks.cs new file mode 100644 index 0000000..fb24de3 --- /dev/null +++ b/Queueify.Core/Services/PlayLinks.cs @@ -0,0 +1,34 @@ +using Queueify.Models; + +namespace Queueify.Services; + +/// The two ways to open an album: the installed app's link, and the web player when no app answers. +public sealed record PlayLink(string App, string Web); + +public static class PlayLinks +{ + public static PlayLink For(MusicService service, string id) => service == MusicService.Spotify + ? new($"spotify:album:{id}", $"https://open.spotify.com/album/{id}") + : new($"tidal://album/{id}", $"https://tidal.com/album/{id}"); + + /// + /// The link for a saved album on , or on the other service when only that + /// one has it. Ids come from catalogs and from sync, so anything that isn't a plain token is refused + /// rather than put into a link. + /// + public static PlayLink? Of(BacklogItem item, MusicService preferred) + { + var order = preferred == MusicService.Spotify + ? new[] { MusicService.Spotify, MusicService.Tidal } + : new[] { MusicService.Tidal, MusicService.Spotify }; + foreach (var service in order) + { + var id = service == MusicService.Spotify ? item.SpotifyId : item.TidalId; + if (IsPlainId(id)) return For(service, id!); + } + return null; + } + + private static bool IsPlainId(string? id) => + !string.IsNullOrEmpty(id) && id.Length <= 64 && id.All(char.IsAsciiLetterOrDigit); +} diff --git a/Queueify.Core/Services/QueueView.cs b/Queueify.Core/Services/QueueView.cs new file mode 100644 index 0000000..9dac29f --- /dev/null +++ b/Queueify.Core/Services/QueueView.cs @@ -0,0 +1,56 @@ +using Queueify.Models; + +namespace Queueify.Services; + +/// An album typed by hand. +public sealed record TypedAlbum(string Artist, string Album, int? Year); + +/// What the queue pages list and how the add box reads what was typed: pure, so every front end agrees. +public static class QueueView +{ + /// The orders offered, in menu order; "oldest" is also the fallback for anything unknown. + public static readonly IReadOnlyList SortKeys = ["oldest", "newest", "artist", "year", "source"]; + + /// The pending (or listened) albums that match , in the chosen order. + public static List Apply(IEnumerable all, bool listened, string filter, string sort) + { + var words = Matcher.Normalize(filter); + var items = all + .Where(i => !i.Deleted && i.IsListened == listened) + .Where(i => words.Length == 0 || Matcher.Normalize($"{i.Artist} {i.Album} {i.Source} {i.Year}").Contains(words)); + + var text = StringComparer.Create(Loc.Culture, ignoreCase: true); + items = sort switch + { + "newest" => items.OrderByDescending(i => i.AddedAt), + "artist" => items.OrderBy(i => i.Artist, text).ThenBy(i => i.Year), + "year" => items.OrderBy(i => i.Year ?? int.MaxValue).ThenBy(i => i.Artist, text), + "source" => items.OrderBy(i => i.Source ?? "￿", text).ThenBy(i => i.AddedAt), + _ => listened ? items.OrderByDescending(i => i.ListenedAt) : items.OrderBy(i => i.AddedAt), + }; + return items.ToList(); + } + + /// + /// What "Add without a link" saves from the typed line: "Artist - Album 1999" is split, anything + /// else is kept whole as the album. Null when nothing was typed. + /// + public static TypedAlbum? ParseTyped(string typed) + { + var (text, year) = Matcher.ExtractYear(typed.Trim()); + if (text.Length == 0) return null; + var parts = text.Split([" - ", " – ", " — "], 2, StringSplitOptions.TrimEntries); + return parts.Length == 2 ? new(parts[0], parts[1], year) : new("", text, year); + } + + /// The saved album a search result is already, by service link or by name; null when it is new. + public static BacklogItem? FindSaved(AlbumResult result, IEnumerable saved) + { + var title = Matcher.Normalize(result.Title); + var artist = Matcher.Normalize(result.Artist); + return saved.FirstOrDefault(i => + (result.Spotify != null && i.SpotifyId == result.Spotify.Id) || + (result.Tidal != null && i.TidalId == result.Tidal.Id) || + (Matcher.Normalize(i.Album) == title && Matcher.Normalize(i.Artist) == artist)); + } +} diff --git a/Queueify.Tests/PlayLinksTests.cs b/Queueify.Tests/PlayLinksTests.cs new file mode 100644 index 0000000..38449d9 --- /dev/null +++ b/Queueify.Tests/PlayLinksTests.cs @@ -0,0 +1,47 @@ +using Queueify.Models; +using Queueify.Services; + +namespace Queueify.Tests; + +/// The links Play opens: the installed app first, the web player as the fallback. +public class PlayLinksTests +{ + [Fact] + public void Spotify_HasAnAppLinkAndAWebFallback() + { + var link = PlayLinks.For(MusicService.Spotify, "4aawyAB9vmqN3uQ7FjRGTy"); + Assert.Equal("spotify:album:4aawyAB9vmqN3uQ7FjRGTy", link.App); + Assert.Equal("https://open.spotify.com/album/4aawyAB9vmqN3uQ7FjRGTy", link.Web); + } + + [Fact] + public void Tidal_HasAnAppLinkAndAWebFallback() + { + var link = PlayLinks.For(MusicService.Tidal, "12345"); + Assert.Equal("tidal://album/12345", link.App); + Assert.Equal("https://tidal.com/album/12345", link.Web); + } + + [Theory] + [InlineData("a/b")] + [InlineData("x?y=1")] + [InlineData("a b")] + [InlineData("")] + public void AnIdThatIsNotAPlainToken_IsRefused(string id) => + Assert.Null(PlayLinks.Of(new BacklogItem { SpotifyId = id }, MusicService.Spotify)); + + [Fact] + public void Of_UsesThePreferredServiceWhenTheAlbumIsOnBoth() + { + var item = new BacklogItem { SpotifyId = "sp", TidalId = "td" }; + Assert.Equal("https://tidal.com/album/td", PlayLinks.Of(item, MusicService.Tidal)!.Web); + Assert.Equal("https://open.spotify.com/album/sp", PlayLinks.Of(item, MusicService.Spotify)!.Web); + } + + [Fact] + public void Of_FallsBackToTheOnlyServiceThereIs() + { + Assert.Equal("https://tidal.com/album/td", PlayLinks.Of(new BacklogItem { TidalId = "td" }, MusicService.Spotify)!.Web); + Assert.Null(PlayLinks.Of(new BacklogItem(), MusicService.Tidal)); + } +} diff --git a/Queueify.Tests/QueueViewTests.cs b/Queueify.Tests/QueueViewTests.cs new file mode 100644 index 0000000..74b913e --- /dev/null +++ b/Queueify.Tests/QueueViewTests.cs @@ -0,0 +1,106 @@ +using Queueify.Models; +using Queueify.Services; + +namespace Queueify.Tests; + +/// What the queue pages list: filtering, ordering, and the add box's text handling. +public class QueueViewTests +{ + private static readonly DateTime T0 = new(2026, 1, 1, 12, 0, 0, DateTimeKind.Local); + + private static BacklogItem Item(string artist, string album, int? year = null, string? source = null, int addedDays = 0, int? listenedDays = null) => new() + { + Artist = artist, + Album = album, + Year = year, + Source = source, + AddedAt = T0.AddDays(addedDays), + ListenedAt = listenedDays is int d ? T0.AddDays(d) : null, + }; + + private static readonly BacklogItem[] Sample = + [ + Item("Soda Stereo", "Signos", 1986, "Rolling Stone", addedDays: 1), + Item("Charly García", "Clics Modernos", 1983, "Pelo", addedDays: 3), + Item("Spinetta", "Artaud", 1973, null, addedDays: 2), + Item("Gustavo Cerati", "Bocanada", 1999, "Rolling Stone", addedDays: 0, listenedDays: 10), + Item("Fito Páez", "Giros", 1985, "Pelo", addedDays: 4, listenedDays: 20), + ]; + + private static string[] Albums(IEnumerable items) => items.Select(i => i.Album).ToArray(); + + [Fact] + public void Pending_AndListened_AreSeparatePages() + { + Assert.Equal(["Signos", "Artaud", "Clics Modernos"], Albums(QueueView.Apply(Sample, listened: false, "", "oldest"))); + Assert.Equal(["Giros", "Bocanada"], Albums(QueueView.Apply(Sample, listened: true, "", "oldest"))); + } + + [Fact] + public void Listened_DefaultsToMostRecentlyHeardFirst() => + Assert.Equal(["Giros", "Bocanada"], Albums(QueueView.Apply(Sample, true, "", "oldest"))); + + [Theory] + [InlineData("newest", new[] { "Clics Modernos", "Artaud", "Signos" })] + [InlineData("artist", new[] { "Clics Modernos", "Signos", "Artaud" })] + [InlineData("year", new[] { "Artaud", "Clics Modernos", "Signos" })] + [InlineData("source", new[] { "Clics Modernos", "Signos", "Artaud" })] // no magazine goes last + public void Sort_OrdersTheQueue(string sort, string[] expected) => + Assert.Equal(expected, Albums(QueueView.Apply(Sample, false, "", sort))); + + [Fact] + public void UnknownSort_FallsBackToOldest() => + Assert.Equal(["Signos", "Artaud", "Clics Modernos"], Albums(QueueView.Apply(Sample, false, "", "bogus"))); + + [Theory] + [InlineData("clics", new[] { "Clics Modernos" })] + [InlineData("GARCIA", new[] { "Clics Modernos" })] // accents and case don't matter + [InlineData("rolling", new[] { "Signos" })] // the magazine counts + [InlineData("1973", new[] { "Artaud" })] // so does the year + [InlineData("zzz", new string[0])] + public void Filter_MatchesArtistAlbumMagazineAndYear(string filter, string[] expected) => + Assert.Equal(expected, Albums(QueueView.Apply(Sample, false, filter, "oldest"))); + + [Fact] + public void Apply_DoesNotShowDeletedAlbums() + { + var gone = Item("A", "Gone", addedDays: 1); + gone.Deleted = true; + Assert.Empty(QueueView.Apply([gone], false, "", "oldest")); + } + + [Theory] + [InlineData("Soda Stereo - Signos 1986", "Soda Stereo", "Signos", 1986)] + [InlineData("Soda Stereo – Signos", "Soda Stereo", "Signos", null)] + [InlineData("Signos", "", "Signos", null)] + [InlineData("Charly García - Clics Modernos (1983)", "Charly García", "Clics Modernos", 1983)] + public void ParseTyped_SplitsArtistAndAlbum(string typed, string artist, string album, int? year) + { + var parsed = QueueView.ParseTyped(typed)!; + Assert.Equal((artist, album, year), (parsed.Artist, parsed.Album, parsed.Year)); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + public void ParseTyped_NothingTyped_IsNull(string typed) => Assert.Null(QueueView.ParseTyped(typed)); + + [Fact] + public void FindSaved_RecognisesAnAlbumByLinkOrByName() + { + var saved = new BacklogItem { Artist = "Soda Stereo", Album = "Signos", SpotifyId = "sp1" }; + var byLink = Result(spotifyId: "sp1", title: "Other", artist: "Other"); + var byName = Result(title: "Signos (Remastered 2007)", artist: "soda stereo"); + var other = Result(title: "Dynamo", artist: "Soda Stereo"); + + Assert.Same(saved, QueueView.FindSaved(byLink, [saved])); + Assert.Same(saved, QueueView.FindSaved(byName, [saved])); + Assert.Null(QueueView.FindSaved(other, [saved])); + } + + private static AlbumResult Result(string title, string artist, string? spotifyId = null) + { + var m = new AlbumMatch { Service = MusicService.Spotify, Id = spotifyId ?? "zz", Title = title, Artists = [artist] }; + return new AlbumResult(m, Matcher.Normalize(title), Matcher.Normalize(artist)); + } +} diff --git a/Queueify.Web.Tests/AlbumSearchTests.cs b/Queueify.Web.Tests/AlbumSearchTests.cs new file mode 100644 index 0000000..a35c404 --- /dev/null +++ b/Queueify.Web.Tests/AlbumSearchTests.cs @@ -0,0 +1,129 @@ +using Queueify.Models; +using Queueify.Services; +using Queueify.Web.Services; + +namespace Queueify.Web.Tests; + +public class AlbumSearchTests +{ + private static AppSettings Keys(bool spotify = true, bool tidal = true) => new() + { + SpotifyClientId = spotify ? "id" : "", SpotifyClientSecret = spotify ? "secret" : "", + TidalClientId = tidal ? "id" : "", TidalClientSecret = tidal ? "secret" : "", + }; + + private static AlbumMatch Match(MusicService s, string id, string title, string artist, int year) => new() + { + Service = s, Id = id, Title = title, Artists = [artist], Year = year, + }; + + [Fact] + public async Task TheSameAlbumOnBothServices_IsOneRow_WithBothLinks() + { + var catalogs = new FakeCatalogs + { + Spotify = [Match(MusicService.Spotify, "sp1", "Clics Modernos", "Charly García", 1983)], + Tidal = [Match(MusicService.Tidal, "td1", "Clics Modernos", "Charly García", 1983)], + }; + + var outcome = await new AlbumSearch(catalogs).RunAsync("charly garcia clics modernos 1983", "u", Keys(), default); + + var row = Assert.Single(outcome.Results); + Assert.Equal("sp1", row.Spotify!.Id); + Assert.Equal("td1", row.Tidal!.Id); + Assert.True(outcome.Confident); + } + + [Fact] + public async Task OnlyTheConfiguredServicesAreAsked() + { + var catalogs = new FakeCatalogs { Spotify = [Match(MusicService.Spotify, "sp1", "Signos", "Soda Stereo", 1986)] }; + + var outcome = await new AlbumSearch(catalogs).RunAsync("soda stereo signos", "u", Keys(tidal: false), default); + + Assert.Equal([MusicService.Spotify], catalogs.Asked.Select(a => a.Service).Distinct()); + Assert.Single(outcome.Results); + } + + [Fact] + public async Task NoKeysAtAll_MeansNothingIsAsked_AndTheOutcomeSaysSo() + { + var catalogs = new FakeCatalogs(); + var outcome = await new AlbumSearch(catalogs).RunAsync("anything", "u", Keys(false, false), default); + + Assert.Empty(catalogs.Asked); + Assert.True(outcome.NeedsKeys); + } + + [Fact] + public async Task AServiceThatFails_IsReported_AndTheOtherStillAnswers() + { + var catalogs = new FakeCatalogs + { + Tidal = [Match(MusicService.Tidal, "td1", "Signos", "Soda Stereo", 1986)], + SpotifyFails = new CatalogException("Spotify said no"), + }; + + var outcome = await new AlbumSearch(catalogs).RunAsync("soda stereo signos", "u", Keys(), default); + + Assert.Single(outcome.Results); + Assert.Equal("Spotify: Spotify said no", Assert.Single(outcome.Errors)); + } + + [Fact] + public async Task ANetworkError_BecomesAReadableMessage_NotACrash() + { + var catalogs = new FakeCatalogs { SpotifyFails = new HttpRequestException("boom") }; + var outcome = await new AlbumSearch(catalogs).RunAsync("x y z", "u", Keys(tidal: false), default); + Assert.Contains("boom", Assert.Single(outcome.Errors)); + } + + [Fact] + public async Task ANumberThatIsTheTitle_IsSearchedAgainWithTheYear() + { + var catalogs = new FakeCatalogs(); + catalogs.OnSearch = q => q == "Prince 1999" + ? [Match(MusicService.Spotify, "sp9", "1999", "Prince", 1982)] + : []; + + var outcome = await new AlbumSearch(catalogs).RunAsync("Prince 1999", "u", Keys(tidal: false), default); + + Assert.Contains("Prince", catalogs.Asked.Select(a => a.Query)); + Assert.Contains("Prince 1999", catalogs.Asked.Select(a => a.Query)); + Assert.Equal("sp9", outcome.Results.Single().Spotify!.Id); + } + + [Fact] + public async Task ACancelledSearch_ReturnsNull_SoANewerOneCanTakeOver() + { + using var cts = new CancellationTokenSource(); + var catalogs = new FakeCatalogs { OnSearch = _ => { cts.Cancel(); throw new OperationCanceledException(cts.Token); } }; + var outcome = await new AlbumSearch(catalogs).RunAsync("x y z", "u", Keys(tidal: false), cts.Token); + Assert.Null(outcome); + } + + [Fact] + public async Task ATimeoutThatIsNotACancellation_IsReportedAsATimeout() + { + var catalogs = new FakeCatalogs { SpotifyFails = new TaskCanceledException() }; + var outcome = await new AlbumSearch(catalogs).RunAsync("x y z", "u", Keys(tidal: false), default); + Assert.Contains("Spotify", Assert.Single(outcome!.Errors)); + } + + private sealed class FakeCatalogs : ICatalogs + { + public List Spotify { get; init; } = []; + public List Tidal { get; init; } = []; + public Exception? SpotifyFails { get; init; } + public Func>? OnSearch { get; set; } + public List<(MusicService Service, string Query)> Asked { get; } = []; + + public Task> SearchAsync(MusicService service, string query, string userId, AppSettings settings, CancellationToken ct) + { + Asked.Add((service, query)); + if (service == MusicService.Spotify && SpotifyFails != null) throw SpotifyFails; + if (OnSearch != null) return Task.FromResult(OnSearch(query)); + return Task.FromResult(service == MusicService.Spotify ? Spotify : Tidal); + } + } +} diff --git a/Queueify.Web.Tests/PrefsTests.cs b/Queueify.Web.Tests/PrefsTests.cs new file mode 100644 index 0000000..9ab744e --- /dev/null +++ b/Queueify.Web.Tests/PrefsTests.cs @@ -0,0 +1,48 @@ +using Queueify.Web.Services; + +namespace Queueify.Web.Tests; + +/// Language and theme come from cookies, then from the browser's own language. +public class PrefsTests +{ + [Theory] + [InlineData("es", "en-US,en;q=0.9", "es")] // the cookie is the user's choice + [InlineData("en", "es-AR,es;q=0.9", "en")] + [InlineData(null, "es-AR,es;q=0.9,en;q=0.8", "es")] + [InlineData(null, "es", "es")] + [InlineData(null, "en-GB,en;q=0.9", "en")] + [InlineData(null, "fr-FR,fr;q=0.9", "en")] // not translated: English + [InlineData(null, null, "en")] + [InlineData("klingon", "es-AR", "es")] // a made-up cookie is ignored + [InlineData("", "", "en")] + public void Language_ComesFromTheCookieThenTheBrowser(string? cookie, string? accept, string expected) => + Assert.Equal(expected, Prefs.Language(cookie, accept)); + + [Theory] + [InlineData("dark", "dark")] + [InlineData("light", "light")] + [InlineData("system", "system")] + [InlineData(null, "system")] + [InlineData(" + + +@code { + [CascadingParameter] private HttpContext HttpContext { get; set; } = default!; + + private string Lang => HttpContext.Items[nameof(Prefs.Language)] as string ?? "en"; + private string Theme => Prefs.Theme(HttpContext.Request.Cookies[Prefs.ThemeCookie]); + + private IComponentRenderMode? PageRenderMode => + HttpContext.AcceptsInteractiveRouting() ? InteractiveServer : null; +} diff --git a/Queueify.Web/Components/Layout/MainLayout.razor b/Queueify.Web/Components/Layout/MainLayout.razor index 78624f3..84fb6af 100644 --- a/Queueify.Web/Components/Layout/MainLayout.razor +++ b/Queueify.Web/Components/Layout/MainLayout.razor @@ -1,23 +1,36 @@ -@inherits LayoutComponentBase +@inherits LayoutComponentBase -
+ + + +
+
+
+ +

Queueify

+
+ @Body +
+
+
+
- An unhandled error has occurred. - Reload - 🗙 + @Loc.T("web.error.unhandled") + @Loc.T("web.error.reload") + 🗙
+ +@code { + [Inject] private NavigationManager Nav { get; set; } = default!; +} diff --git a/Queueify.Web/Components/Layout/MainLayout.razor.css b/Queueify.Web/Components/Layout/MainLayout.razor.css deleted file mode 100644 index 38d1f25..0000000 --- a/Queueify.Web/Components/Layout/MainLayout.razor.css +++ /dev/null @@ -1,98 +0,0 @@ -.page { - position: relative; - display: flex; - flex-direction: column; -} - -main { - flex: 1; -} - -.sidebar { - background-image: linear-gradient(180deg, rgb(5, 39, 103) 0%, #3a0647 70%); -} - -.top-row { - background-color: #f7f7f7; - border-bottom: 1px solid #d6d5d5; - justify-content: flex-end; - height: 3.5rem; - display: flex; - align-items: center; -} - - .top-row ::deep a, .top-row ::deep .btn-link { - white-space: nowrap; - margin-left: 1.5rem; - text-decoration: none; - } - - .top-row ::deep a:hover, .top-row ::deep .btn-link:hover { - text-decoration: underline; - } - - .top-row ::deep a:first-child { - overflow: hidden; - text-overflow: ellipsis; - } - -@media (max-width: 640.98px) { - .top-row { - justify-content: space-between; - } - - .top-row ::deep a, .top-row ::deep .btn-link { - margin-left: 0; - } -} - -@media (min-width: 641px) { - .page { - flex-direction: row; - } - - .sidebar { - width: 250px; - height: 100vh; - position: sticky; - top: 0; - } - - .top-row { - position: sticky; - top: 0; - z-index: 1; - } - - .top-row.auth ::deep a:first-child { - flex: 1; - text-align: right; - width: 0; - } - - .top-row, article { - padding-left: 2rem !important; - padding-right: 1.5rem !important; - } -} - -#blazor-error-ui { - color-scheme: light only; - background: lightyellow; - bottom: 0; - box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2); - box-sizing: border-box; - display: none; - left: 0; - padding: 0.6rem 1.25rem 0.7rem 1.25rem; - position: fixed; - width: 100%; - z-index: 1000; -} - - #blazor-error-ui .dismiss { - cursor: pointer; - position: absolute; - right: 0.75rem; - top: 0.5rem; - } diff --git a/Queueify.Web/Components/Layout/NavMenu.razor b/Queueify.Web/Components/Layout/NavMenu.razor index 6ddc241..7a204ca 100644 --- a/Queueify.Web/Components/Layout/NavMenu.razor +++ b/Queueify.Web/Components/Layout/NavMenu.razor @@ -1,92 +1,89 @@ -@implements IDisposable +@implements IDisposable +@inject UserQueue Queue +@inject NavigationManager Nav -@inject NavigationManager NavigationManager +@* One list of every page, drawn twice: the left rail on desktops, the bottom bar (with a More sheet) on phones. *@ + - - - - - + private Page Connect => new("connect", "connect", Loc.T("web.nav.connect"), Loc.T("web.nav.connect.tip")); -@code { - private string? currentUrl; + private string ReturnUrl => Nav.ToBaseRelativePath(Nav.Uri); - protected override void OnInitialized() + protected override async Task OnInitializedAsync() { - currentUrl = NavigationManager.ToBaseRelativePath(NavigationManager.Uri); - NavigationManager.LocationChanged += OnLocationChanged; + await Queue.LoadAsync(); + Queue.Changed += OnChanged; + Nav.LocationChanged += OnLocation; } - private void OnLocationChanged(object? sender, LocationChangedEventArgs e) - { - currentUrl = NavigationManager.ToBaseRelativePath(e.Location); - StateHasChanged(); - } + private void OnChanged() => _ = InvokeAsync(StateHasChanged); + + private void OnLocation(object? sender, LocationChangedEventArgs e) => _ = InvokeAsync(StateHasChanged); public void Dispose() { - NavigationManager.LocationChanged -= OnLocationChanged; + Queue.Changed -= OnChanged; + Nav.LocationChanged -= OnLocation; } -} + private RenderFragment Link(Page p, string? extra = null) => @ + @if (p.Count > 0){}@p.Label + ; + + private RenderFragment Tab(Page p, string? extra = null) => Link(p, extra); + + // The badge is read out too: "To listen, 12 waiting". + private static string Name(Page p) => + p.Count > 0 && p.CountKey != null ? Loc.F(p.Count == 1 ? p.CountKey + ".one" : p.CountKey, p.Label, p.Count) : p.Label; +} diff --git a/Queueify.Web/Components/Layout/NavMenu.razor.css b/Queueify.Web/Components/Layout/NavMenu.razor.css deleted file mode 100644 index 0145d9d..0000000 --- a/Queueify.Web/Components/Layout/NavMenu.razor.css +++ /dev/null @@ -1,125 +0,0 @@ -.navbar-toggler { - appearance: none; - cursor: pointer; - width: 3.5rem; - height: 2.5rem; - color: white; - position: absolute; - top: 0.5rem; - right: 1rem; - border: 1px solid rgba(255, 255, 255, 0.1); - background: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba%28255, 255, 255, 0.55%29' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e") no-repeat center/1.75rem rgba(255, 255, 255, 0.1); -} - -.navbar-toggler:checked { - background-color: rgba(255, 255, 255, 0.5); -} - -.top-row { - min-height: 3.5rem; - background-color: rgba(0,0,0,0.4); -} - -.navbar-brand { - font-size: 1.1rem; -} - -.bi { - display: inline-block; - position: relative; - width: 1.25rem; - height: 1.25rem; - margin-right: 0.75rem; - top: -1px; - background-size: cover; -} - -.bi-house-door-fill-nav-menu { - background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-house-door-fill' viewBox='0 0 16 16'%3E%3Cpath d='M6.5 14.5v-3.505c0-.245.25-.495.5-.495h2c.25 0 .5.25.5.5v3.5a.5.5 0 0 0 .5.5h4a.5.5 0 0 0 .5-.5v-7a.5.5 0 0 0-.146-.354L13 5.793V2.5a.5.5 0 0 0-.5-.5h-1a.5.5 0 0 0-.5.5v1.293L8.354 1.146a.5.5 0 0 0-.708 0l-6 6A.5.5 0 0 0 1.5 7.5v7a.5.5 0 0 0 .5.5h4a.5.5 0 0 0 .5-.5Z'/%3E%3C/svg%3E"); -} - -.bi-plus-square-fill-nav-menu { - background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-plus-square-fill' viewBox='0 0 16 16'%3E%3Cpath d='M2 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2zm6.5 4.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3a.5.5 0 0 1 1 0z'/%3E%3C/svg%3E"); -} - -.bi-list-nested-nav-menu { - background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-list-nested' viewBox='0 0 16 16'%3E%3Cpath fill-rule='evenodd' d='M4.5 11.5A.5.5 0 0 1 5 11h10a.5.5 0 0 1 0 1H5a.5.5 0 0 1-.5-.5zm-2-4A.5.5 0 0 1 3 7h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5zm-2-4A.5.5 0 0 1 1 3h10a.5.5 0 0 1 0 1H1a.5.5 0 0 1-.5-.5z'/%3E%3C/svg%3E"); -} - -.bi-lock-nav-menu { - background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-list-nested' viewBox='0 0 16 16'%3E%3Cpath d='M8 1a2 2 0 0 1 2 2v4H6V3a2 2 0 0 1 2-2zm3 6V3a3 3 0 0 0-6 0v4a2 2 0 0 0-2 2v5a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2zM5 8h6a1 1 0 0 1 1 1v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V9a1 1 0 0 1 1-1z'/%3E%3C/svg%3E"); -} - -.bi-person-nav-menu { - background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-person' viewBox='0 0 16 16'%3E%3Cpath d='M8 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6Zm2-3a2 2 0 1 1-4 0 2 2 0 0 1 4 0Zm4 8c0 1-1 1-1 1H3s-1 0-1-1 1-4 6-4 6 3 6 4Zm-1-.004c-.001-.246-.154-.986-.832-1.664C11.516 10.68 10.289 10 8 10c-2.29 0-3.516.68-4.168 1.332-.678.678-.83 1.418-.832 1.664h10Z'/%3E%3C/svg%3E"); -} - -.bi-person-badge-nav-menu { - background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-person-badge' viewBox='0 0 16 16'%3E%3Cpath d='M6.5 2a.5.5 0 0 0 0 1h3a.5.5 0 0 0 0-1h-3zM11 8a3 3 0 1 1-6 0 3 3 0 0 1 6 0z'/%3E%3Cpath d='M4.5 0A2.5 2.5 0 0 0 2 2.5V14a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V2.5A2.5 2.5 0 0 0 11.5 0h-7zM3 2.5A1.5 1.5 0 0 1 4.5 1h7A1.5 1.5 0 0 1 13 2.5v10.795a4.2 4.2 0 0 0-.776-.492C11.392 12.387 10.063 12 8 12s-3.392.387-4.224.803a4.2 4.2 0 0 0-.776.492V2.5z'/%3E%3C/svg%3E"); -} - -.bi-person-fill-nav-menu { - background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-person-fill' viewBox='0 0 16 16'%3E%3Cpath d='M3 14s-1 0-1-1 1-4 6-4 6 3 6 4-1 1-1 1H3Zm5-6a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z'/%3E%3C/svg%3E"); -} - -.bi-arrow-bar-left-nav-menu { - background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-arrow-bar-left' viewBox='0 0 16 16'%3E%3Cpath d='M12.5 15a.5.5 0 0 1-.5-.5v-13a.5.5 0 0 1 1 0v13a.5.5 0 0 1-.5.5ZM10 8a.5.5 0 0 1-.5.5H3.707l2.147 2.146a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 1 1 .708.708L3.707 7.5H9.5a.5.5 0 0 1 .5.5Z'/%3E%3C/svg%3E"); -} - -.nav-item { - font-size: 0.9rem; - padding-bottom: 0.5rem; -} - - .nav-item:first-of-type { - padding-top: 1rem; - } - - .nav-item:last-of-type { - padding-bottom: 1rem; - } - - .nav-item ::deep .nav-link { - color: #d7d7d7; - background: none; - border: none; - border-radius: 4px; - height: 3rem; - display: flex; - align-items: center; - line-height: 3rem; - width: 100%; - } - -.nav-item ::deep a.active { - background-color: rgba(255,255,255,0.37); - color: white; -} - -.nav-item ::deep .nav-link:hover { - background-color: rgba(255,255,255,0.1); - color: white; -} - -.nav-scrollable { - display: none; -} - -.navbar-toggler:checked ~ .nav-scrollable { - display: block; -} - -@media (min-width: 641px) { - .navbar-toggler { - display: none; - } - - .nav-scrollable { - /* Never collapse the sidebar for wide screens */ - display: block; - - /* Allow sidebar to scroll for tall menus */ - height: calc(100vh - 3.5rem); - overflow-y: auto; - } -} diff --git a/Queueify.Web/Components/Layout/PrefsMenu.razor b/Queueify.Web/Components/Layout/PrefsMenu.razor new file mode 100644 index 0000000..6f1bd9f --- /dev/null +++ b/Queueify.Web/Components/Layout/PrefsMenu.razor @@ -0,0 +1,22 @@ +@* Language and theme are cookies set by a plain form POST (see QueueifyUi.MapQueueifyUi), so they work before any script runs. *@ +
+ @Loc.T("web.pref.language") +
+ + + + + + @Loc.T("web.pref.theme") +
+ + + + + + +
+ +@code { + [Parameter] public string ReturnUrl { get; set; } = ""; +} diff --git a/Queueify.Web/Components/Layout/ReconnectModal.razor b/Queueify.Web/Components/Layout/ReconnectModal.razor index e740b0c..e118b6f 100644 --- a/Queueify.Web/Components/Layout/ReconnectModal.razor +++ b/Queueify.Web/Components/Layout/ReconnectModal.razor @@ -1,31 +1,15 @@ - +
- -

- Rejoining the server... -

+

@Loc.T("web.reconnect.first")

- Rejoin failed... trying again in seconds. -

-

- Failed to rejoin.
Please retry or reload the page. -

- -

- The session has been paused by the server. -

-

- Failed to resume the session.
Please retry or reload the page. + @Loc.T("web.reconnect.repeat")

- +

@Loc.T("web.reconnect.failed")

+ +

@Loc.T("web.reconnect.paused")

+

@Loc.T("web.reconnect.failed")

+
diff --git a/Queueify.Web/Components/Layout/ReconnectModal.razor.css b/Queueify.Web/Components/Layout/ReconnectModal.razor.css deleted file mode 100644 index 3ad3773..0000000 --- a/Queueify.Web/Components/Layout/ReconnectModal.razor.css +++ /dev/null @@ -1,157 +0,0 @@ -.components-reconnect-first-attempt-visible, -.components-reconnect-repeated-attempt-visible, -.components-reconnect-failed-visible, -.components-pause-visible, -.components-resume-failed-visible, -.components-rejoining-animation { - display: none; -} - -#components-reconnect-modal.components-reconnect-show .components-reconnect-first-attempt-visible, -#components-reconnect-modal.components-reconnect-show .components-rejoining-animation, -#components-reconnect-modal.components-reconnect-paused .components-pause-visible, -#components-reconnect-modal.components-reconnect-resume-failed .components-resume-failed-visible, -#components-reconnect-modal.components-reconnect-retrying, -#components-reconnect-modal.components-reconnect-retrying .components-reconnect-repeated-attempt-visible, -#components-reconnect-modal.components-reconnect-retrying .components-rejoining-animation, -#components-reconnect-modal.components-reconnect-failed, -#components-reconnect-modal.components-reconnect-failed .components-reconnect-failed-visible { - display: block; -} - - -#components-reconnect-modal { - background-color: white; - width: 20rem; - margin: 20vh auto; - padding: 2rem; - border: 0; - border-radius: 0.5rem; - box-shadow: 0 3px 6px 2px rgba(0, 0, 0, 0.3); - opacity: 0; - transition: display 0.5s allow-discrete, overlay 0.5s allow-discrete; - animation: components-reconnect-modal-fadeOutOpacity 0.5s both; - &[open] - -{ - animation: components-reconnect-modal-slideUp 1.5s cubic-bezier(.05, .89, .25, 1.02) 0.3s, components-reconnect-modal-fadeInOpacity 0.5s ease-in-out 0.3s; - animation-fill-mode: both; -} - -} - -#components-reconnect-modal::backdrop { - background-color: rgba(0, 0, 0, 0.4); - animation: components-reconnect-modal-fadeInOpacity 0.5s ease-in-out; - opacity: 1; -} - -@keyframes components-reconnect-modal-slideUp { - 0% { - transform: translateY(30px) scale(0.95); - } - - 100% { - transform: translateY(0); - } -} - -@keyframes components-reconnect-modal-fadeInOpacity { - 0% { - opacity: 0; - } - - 100% { - opacity: 1; - } -} - -@keyframes components-reconnect-modal-fadeOutOpacity { - 0% { - opacity: 1; - } - - 100% { - opacity: 0; - } -} - -.components-reconnect-container { - display: flex; - flex-direction: column; - align-items: center; - gap: 1rem; -} - -#components-reconnect-modal p { - margin: 0; - text-align: center; -} - -#components-reconnect-modal button { - border: 0; - background-color: #6b9ed2; - color: white; - padding: 4px 24px; - border-radius: 4px; -} - - #components-reconnect-modal button:hover { - background-color: #3b6ea2; - } - - #components-reconnect-modal button:active { - background-color: #6b9ed2; - } - -.components-rejoining-animation { - position: relative; - width: 80px; - height: 80px; -} - - .components-rejoining-animation div { - position: absolute; - border: 3px solid #0087ff; - opacity: 1; - border-radius: 50%; - animation: components-rejoining-animation 1.5s cubic-bezier(0, 0.2, 0.8, 1) infinite; - } - - .components-rejoining-animation div:nth-child(2) { - animation-delay: -0.5s; - } - -@keyframes components-rejoining-animation { - 0% { - top: 40px; - left: 40px; - width: 0; - height: 0; - opacity: 0; - } - - 4.9% { - top: 40px; - left: 40px; - width: 0; - height: 0; - opacity: 0; - } - - 5% { - top: 40px; - left: 40px; - width: 0; - height: 0; - opacity: 1; - } - - 100% { - top: 0px; - left: 0px; - width: 80px; - height: 80px; - opacity: 0; - } -} diff --git a/Queueify.Web/Components/Layout/SignOut.razor b/Queueify.Web/Components/Layout/SignOut.razor new file mode 100644 index 0000000..3eedc40 --- /dev/null +++ b/Queueify.Web/Components/Layout/SignOut.razor @@ -0,0 +1,12 @@ +@* Signing out changes state, so it is a POST with the antiforgery token, never a link. *@ +
+ + + + + +@code { + [Parameter] public string ReturnUrl { get; set; } = ""; +} diff --git a/Queueify.Web/Components/Pages/Add.razor b/Queueify.Web/Components/Pages/Add.razor new file mode 100644 index 0000000..5035b69 --- /dev/null +++ b/Queueify.Web/Components/Pages/Add.razor @@ -0,0 +1,226 @@ +@page "/add" +@attribute [Microsoft.AspNetCore.Authorization.Authorize] +@implements IDisposable +@inject UserQueue Queue +@inject AlbumSearch Search +@inject Toasts Toasts +@inject IJSRuntime JS + +@Loc.T("pane.title") - Queueify + +
+ +
+

@Loc.T("pane.title")

+

@Loc.T("web.add.summary")

+
+
+ +
+ @if (_needsKeys) + { +
+ +
+

@Loc.T("search.no_service")

+

@Loc.T("web.add.keys_link")

+
+
+ } + +
+ + + @Loc.T("pane.magazine.help") +
+ +
+ + +
+ +

+ @if (_searching) { @Loc.T("search.searching") } + else { @_status } + @foreach (var e in _errors) { +@e } +

+ + @if (_results.Count > 0) + { +
    + @for (int i = 0; i < _results.Count; i++) + { + var r = _results[i]; + var index = i; +
  • + +
    +
    @r.Title
    +
    @r.Details
    +
    +
    +
    + Spotify + Tidal + @if (r.ScoreText.Length > 0) { @r.ScoreText (@((int)Math.Round(r.Score * 100))%) } + @if (r.QueueState != null) { @r.QueueState } +
    + @if (r.CanAdd) + { + + } +
    +
  • + } +
+ } + + @if (_offerNoLink && _query.Trim().Length > 0) + { + + } + +
+ @Loc.T("web.add.quick") +
+
+
+
+ +
+
+
+ +@code { + private string _magazine = ""; + private string _query = ""; + private string _status = ""; + private string? _resultsFor; + private bool _searching, _needsKeys, _offerNoLink; + private int _selected = -1; + private List _results = []; + private List _errors = []; + private CancellationTokenSource? _cts; + private string _qArtist = "", _qAlbum = "", _qYear = ""; + + protected override async Task OnInitializedAsync() + { + await Queue.LoadAsync(); + _magazine = Queue.Settings.LastSource; + _needsKeys = !Queue.Settings.SpotifyConfigured && !Queue.Settings.TidalConfigured; + } + + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (!firstRender) return; + try { await JS.InvokeAsync("queueify.focus", "[data-q-search]"); } + catch (JSException) { } + catch (InvalidOperationException) { } + } + + private async Task OnInput(ChangeEventArgs e) + { + _query = e.Value?.ToString() ?? ""; + _cts?.Cancel(); + if (_query.Trim().Length == 0) + { + _results = []; _errors = []; _status = ""; _resultsFor = null; _searching = false; _offerNoLink = false; + return; + } + if (_query.Trim().Length < 3) return; + + // Wait for a pause in typing; a newer keystroke cancels this wait. + var cts = _cts = new CancellationTokenSource(); + try { await Task.Delay(550, cts.Token); } + catch (OperationCanceledException) { return; } + await RunSearch(cts); + } + + private async Task OnKey(KeyboardEventArgs e) + { + switch (e.Key) + { + case "ArrowDown": Move(+1); break; + case "ArrowUp": Move(-1); break; + case "Escape": _query = ""; _results = []; _errors = []; _status = ""; _resultsFor = null; _offerNoLink = false; _cts?.Cancel(); break; + case "Enter": + if (_resultsFor == _query.Trim() && _selected >= 0 && _selected < _results.Count) AddResult(_results[_selected]); + else { _cts?.Cancel(); await RunSearch(_cts = new CancellationTokenSource()); } + break; + } + } + + private void Move(int delta) + { + if (_results.Count > 0) _selected = Math.Clamp(_selected + delta, 0, _results.Count - 1); + } + + private async Task RunSearch(CancellationTokenSource cts) + { + var raw = _query.Trim(); + if (raw.Length == 0) return; + _searching = true; _offerNoLink = false; _errors = []; _resultsFor = null; + StateHasChanged(); + + SearchOutcome? outcome; + try { outcome = await Search.RunAsync(raw, Queue.UserId!, Queue.Settings, cts.Token); } + finally { if (!cts.IsCancellationRequested) _searching = false; } + if (outcome == null || cts.IsCancellationRequested) return; + + _needsKeys = outcome.NeedsKeys; + _results = outcome.Results.ToList(); + foreach (var r in _results) + r.QueueState = QueueView.FindSaved(r, Queue.All) is { } saved ? (saved.IsListened ? Loc.T("search.state.listened") : Loc.T("search.state.queued")) : null; + _errors = outcome.Errors.ToList(); + _resultsFor = raw; + _selected = outcome.Confident ? 0 : -1; + _status = outcome.NeedsKeys ? "" : _results.Count == 0 ? Loc.T("search.none") + : outcome.Confident ? (_results[0].CanAdd ? Loc.T("search.press_enter") : Loc.T("search.already")) : Loc.T("search.no_close"); + _offerNoLink = outcome.NeedsKeys || !outcome.Confident; + } + + private void AddResult(AlbumResult r) + { + if (!r.CanAdd) + { + _status = Loc.F("search.already_saved", r.Title, r.QueueState!); + return; + } + Added(new BacklogItem + { + Artist = r.Artist, Album = r.Title, Year = r.Year, CoverUrl = r.CoverUrl, + SpotifyId = r.Spotify?.Id, TidalId = r.Tidal?.Id, + }); + } + + private void AddWithoutLink() + { + if (QueueView.ParseTyped(_query) is not { } typed) return; + Added(new BacklogItem { Artist = typed.Artist, Album = typed.Album, Year = typed.Year }); + } + + private void QuickAdd() + { + var album = _qAlbum.Trim(); + if (album.Length == 0) return; + int? year = int.TryParse(_qYear.Trim(), out var y) && y is >= 1900 and <= 2100 ? y : null; + Added(new BacklogItem { Artist = _qArtist.Trim(), Album = album, Year = year }); + _qArtist = _qAlbum = _qYear = ""; + } + + private void Added(BacklogItem item) + { + item = Queue.Add(item, _magazine); + _query = ""; _results = []; _errors = []; _status = ""; _resultsFor = null; _offerNoLink = false; _selected = -1; + Toasts.Show(new Toast(Loc.F("toast.added", item.Album), Loc.T("toast.undo"), () => Queue.Remove(item))); + _ = JS.InvokeVoidAsync("queueify.focus", "[data-q-search]").AsTask().ContinueWith(_ => { }, TaskScheduler.Default); + } + + public void Dispose() => _cts?.Cancel(); +} diff --git a/Queueify.Web/Components/Pages/Auth.razor b/Queueify.Web/Components/Pages/Auth.razor deleted file mode 100644 index b7bbe6e..0000000 --- a/Queueify.Web/Components/Pages/Auth.razor +++ /dev/null @@ -1,13 +0,0 @@ -@page "/auth" - -@using Microsoft.AspNetCore.Authorization - -@attribute [Authorize] - -Auth - -

You are authenticated

- - - Hello @context.User.Identity?.Name! - diff --git a/Queueify.Web/Components/Pages/Home.razor b/Queueify.Web/Components/Pages/Home.razor index 9001e0b..bb89ad4 100644 --- a/Queueify.Web/Components/Pages/Home.razor +++ b/Queueify.Web/Components/Pages/Home.razor @@ -1,7 +1,6 @@ -@page "/" +@page "/" +@attribute [Microsoft.AspNetCore.Authorization.Authorize] -Home +@Loc.T("nav.queue") - Queueify -

Hello, world!

- -Welcome to your new app. + diff --git a/Queueify.Web/Components/Pages/Listened.razor b/Queueify.Web/Components/Pages/Listened.razor new file mode 100644 index 0000000..679c4cb --- /dev/null +++ b/Queueify.Web/Components/Pages/Listened.razor @@ -0,0 +1,6 @@ +@page "/listened" +@attribute [Microsoft.AspNetCore.Authorization.Authorize] + +@Loc.T("nav.listened") - Queueify + + diff --git a/Queueify.Web/Components/Routes.razor b/Queueify.Web/Components/Routes.razor index ae5f724..3fa5213 100644 --- a/Queueify.Web/Components/Routes.razor +++ b/Queueify.Web/Components/Routes.razor @@ -1,4 +1,6 @@ -@using Queueify.Web.Components.Account.Shared +@using Queueify.Web.Components.Account.Shared +@inject LanguageState State + @@ -9,3 +11,18 @@ + +@code { + /// From the page's cookie; the circuit speaks it from here on (see LocCircuitHandler). + [Parameter] public string? Language { get; set; } + + protected override void OnParametersSet() + { + if (Language is "en" or "es") + { + State.Value = Language; + // Set for the render that follows this call as well; later calls are wrapped by the circuit handler. + Loc.Override(Language); + } + } +} diff --git a/Queueify.Web/Components/Shared/QueueBrowser.razor b/Queueify.Web/Components/Shared/QueueBrowser.razor new file mode 100644 index 0000000..2db1b43 --- /dev/null +++ b/Queueify.Web/Components/Shared/QueueBrowser.razor @@ -0,0 +1,220 @@ +@implements IDisposable +@inject UserQueue Queue +@inject Toasts Toasts +@inject IJSRuntime JS + +@{ + var pending = Queue.All.Where(i => i.IsPending).ToList(); + var heard = Queue.All.Where(i => i.IsListened).ToList(); + var items = QueueView.Apply(Queue.All, Listened, _filter, _sort); +} + +
+ +
+

@(Listened ? Loc.T("nav.listened") : Loc.T("nav.queue"))

+

@(Listened ? QueueText.ListenedSummary(heard) : QueueText.PendingSummary(pending, DateTime.Now))

+
+
+ + + +@if (items.Count == 0) +{ +
+ +

@EmptyTitle

+

@EmptyText

+ @if (!Listened && _filter.Length == 0) + { + @Loc.T("web.nav.add") + } +
+} +else if (_covers) +{ +
    + @foreach (var item in items) + { +
  • + +
    +
    @item.Album
    +
    @item.ArtistLine
    +
    @Subtitle(item)
    +
    + @if (Listened) { } +
    @Actions(item)
    +
  • + } +
+} +else +{ +
    + @foreach (var item in items) + { +
  • + +
    +
    @item.Album
    +
    @item.ArtistLine
    +
    @Subtitle(item)
    + @if (Listened) { } +
    +
    @Actions(item)
    +
  • + } +
+} + +@code { + [Parameter] public bool Listened { get; set; } + + private string _filter = ""; + private string _sort = "oldest"; + private bool _covers; + private string? _picked; + + private RenderFragment Actions(BacklogItem item) => @ + @{ + var link = PlayLinks.Of(item, Queue.Preferred); + var service = item.HasTidal && (Queue.Preferred == MusicService.Tidal || !item.HasSpotify) ? "Tidal" : "Spotify"; + } + @if (link != null) + { + @service + } + else + { + @Loc.T("item.no_link") + } + +
+ +
+ @if (item.HasTidal) + { + @Loc.T("menu.open_tidal") + } + @if (item.HasSpotify) + { + @Loc.T("menu.open_spotify") + } + +
+
+
; + + protected override async Task OnInitializedAsync() + { + await Queue.LoadAsync(); + Queue.Changed += OnChanged; + } + + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (!firstRender) return; + try + { + var sort = await JS.InvokeAsync("queueify.get", "q-sort"); + var covers = await JS.InvokeAsync("queueify.get", "q-covers"); + if (sort != null && QueueView.SortKeys.Contains(sort)) _sort = sort; + _covers = covers == "1"; + StateHasChanged(); + } + catch (JSException) { } + catch (InvalidOperationException) { } // prerendering: no browser yet + } + + private void OnChanged() => _ = InvokeAsync(StateHasChanged); + + private string SortLabel(string key) => Loc.T("sort." + (key == "source" ? "magazine" : key)); + + private string Subtitle(BacklogItem item) => item.Subtitle; + + private string EmptyTitle => _filter.Length > 0 ? Loc.T("empty.filter.title") : Listened ? Loc.T("empty.listened.title") : Loc.T("empty.queue.title"); + private string EmptyText => _filter.Length > 0 ? Loc.T("empty.filter.text") : Listened ? Loc.T("empty.listened.text") : Loc.T("empty.queue.text"); + + private async Task OnSort(ChangeEventArgs e) + { + _sort = e.Value?.ToString() ?? "oldest"; + await Persist("q-sort", _sort); + } + + private async Task SetCovers(bool on) + { + _covers = on; + await Persist("q-covers", on ? "1" : "0"); + } + + private async Task Persist(string key, string value) + { + try { await JS.InvokeVoidAsync("queueify.set", key, value); } + catch (JSException) { } + catch (InvalidOperationException) { } + } + + private void OnFilterKey(KeyboardEventArgs e) + { + if (e.Key == "Escape") _filter = ""; + } + + private void Toggle(BacklogItem item) + { + var listened = !item.IsListened; + var undo = Queue.SetListened(item, listened); + Toasts.Show(new Toast(Loc.F(listened ? "toast.listened" : "toast.moved_back", item.Album), Loc.T("toast.undo"), undo, + Rate: listened ? stars => Queue.Rate(item, stars) : null)); + } + + private void Delete(BacklogItem item) + { + var undo = Queue.Delete(item); + Toasts.Show(new Toast(Loc.F("toast.deleted", item.Album), Loc.T("toast.undo"), undo)); + } + + private async Task Surprise() + { + var pending = Queue.All.Where(i => i.IsPending).ToList(); + if (pending.Count == 0) + { + Toasts.Show(new Toast(Loc.T("toast.surprise_empty"))); + return; + } + var pick = pending[Random.Shared.Next(pending.Count)]; + _filter = ""; + _picked = pick.Uid; + var question = pick.Artist.Length > 0 ? Loc.F("toast.surprise_by", pick.Album, pick.Artist) : Loc.F("toast.surprise", pick.Album); + Toasts.Show(new Toast(question)); + StateHasChanged(); + try { await JS.InvokeVoidAsync("queueify.scrollTo", "a-" + pick.Uid); } + catch (JSException) { } + catch (InvalidOperationException) { } + } + + public void Dispose() => Queue.Changed -= OnChanged; +} diff --git a/Queueify.Web/Components/Shared/Snackbar.razor b/Queueify.Web/Components/Shared/Snackbar.razor new file mode 100644 index 0000000..4e7a58e --- /dev/null +++ b/Queueify.Web/Components/Shared/Snackbar.razor @@ -0,0 +1,63 @@ +@implements IDisposable +@inject Toasts Toasts + +
+ @if (Toasts.Current is { } t) + { +
+ @t.Message + @if (t.Rate is { } rate) + { + + @for (int i = 1; i <= 5; i++) + { + var stars = i; + + } + + } + @if (t.Action is { } action) + { + + } + +
+ } +
+ +@code { + private CancellationTokenSource? _timer; + + protected override void OnInitialized() => Toasts.Changed += OnChanged; + + private void OnChanged() + { + _timer?.Cancel(); + if (Toasts.Current != null) + { + var cts = _timer = new CancellationTokenSource(); + _ = Task.Delay(TimeSpan.FromSeconds(9), cts.Token).ContinueWith( + _ => InvokeAsync(Toasts.Dismiss), CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default); + } + _ = InvokeAsync(StateHasChanged); + } + + private void Act(Action action) + { + Toasts.Dismiss(); + action(); + } + + private void Rated(Action rate, int stars) + { + Toasts.Dismiss(); + rate(stars); + } + + public void Dispose() + { + Toasts.Changed -= OnChanged; + _timer?.Cancel(); + } +} diff --git a/Queueify.Web/Components/Shared/Stars.razor b/Queueify.Web/Components/Shared/Stars.razor new file mode 100644 index 0000000..57cf04b --- /dev/null +++ b/Queueify.Web/Components/Shared/Stars.razor @@ -0,0 +1,14 @@ +@* Five stars as a radio-like group of buttons: usable with the keyboard and read out as "3 stars, pressed". *@ + + @for (int i = 1; i <= 5; i++) + { + var stars = i; + + } + + +@code { + [Parameter, EditorRequired] public BacklogItem Item { get; set; } = default!; + [Parameter] public EventCallback OnRate { get; set; } +} diff --git a/Queueify.Web/Components/_Imports.razor b/Queueify.Web/Components/_Imports.razor index d9e4c71..fc14ea1 100644 --- a/Queueify.Web/Components/_Imports.razor +++ b/Queueify.Web/Components/_Imports.razor @@ -1,4 +1,4 @@ -@using System.Net.Http +@using System.Net.Http @using System.Net.Http.Json @using Microsoft.AspNetCore.Components.Authorization @using Microsoft.AspNetCore.Components.Forms @@ -7,6 +7,10 @@ @using static Microsoft.AspNetCore.Components.Web.RenderMode @using Microsoft.AspNetCore.Components.Web.Virtualization @using Microsoft.JSInterop +@using Queueify.Models +@using Queueify.Services @using Queueify.Web @using Queueify.Web.Components @using Queueify.Web.Components.Layout +@using Queueify.Web.Components.Shared +@using Queueify.Web.Services diff --git a/Queueify.Web/wwwroot/app.css b/Queueify.Web/wwwroot/app.css deleted file mode 100644 index 73a69d6..0000000 --- a/Queueify.Web/wwwroot/app.css +++ /dev/null @@ -1,60 +0,0 @@ -html, body { - font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; -} - -a, .btn-link { - color: #006bb7; -} - -.btn-primary { - color: #fff; - background-color: #1b6ec2; - border-color: #1861ac; -} - -.btn:focus, .btn:active:focus, .btn-link.nav-link:focus, .form-control:focus, .form-check-input:focus { - box-shadow: 0 0 0 0.1rem white, 0 0 0 0.25rem #258cfb; -} - -.content { - padding-top: 1.1rem; -} - -h1:focus { - outline: none; -} - -.valid.modified:not([type=checkbox]) { - outline: 1px solid #26b050; -} - -.invalid { - outline: 1px solid #e50000; -} - -.validation-message { - color: #e50000; -} - -.blazor-error-boundary { - background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121; - padding: 1rem 1rem 1rem 3.7rem; - color: white; -} - - .blazor-error-boundary::after { - content: "An error has occurred." - } - -.darker-border-checkbox.form-check-input { - border-color: #929292; -} - -.form-floating > .form-control-plaintext::placeholder, .form-floating > .form-control::placeholder { - color: var(--bs-secondary-color); - text-align: end; -} - -.form-floating > .form-control-plaintext:focus::placeholder, .form-floating > .form-control:focus::placeholder { - text-align: start; -} \ No newline at end of file diff --git a/Queueify.Web/wwwroot/manifest.webmanifest b/Queueify.Web/wwwroot/manifest.webmanifest new file mode 100644 index 0000000..7d7a393 --- /dev/null +++ b/Queueify.Web/wwwroot/manifest.webmanifest @@ -0,0 +1,22 @@ +{ + "name": "Queueify", + "short_name": "Queueify", + "description": "Your listen-later queue of albums from magazines.", + "id": "/", + "start_url": "/add", + "scope": "/", + "display": "standalone", + "orientation": "portrait-primary", + "background_color": "#14111B", + "theme_color": "#6544E6", + "icons": [ + { "src": "icons/icon-192.png", "sizes": "192x192", "type": "image/png" }, + { "src": "icons/icon-512.png", "sizes": "512x512", "type": "image/png" }, + { "src": "icons/icon-maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }, + { "src": "icons/icon.svg", "sizes": "any", "type": "image/svg+xml" } + ], + "shortcuts": [ + { "name": "Add", "url": "/add", "icons": [{ "src": "icons/icon-192.png", "sizes": "192x192" }] }, + { "name": "To listen", "url": "/", "icons": [{ "src": "icons/icon-192.png", "sizes": "192x192" }] } + ] +} diff --git a/Queueify.Web/wwwroot/offline.html b/Queueify.Web/wwwroot/offline.html new file mode 100644 index 0000000..5e6ff75 --- /dev/null +++ b/Queueify.Web/wwwroot/offline.html @@ -0,0 +1,29 @@ + + + + + +Queueify + + + +
+
+

Queueify

+
+

You're offline

+

Queueify needs a connection to reach your queue. Try again when you're back online.

+ +
+
+
+ + + diff --git a/Queueify.Web/wwwroot/queueify.css b/Queueify.Web/wwwroot/queueify.css index b0f7d98..9054b57 100644 --- a/Queueify.Web/wwwroot/queueify.css +++ b/Queueify.Web/wwwroot/queueify.css @@ -122,7 +122,7 @@ code, kbd { font-family: "Cascadia Mono", ui-monospace, Consolas, monospace; fon content: ""; position: absolute; inset-inline-start: -8px; top: 14px; bottom: 14px; width: 3px; border-radius: 3px; background: var(--q-violet); } .q-navitem .q-ico { position: relative; display: grid; place-items: center; width: 28px; height: 28px; } -.q-navitem svg { width: 22px; height: 22px; fill: currentColor; } +.q-navitem svg { width: 22px; height: 22px; } .q-badge { position: absolute; top: -5px; inset-inline-start: 14px; @@ -145,7 +145,7 @@ code, kbd { font-family: "Cascadia Mono", ui-monospace, Consolas, monospace; fon flex: none; display: grid; place-items: center; width: 44px; height: 44px; border-radius: 12px; background: var(--q-violet-wash); color: var(--q-violet-text); } -.q-head-ico svg { width: 24px; height: 24px; fill: currentColor; } +.q-head-ico svg { width: 24px; height: 24px; } .q-sub { color: var(--q-muted); margin-top: 2px; } .q-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin-bottom: 16px; } @@ -165,7 +165,7 @@ code, kbd { font-family: "Cascadia Mono", ui-monospace, Consolas, monospace; fon .q-input.big { height: 52px; font-size: 17px; padding-inline-start: 44px; } .q-searchbox { position: relative; } .q-searchbox > svg { - position: absolute; inset-inline-start: 14px; top: 50%; translate: 0 -50%; width: 20px; height: 20px; fill: var(--q-muted); pointer-events: none; + position: absolute; inset-inline-start: 14px; top: 50%; translate: 0 -50%; width: 20px; height: 20px; color: var(--q-muted); pointer-events: none; } /* Buttons: one shape, three weights. */ @@ -180,7 +180,7 @@ code, kbd { font-family: "Cascadia Mono", ui-monospace, Consolas, monospace; fon transition: background-color .12s ease, border-color .12s ease; } .q-btn:hover { background: var(--q-sleeve-2); color: var(--q-ink); } -.q-btn svg { width: 18px; height: 18px; fill: currentColor; flex: none; } +.q-btn svg { width: 18px; height: 18px; flex: none; } .q-btn.primary { background: var(--q-violet); border-color: var(--q-violet); color: #fff; } .q-btn.primary:hover { background: var(--q-violet-hover); border-color: var(--q-violet-hover); color: #fff; } .q-btn.danger { background: var(--q-danger); border-color: var(--q-danger); color: light-dark(#fff, #14111B); } @@ -225,7 +225,7 @@ code, kbd { font-family: "Cascadia Mono", ui-monospace, Consolas, monospace; fon border: 2px solid var(--q-muted); background: transparent; color: var(--q-muted); cursor: pointer; padding: 0; } .q-check:hover { border-color: var(--q-violet); color: var(--q-violet-text); background: var(--q-violet-wash); } -.q-check svg { width: 20px; height: 20px; fill: currentColor; } +.q-check svg { width: 20px; height: 20px; } .q-check.done { background: var(--q-violet); border-color: var(--q-violet); color: #fff; } .q-menu { position: relative; } @@ -242,7 +242,7 @@ code, kbd { font-family: "Cascadia Mono", ui-monospace, Consolas, monospace; fon .q-stars { display: inline-flex; gap: 2px; } .q-star { display: grid; place-items: center; width: 36px; height: 36px; border: 0; background: none; color: var(--q-muted); cursor: pointer; padding: 0; border-radius: 6px; } -.q-star svg { width: 22px; height: 22px; fill: currentColor; } +.q-star svg { width: 22px; height: 22px; } .q-star.on { color: var(--q-rose); } .q-star:hover { color: var(--q-rose); } @@ -255,7 +255,7 @@ code, kbd { font-family: "Cascadia Mono", ui-monospace, Consolas, monospace; fon .q-empty { display: grid; justify-items: center; gap: 6px; text-align: center; padding: 56px 16px; color: var(--q-muted); } .q-empty h2 { color: var(--q-ink); } -.q-empty svg { width: 40px; height: 40px; fill: var(--q-violet-text); margin-bottom: 8px; } +.q-empty svg { width: 40px; height: 40px; color: var(--q-violet-text); margin-bottom: 8px; } /* ───────── Add page ───────── */ @@ -298,13 +298,13 @@ code, kbd { font-family: "Cascadia Mono", ui-monospace, Consolas, monospace; fon padding: 12px 14px; border-radius: var(--q-radius); background: var(--q-sleeve); border: 1px solid var(--q-hair); border-inline-start: 4px solid var(--q-violet); } -.q-alert svg { flex: none; width: 20px; height: 20px; fill: var(--q-violet-text); margin-top: 1px; } +.q-alert svg { flex: none; width: 20px; height: 20px; color: var(--q-violet-text); margin-top: 1px; } .q-alert.warn { border-inline-start-color: var(--q-warn); } -.q-alert.warn svg { fill: var(--q-warn); } +.q-alert.warn svg { color: var(--q-warn); } .q-alert.bad { border-inline-start-color: var(--q-danger); } -.q-alert.bad svg { fill: var(--q-danger); } +.q-alert.bad svg { color: var(--q-danger); } .q-alert.ok { border-inline-start-color: var(--q-ok); } -.q-alert.ok svg { fill: var(--q-ok); } +.q-alert.ok svg { color: var(--q-ok); } .q-alert p + p { margin-top: 4px; } .q-snack { @@ -436,3 +436,5 @@ code, kbd { font-family: "Cascadia Mono", ui-monospace, Consolas, monospace; fon @media (min-width: 760px) { .q-more-sheet { display: none; } } + +.q-star.on svg { fill: currentColor; } diff --git a/Queueify.Web/wwwroot/queueify.js b/Queueify.Web/wwwroot/queueify.js new file mode 100644 index 0000000..e797fea --- /dev/null +++ b/Queueify.Web/wwwroot/queueify.js @@ -0,0 +1,62 @@ +// Small browser helpers: shortcuts, the Play fallback, scrolling to a pick, and the service worker. +(function () { + 'use strict'; + + function focusFirst(selector) { + const el = document.querySelector(selector); + if (!el) return false; + el.focus(); + if (el.select) el.select(); + return true; + } + + // Ctrl+F filters the queue (or searches on Add); Ctrl+K goes to Add; F1 opens Help. + document.addEventListener('keydown', function (e) { + if (e.key === 'F1') { + const help = document.querySelector('a[data-q-nav="help"]'); + if (help) { e.preventDefault(); help.click(); } + } else if ((e.ctrlKey || e.metaKey) && !e.shiftKey && !e.altKey && (e.key === 'f' || e.key === 'F')) { + if (focusFirst('[data-q-filter]')) e.preventDefault(); + } else if ((e.ctrlKey || e.metaKey) && !e.shiftKey && !e.altKey && (e.key === 'k' || e.key === 'K')) { + e.preventDefault(); + if (!focusFirst('[data-q-search]')) { + const add = document.querySelector('.q-rail a[href="add"], .q-rail a[href="/add"]'); + if (add) add.click(); + } + } + }); + + // Play: try the installed app's link, and open the web player if nothing took over within a second. + document.addEventListener('click', function (e) { + const a = e.target.closest && e.target.closest('a[data-app]'); + if (!a || e.defaultPrevented || e.button !== 0 || e.ctrlKey || e.metaKey || e.shiftKey) return; + e.preventDefault(); + const web = a.href; + let left = false; + const mark = function () { left = true; }; + window.addEventListener('blur', mark, { once: true }); + document.addEventListener('visibilitychange', mark, { once: true }); + window.location.href = a.getAttribute('data-app'); + setTimeout(function () { + window.removeEventListener('blur', mark); + document.removeEventListener('visibilitychange', mark); + if (!left) window.open(web, '_blank', 'noopener'); + }, 1100); + }); + + window.queueify = { + scrollTo: function (id) { + const el = document.getElementById(id); + if (el) el.scrollIntoView({ block: 'center', behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth' }); + }, + focus: function (selector) { return focusFirst(selector); }, + get: function (key) { try { return localStorage.getItem(key); } catch (_) { return null; } }, + set: function (key, value) { try { localStorage.setItem(key, value); } catch (_) { } }, + }; + + if ('serviceWorker' in navigator) { + window.addEventListener('load', function () { + navigator.serviceWorker.register('sw.js').catch(function () { }); + }); + } +})(); diff --git a/Queueify.Web/wwwroot/sw.js b/Queueify.Web/wwwroot/sw.js new file mode 100644 index 0000000..ede7385 --- /dev/null +++ b/Queueify.Web/wwwroot/sw.js @@ -0,0 +1,30 @@ +// Caches the shell (icons, stylesheet, offline page) so the app is installable and fails politely offline. +// Pages and data are never cached: they are per user and live on the server. +const CACHE = 'queueify-shell-v1'; +const SHELL = ['offline.html', 'queueify.css', 'icons/icon-192.png', 'icons/icon.svg']; + +self.addEventListener('install', function (event) { + event.waitUntil(caches.open(CACHE).then(function (c) { return c.addAll(SHELL); }).then(function () { return self.skipWaiting(); })); +}); + +self.addEventListener('activate', function (event) { + event.waitUntil( + caches.keys() + .then(function (keys) { return Promise.all(keys.filter(function (k) { return k !== CACHE; }).map(function (k) { return caches.delete(k); })); }) + .then(function () { return self.clients.claim(); })); +}); + +self.addEventListener('fetch', function (event) { + const req = event.request; + if (req.method !== 'GET') return; + const url = new URL(req.url); + if (url.origin !== location.origin) return; + + if (req.mode === 'navigate') { + event.respondWith(fetch(req).catch(function () { return caches.match('offline.html'); })); + return; + } + if (SHELL.some(function (p) { return url.pathname.endsWith('/' + p); })) { + event.respondWith(caches.match(req).then(function (hit) { return hit || fetch(req); })); + } +}); From 51fd278f757d18a0f0ba248c044468e31eff3cd9 Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:09:51 -0300 Subject: [PATCH 11/66] feat(web): settings and preferences services Co-Authored-By: Claude Sonnet 5.5 --- .../Settings/PreferencesStoreTests.cs | 47 +++++ .../Settings/SettingsServiceTests.cs | 191 ++++++++++++++++++ Queueify.Web/Services/PreferencesStore.cs | 53 +++++ Queueify.Web/Services/SettingsService.cs | 107 ++++++++++ 4 files changed, 398 insertions(+) create mode 100644 Queueify.Web.Tests/Settings/PreferencesStoreTests.cs create mode 100644 Queueify.Web.Tests/Settings/SettingsServiceTests.cs create mode 100644 Queueify.Web/Services/PreferencesStore.cs create mode 100644 Queueify.Web/Services/SettingsService.cs diff --git a/Queueify.Web.Tests/Settings/PreferencesStoreTests.cs b/Queueify.Web.Tests/Settings/PreferencesStoreTests.cs new file mode 100644 index 0000000..fdda5c9 --- /dev/null +++ b/Queueify.Web.Tests/Settings/PreferencesStoreTests.cs @@ -0,0 +1,47 @@ +using Queueify.Web.Services; +using Queueify.Web.Storage; + +namespace Queueify.Web.Tests.Settings; + +public sealed class PreferencesStoreTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "qp-" + Guid.NewGuid().ToString("N")); + public void Dispose() { try { Directory.Delete(_root, true); } catch (IOException) { } } + + [Fact] + public void Defaults_follow_the_device_and_read_spanish_and_english() + { + var p = new PreferencesStore(new UserStores(_root)).Load("alice"); + Assert.Equal(("system", "system", "auto", false), (p.Theme, p.Language, p.OcrLanguage, p.TourSeen)); + } + + [Fact] + public void Saved_preferences_come_back_and_belong_to_one_user() + { + var store = new PreferencesStore(new UserStores(_root)); + store.Save("alice", new Preferences("dark", "es", "en", true)); + + Assert.Equal(new Preferences("dark", "es", "en", true), store.Load("alice")); + Assert.Equal("system", store.Load("bob").Theme); + } + + [Fact] + public void Values_outside_the_choices_are_replaced_when_read_and_refused_when_saved() + { + var stores = new UserStores(_root); + Directory.CreateDirectory(Path.Combine(_root, "alice")); + File.WriteAllText(Path.Combine(_root, "alice", "prefs.json"), """{"Theme":" - + \ No newline at end of file diff --git a/Queueify.Web/wwwroot/queueify.css b/Queueify.Web/wwwroot/queueify.css index 8cb41e8..0bebf7d 100644 --- a/Queueify.Web/wwwroot/queueify.css +++ b/Queueify.Web/wwwroot/queueify.css @@ -457,3 +457,11 @@ h1[tabindex="-1"]:focus, h1[tabindex="-1"]:focus-visible { outline: none; } .q-pill.off { opacity: .7; } .q-switch, .q-switch span { color: var(--q-ink); } + +.q-scrim { display: none; } +@media (max-width: 759.98px) { + .q-scrim { display: block; position: fixed; inset: 0; z-index: 54; background: rgb(0 0 0 / .4); } + .q-more-sheet .q-navitem { color: var(--q-ink); } + .q-more-sheet .q-prefs { padding: 8px 12px 4px; border-top: 1px solid var(--q-hair); margin-top: 4px; } +} + diff --git a/Queueify.Web/wwwroot/queueify.js b/Queueify.Web/wwwroot/queueify.js index 9f53c66..f454657 100644 --- a/Queueify.Web/wwwroot/queueify.js +++ b/Queueify.Web/wwwroot/queueify.js @@ -48,7 +48,7 @@ document.addEventListener('click', function (e) { document.querySelectorAll('details.q-more[open], details.q-menu[open]').forEach(function (d) { const insideLink = e.target.closest && d.contains(e.target) && e.target.closest('a'); - if (!d.contains(e.target) || insideLink) d.removeAttribute('open'); + if (!d.contains(e.target) || insideLink || (e.target.classList && e.target.classList.contains('q-scrim'))) d.removeAttribute('open'); }); }); document.addEventListener('keydown', function (e) { diff --git a/Queueify.Web/wwwroot/sw.js b/Queueify.Web/wwwroot/sw.js index ede7385..20aa750 100644 --- a/Queueify.Web/wwwroot/sw.js +++ b/Queueify.Web/wwwroot/sw.js @@ -1,7 +1,8 @@ // Caches the shell (icons, stylesheet, offline page) so the app is installable and fails politely offline. // Pages and data are never cached: they are per user and live on the server. -const CACHE = 'queueify-shell-v1'; -const SHELL = ['offline.html', 'queueify.css', 'icons/icon-192.png', 'icons/icon.svg']; +const CACHE = 'queueify-shell-v2'; +// Only files whose names never change; the app's stylesheet is fingerprinted per release and always comes from the network. +const SHELL = ['offline.html', 'icons/icon-192.png', 'icons/icon.svg']; self.addEventListener('install', function (event) { event.waitUntil(caches.open(CACHE).then(function (c) { return c.addAll(SHELL); }).then(function () { return self.skipWaiting(); })); diff --git a/SECURITY.md b/SECURITY.md index f2ad104..91b4005 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -28,3 +28,16 @@ Queueify runs with the user's rights on their own PC. It has no servers of its o | Network | Exfiltration | Only Spotify, Tidal, the user's own Firebase project, Windows Update and GitHub (the update check at each start: GitHub sees the address and that Queueify is starting, nothing else; it can be turned off). No telemetry. | Out of scope: a compromised PC or user account, and the security of Spotify, Tidal and Google's services. + +## Threat model: the web app (`Queueify.Web`) + +| Asset / surface | Threat | Defence | +| --- | --- | --- | +| Sign-in | Guessing passwords | ASP.NET Core Identity with passkeys; failed passwords count towards lockout (5 tries, then locked for 5 minutes). Not covered: a global rate limit in front of the server, so put the site behind a reverse proxy that has one. | +| Registration | A stranger creating an account on a public server | The first account owns the server (checked and written under one lock, so two first sign-ups can't both win); after that registration is closed unless `Queueify:AllowRegistration` is `true`. A fresh public server belongs to whoever registers first: register before exposing it. | +| Cross-site requests | Forged form posts (sign out, language, delete) | Antiforgery tokens on every form post, including `/prefs` and sign out; cookies are `SameSite=Lax`, `HttpOnly`, and `Secure` over HTTPS. | +| Page content | Script injection, clickjacking, tracking pixels | Razor encodes everything; no raw HTML is rendered. Every response carries a Content-Security-Policy (own scripts only, `frame-ancestors 'none'`, `object-src 'none'`, forms only to the site; album covers may come from any HTTPS host and are fetched without a referrer), `X-Content-Type-Options: nosniff` and `Referrer-Policy: no-referrer`. | +| Other users' data | Seeing or changing another queue | Each user's queue and settings live in a folder named by their account id (never by anything the browser sends); ids are checked against path tricks. | +| Spotify/Tidal keys | Leaking to the browser, or abuse of the server's address | Keys are read only on the server and never rendered; each user gets 30 catalog searches a minute so one account can't get the server's address blocked. The keys sit unencrypted in the user's `settings.json` on the server's disk: protect the data folder. | +| Redirects | Open redirect after sign-in, sign-out or a language change | Return addresses are reduced to a plain path on this site, otherwise the home page. | +| Service worker | Stale or other users' pages served from cache | It caches only the icons and an offline page, never pages or data, and only for GET requests on this site. | \ No newline at end of file From 7cdf2ca12356e4e9090e93badb22b092c4c2de4a Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:48:00 -0300 Subject: [PATCH 31/66] fix(web): cover tiles on phones, account pages in the shell Co-Authored-By: Claude Sonnet 5.5 --- Queueify.Web/Components/Layout/MainLayout.razor | 14 +++++++++++++- Queueify.Web/wwwroot/queueify.css | 6 ++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/Queueify.Web/Components/Layout/MainLayout.razor b/Queueify.Web/Components/Layout/MainLayout.razor index 3cb3403..671e050 100644 --- a/Queueify.Web/Components/Layout/MainLayout.razor +++ b/Queueify.Web/Components/Layout/MainLayout.razor @@ -7,7 +7,10 @@
-
@Body
+ @* Account pages other than Manage (which has its own card) are narrow forms: give them a card too. *@ +
+ @if (PlainAccountPage) {
@Body
} else { @Body } +
@@ -33,6 +36,15 @@ @code { [Inject] private NavigationManager Nav { get; set; } = default!; + + private bool PlainAccountPage + { + get + { + var path = Nav.ToBaseRelativePath(Nav.Uri); + return path.StartsWith("Account", StringComparison.OrdinalIgnoreCase) && !path.StartsWith("Account/Manage", StringComparison.OrdinalIgnoreCase); + } + } [Inject] private IThemeService Themes { get; set; } = default!; [Inject] private IJSRuntime JS { get; set; } = default!; diff --git a/Queueify.Web/wwwroot/queueify.css b/Queueify.Web/wwwroot/queueify.css index 0bebf7d..1b9e502 100644 --- a/Queueify.Web/wwwroot/queueify.css +++ b/Queueify.Web/wwwroot/queueify.css @@ -465,3 +465,9 @@ h1[tabindex="-1"]:focus, h1[tabindex="-1"]:focus-visible { outline: none; } .q-more-sheet .q-prefs { padding: 8px 12px 4px; border-top: 1px solid var(--q-hair); margin-top: 4px; } } + +.q-tile .q-actions { flex-wrap: wrap; justify-content: space-between; } +.q-tile .q-actions .q-btn.primary { flex: 1 1 100%; min-width: 0; } + +.q-page.q-narrow { max-width: 520px; margin-inline: 0; } + From 15690b3be940ec4e5a6c4a63b8c57c561ae1144f Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 21:39:04 -0300 Subject: [PATCH 32/66] test(web): one test at a time and a private account db per host Co-Authored-By: Claude Sonnet 5.5 --- Queueify.Web.Tests/AssemblyInfo.cs | 4 ++++ Queueify.Web.Tests/Support/ScratchHost.cs | 3 +++ 2 files changed, 7 insertions(+) create mode 100644 Queueify.Web.Tests/AssemblyInfo.cs diff --git a/Queueify.Web.Tests/AssemblyInfo.cs b/Queueify.Web.Tests/AssemblyInfo.cs new file mode 100644 index 0000000..c586621 --- /dev/null +++ b/Queueify.Web.Tests/AssemblyInfo.cs @@ -0,0 +1,4 @@ +// Several tests start the whole web app, and apps that share one account database migrate it at the same +// time and trip over each other under load. One collection for the whole assembly runs them one at a time: +// slower but steady. +[assembly: Xunit.CollectionBehavior(Xunit.CollectionBehavior.CollectionPerAssembly)] diff --git a/Queueify.Web.Tests/Support/ScratchHost.cs b/Queueify.Web.Tests/Support/ScratchHost.cs index 3dcf9e0..6ff69d5 100644 --- a/Queueify.Web.Tests/Support/ScratchHost.cs +++ b/Queueify.Web.Tests/Support/ScratchHost.cs @@ -31,6 +31,9 @@ public static WebApplicationFactory On(WebApplicationFactory f factory.WithWebHostBuilder(builder => { builder.UseSetting("Queueify:DataDir", dataRoot); + // Each host gets its own account database: hosts sharing one file migrate it at the same time and fail. + Directory.CreateDirectory(dataRoot); + builder.UseSetting("ConnectionStrings:DefaultConnection", $"DataSource={Path.Combine(dataRoot, "app.db")}"); builder.ConfigureTestServices(services => { services.AddAuthentication(o => o.DefaultScheme = HeaderUserAuthHandler.Scheme) From 7ed3e5e3aa8f358985e468fd8b52451ccb8849bc Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 21:54:02 -0300 Subject: [PATCH 33/66] feat(web): account prefs in the shell, tour, /add?q, user data deleted Co-Authored-By: Claude Sonnet 5.5 --- Queueify.Core/Services/Shortcuts.cs | 16 ++- Queueify.Core/Services/Strings.En.cs | 2 + Queueify.Core/Services/Strings.Es.cs | 2 + Queueify.Tests/ShortcutsTests.cs | 23 ++++ Queueify.Web.Tests/AccountPrefsTests.cs | 128 ++++++++++++++++++ Queueify.Web.Tests/ComponentTests.cs | 14 ++ Queueify.Web.Tests/Pages/HelpTests.cs | 4 +- .../Pages/Manage/DeletePersonalData.razor | 3 + Queueify.Web/Components/App.razor | 2 +- .../Components/Layout/MainLayout.razor | 1 + Queueify.Web/Components/Pages/Add.razor | 10 +- Queueify.Web/Components/Pages/Help.razor | 2 +- Queueify.Web/Services/Prefs.cs | 6 + Queueify.Web/Services/QueueifyUi.cs | 13 +- 14 files changed, 218 insertions(+), 8 deletions(-) create mode 100644 Queueify.Tests/ShortcutsTests.cs create mode 100644 Queueify.Web.Tests/AccountPrefsTests.cs diff --git a/Queueify.Core/Services/Shortcuts.cs b/Queueify.Core/Services/Shortcuts.cs index 8d2d567..41d22e9 100644 --- a/Queueify.Core/Services/Shortcuts.cs +++ b/Queueify.Core/Services/Shortcuts.cs @@ -1,4 +1,4 @@ -namespace Queueify.Services; +namespace Queueify.Services; public sealed record Shortcut(string Keys, string Description); @@ -16,4 +16,16 @@ public static class Shortcuts new("Ctrl+V", Loc.T("keys.ctrl_v")), new("F1", Loc.T("keys.f1")), ]; -} + + /// The shortcuts the web app handles: no side panel to hide, and Ctrl+K opens the Add page. + public static IReadOnlyList Web => + [ + new("Enter", Loc.T("keys.enter")), + new("↑ ↓", Loc.T("keys.arrows")), + new("Esc", Loc.T("keys.esc")), + new("Ctrl+K", Loc.T("web.keys.ctrl_k")), + new("Ctrl+F", Loc.T("keys.ctrl_f")), + new("Ctrl+V", Loc.T("keys.ctrl_v")), + new("F1", Loc.T("keys.f1")), + ]; +} \ No newline at end of file diff --git a/Queueify.Core/Services/Strings.En.cs b/Queueify.Core/Services/Strings.En.cs index f78b9c4..88ef517 100644 --- a/Queueify.Core/Services/Strings.En.cs +++ b/Queueify.Core/Services/Strings.En.cs @@ -707,5 +707,7 @@ public static partial class Loc ["connect.revoked"] = "Revoked", ["connect.revoke"] = "Revoke", ["connect.limit"] = "You have reached the limit of tokens. Revoke one to create another.", + + ["web.keys.ctrl_k"] = "Go to Add and its search box", }; } diff --git a/Queueify.Core/Services/Strings.Es.cs b/Queueify.Core/Services/Strings.Es.cs index 4f41192..50663c5 100644 --- a/Queueify.Core/Services/Strings.Es.cs +++ b/Queueify.Core/Services/Strings.Es.cs @@ -708,5 +708,7 @@ public static partial class Loc ["connect.revoked"] = "Revocada", ["connect.revoke"] = "Revocar", ["connect.limit"] = "Llegaste al límite de fichas. Revocá una para crear otra.", + + ["web.keys.ctrl_k"] = "Ir a Agregar y a su cuadro de búsqueda", }; } diff --git a/Queueify.Tests/ShortcutsTests.cs b/Queueify.Tests/ShortcutsTests.cs new file mode 100644 index 0000000..ea870d1 --- /dev/null +++ b/Queueify.Tests/ShortcutsTests.cs @@ -0,0 +1,23 @@ +using Queueify.Services; + +namespace Queueify.Tests; + +public class ShortcutsTests +{ + [Fact] + public void The_web_list_has_only_keys_the_web_app_handles() + { + var keys = Shortcuts.Web.Select(s => s.Keys).ToList(); + Assert.DoesNotContain("Ctrl+B", keys); // the desktop's side panel + Assert.Contains("Ctrl+K", keys); + Assert.Contains("Ctrl+F", keys); + Assert.Contains("F1", keys); + } + + [Fact] + public void The_web_list_describes_Ctrl_K_for_the_web() + { + using (Loc.Override("en")) + Assert.DoesNotContain("Ctrl+N", Shortcuts.Web.Single(s => s.Keys == "Ctrl+K").Description); + } +} \ No newline at end of file diff --git a/Queueify.Web.Tests/AccountPrefsTests.cs b/Queueify.Web.Tests/AccountPrefsTests.cs new file mode 100644 index 0000000..e3b1ea3 --- /dev/null +++ b/Queueify.Web.Tests/AccountPrefsTests.cs @@ -0,0 +1,128 @@ +using System.Net; +using System.Text.RegularExpressions; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Queueify.Web.Data; +using Queueify.Web.Services; +using Queueify.Web.Storage; + +namespace Queueify.Web.Tests; + +public class AccountPrefsTests +{ + [Theory] + [InlineData("es", "en", "en-US", "es")] // the account's own choice beats the cookie and the browser + [InlineData("en", "es", "es-AR", "en")] + [InlineData("system", "es", "en-US", "es")] // "system" defers to the cookie, then the browser + [InlineData("system", null, "es-AR", "es")] + [InlineData(null, null, "fr", "en")] + public void The_accounts_language_comes_first(string? account, string? cookie, string? accept, string expected) => + Assert.Equal(expected, Prefs.Language(account, cookie, accept)); + + [Theory] + [InlineData("dark", "light", "dark")] + [InlineData("system", "light", "light")] + [InlineData(null, null, "system")] + public void The_accounts_theme_comes_first(string? account, string? cookie, string expected) => + Assert.Equal(expected, Prefs.Theme(account, cookie)); +} + +public sealed partial class AccountPrefsAppTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "qw-" + Guid.NewGuid().ToString("N")); + public void Dispose() { try { Directory.Delete(_root, true); } catch (IOException) { } } + + private WebApplicationFactory Factory() => new WebApplicationFactory().WithWebHostBuilder(b => + { + Directory.CreateDirectory(_root); + b.UseSetting("ConnectionStrings:DefaultConnection", $"DataSource={Path.Combine(_root, "app.db")}"); + b.UseSetting("Queueify:DataDir", Path.Combine(_root, "data")); + }); + + [GeneratedRegex("name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"")] + private static partial Regex Token(); + + private static async Task<(HttpClient Client, string Token)> SignedInAsync(WebApplicationFactory f) + { + var client = f.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false, BaseAddress = new Uri("https://localhost") }); + var page = await client.GetStringAsync("/Account/Register", TestContext.Current.CancellationToken); + await client.PostAsync("/Account/Register", new FormUrlEncodedContent(new Dictionary + { + ["__RequestVerificationToken"] = Token().Match(page).Groups[1].Value, ["_handler"] = "register", ["Input.Email"] = "me@example.com", + ["Input.Password"] = "Passw0rd!x", ["Input.ConfirmPassword"] = "Passw0rd!x", + }), TestContext.Current.CancellationToken); + var home = await client.GetStringAsync("/", TestContext.Current.CancellationToken); + return (client, Token().Match(home).Groups[1].Value); + } + + [Fact] + public async Task The_language_chosen_in_Settings_applies_without_any_cookie() + { + using var factory = Factory(); + var (client, _) = await SignedInAsync(factory); + using (var scope = factory.Services.CreateScope()) + { + var id = (await scope.ServiceProvider.GetRequiredService>().FindByEmailAsync("me@example.com"))!.Id; + scope.ServiceProvider.GetRequiredService().Save(id, Preferences.Default with { Language = "es", Theme = "dark" }); + } + + var html = await client.GetStringAsync("/", TestContext.Current.CancellationToken); + + Assert.Contains(">().FindByEmailAsync("me@example.com"))!.Id; + scope.ServiceProvider.GetRequiredService().QueueOf(id).Insert(new Queueify.Models.BacklogItem { Album = "Mine" }); + Assert.True(Directory.Exists(Path.Combine(_root, "data", id))); + } + + var page = await client.GetStringAsync("/Account/Manage/DeletePersonalData", TestContext.Current.CancellationToken); + var response = await client.PostAsync("/Account/Manage/DeletePersonalData", new FormUrlEncodedContent(new Dictionary + { + ["__RequestVerificationToken"] = Token().Match(page).Groups[1].Value, ["_handler"] = "delete-user", ["Input.Password"] = "Passw0rd!x", + }), TestContext.Current.CancellationToken); + + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.False(Directory.Exists(Path.Combine(_root, "data", id))); + } + + [Fact] + public async Task A_new_account_is_greeted_by_the_quick_tour_once_in_the_shell() + { + using var factory = Factory(); + var (client, _) = await SignedInAsync(factory); + + var html = await client.GetStringAsync("/add", TestContext.Current.CancellationToken); + + Assert.Single(Regex.Matches(html, "class=\"tour\"")); + } + + [Fact] + public async Task The_shell_menu_saves_the_choice_to_the_account_too() + { + using var factory = Factory(); + var (client, token) = await SignedInAsync(factory); + + await client.PostAsync("/prefs", new FormUrlEncodedContent(new Dictionary + { + ["__RequestVerificationToken"] = token, ["language"] = "es", ["theme"] = "light", ["returnUrl"] = "/", + }), TestContext.Current.CancellationToken); + + // A new browser (no cookies) of the same account. + using var scope = factory.Services.CreateScope(); + var id = (await scope.ServiceProvider.GetRequiredService>().FindByEmailAsync("me@example.com"))!.Id; + var saved = scope.ServiceProvider.GetRequiredService().Load(id); + Assert.Equal(("es", "light"), (saved.Language, saved.Theme)); + } +} diff --git a/Queueify.Web.Tests/ComponentTests.cs b/Queueify.Web.Tests/ComponentTests.cs index dd662fc..7cbaef7 100644 --- a/Queueify.Web.Tests/ComponentTests.cs +++ b/Queueify.Web.Tests/ComponentTests.cs @@ -453,6 +453,20 @@ public void Adding_by_hand_while_a_search_runs_does_not_bring_old_results_back() Assert.Empty(cut.FindAll("li.q-result")); } + [Fact] + public void A_link_with_q_fills_the_box_and_searches_at_once() + { + SaveKeys(tidal: false); + Catalogs.Spotify = [Match(MusicService.Spotify, "sp1", "Signos", "Soda Stereo", 1986)]; + Services.GetRequiredService().NavigateTo("/add?q=soda%20stereo%20signos"); + + var cut = Open(); + + cut.WaitForAssertion(() => Assert.Single(cut.FindAll("li.q-result"))); + Assert.Equal("soda stereo signos", cut.Find("#q-search").GetAttribute("value")); + Assert.Contains("soda stereo signos", Catalogs.Queries); + } + [Fact] public void A_remembered_magazine_is_filled_in_for_the_next_visit() { diff --git a/Queueify.Web.Tests/Pages/HelpTests.cs b/Queueify.Web.Tests/Pages/HelpTests.cs index 99930ed..8ba574a 100644 --- a/Queueify.Web.Tests/Pages/HelpTests.cs +++ b/Queueify.Web.Tests/Pages/HelpTests.cs @@ -40,8 +40,8 @@ public void Lists_every_shortcut_with_its_keys_and_meaning() var cut = Render(); var rows = cut.FindAll("table.shortcuts tbody tr"); - Assert.Equal(Shortcuts.All.Count, rows.Count); - foreach (var shortcut in Shortcuts.All) + Assert.Equal(Shortcuts.Web.Count, rows.Count); + foreach (var shortcut in Shortcuts.Web) Assert.Contains(rows, r => r.TextContent.Contains(shortcut.Keys) && r.TextContent.Contains(shortcut.Description)); Assert.NotEmpty(cut.FindAll("kbd")); } diff --git a/Queueify.Web/Components/Account/Pages/Manage/DeletePersonalData.razor b/Queueify.Web/Components/Account/Pages/Manage/DeletePersonalData.razor index 9cbe81d..87c6513 100644 --- a/Queueify.Web/Components/Account/Pages/Manage/DeletePersonalData.razor +++ b/Queueify.Web/Components/Account/Pages/Manage/DeletePersonalData.razor @@ -8,6 +8,7 @@ @inject SignInManager SignInManager @inject IdentityRedirectManager RedirectManager @inject ILogger Logger +@inject Queueify.Web.Storage.UserStores Stores @Loc.T("web.acct.delete.title") @@ -84,6 +85,8 @@ await SignInManager.SignOutAsync(); var userId = await UserManager.GetUserIdAsync(user); + // The account is gone, so is everything kept for it: queue, settings, keys, preferences. + Stores.Delete(userId); Logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId); RedirectManager.RedirectToCurrentPage(); diff --git a/Queueify.Web/Components/App.razor b/Queueify.Web/Components/App.razor index 1744564..064c66d 100644 --- a/Queueify.Web/Components/App.razor +++ b/Queueify.Web/Components/App.razor @@ -33,7 +33,7 @@ [CascadingParameter] private HttpContext HttpContext { get; set; } = default!; private string Lang => HttpContext.Items[nameof(Prefs.Language)] as string ?? "en"; - private string Theme => Prefs.Theme(HttpContext.Request.Cookies[Prefs.ThemeCookie]); + private string Theme => HttpContext.Items[nameof(Prefs.Theme)] as string ?? "system"; private IComponentRenderMode? PageRenderMode => HttpContext.AcceptsInteractiveRouting() ? InteractiveServer : null; diff --git a/Queueify.Web/Components/Layout/MainLayout.razor b/Queueify.Web/Components/Layout/MainLayout.razor index 671e050..755e9b8 100644 --- a/Queueify.Web/Components/Layout/MainLayout.razor +++ b/Queueify.Web/Components/Layout/MainLayout.razor @@ -14,6 +14,7 @@ +
diff --git a/Queueify.Web/Components/Pages/Add.razor b/Queueify.Web/Components/Pages/Add.razor index a58ef90..0c99420 100644 --- a/Queueify.Web/Components/Pages/Add.razor +++ b/Queueify.Web/Components/Pages/Add.razor @@ -1,4 +1,4 @@ -@page "/add" +@page "/add" @attribute [Microsoft.AspNetCore.Authorization.Authorize] @implements IDisposable @inject UserQueue Queue @@ -108,11 +108,19 @@ private CancellationTokenSource? _cts; private string _qArtist = "", _qAlbum = "", _qYear = ""; + /// /add?q=Artist - Album 1999 fills the box and searches at once (a link from a note, a share, a shortcut). + [SupplyParameterFromQuery(Name = "q")] public string? Prefill { get; set; } + protected override async Task OnInitializedAsync() { await Queue.LoadAsync(); _magazine = Queue.Settings.LastSource; _needsKeys = !Queue.Settings.SpotifyConfigured && !Queue.Settings.TidalConfigured; + if (Prefill is { Length: > 0 } q && q.Trim().Length > 0) + { + _query = q.Trim().Length > 200 ? q.Trim()[..200] : q.Trim(); + await RunSearch(_cts = new CancellationTokenSource()); + } } protected override async Task OnAfterRenderAsync(bool firstRender) diff --git a/Queueify.Web/Components/Pages/Help.razor b/Queueify.Web/Components/Pages/Help.razor index 66b9662..12dcbb2 100644 --- a/Queueify.Web/Components/Pages/Help.razor +++ b/Queueify.Web/Components/Pages/Help.razor @@ -27,7 +27,7 @@ @Loc.T("webHelp.col.keys")@Loc.T("webHelp.col.does") - @foreach (var shortcut in Shortcuts.All) + @foreach (var shortcut in Shortcuts.Web) { @shortcut.Keys diff --git a/Queueify.Web/Services/Prefs.cs b/Queueify.Web/Services/Prefs.cs index ffdcb5c..d8a8d59 100644 --- a/Queueify.Web/Services/Prefs.cs +++ b/Queueify.Web/Services/Prefs.cs @@ -14,6 +14,12 @@ public static string Language(string? cookie, string? acceptLanguage) return first.StartsWith("es", StringComparison.OrdinalIgnoreCase) ? "es" : "en"; } + /// The account's own choice (Settings, or the shell menu) comes first; "system" or nothing leaves it to the cookie and the browser. + public static string Language(string? account, string? cookie, string? acceptLanguage) => + account is "en" or "es" ? account : Language(cookie, acceptLanguage); + + public static string Theme(string? account, string? cookie) => account is "light" or "dark" ? account : Theme(cookie); + public static string Theme(string? cookie) => cookie is "light" or "dark" ? cookie : "system"; /// The same-site path to go back to, or "/" for anything that could lead elsewhere. diff --git a/Queueify.Web/Services/QueueifyUi.cs b/Queueify.Web/Services/QueueifyUi.cs index ec9c4f5..2a6f760 100644 --- a/Queueify.Web/Services/QueueifyUi.cs +++ b/Queueify.Web/Services/QueueifyUi.cs @@ -1,3 +1,4 @@ +using System.Security.Claims; using Microsoft.AspNetCore.Components.Server.Circuits; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Identity; @@ -64,8 +65,11 @@ public static WebApplication MapQueueifyUi(this WebApplication app) headers["Referrer-Policy"] = "no-referrer"; return Task.CompletedTask; }); - var language = Prefs.Language(context.Request.Cookies[Prefs.LanguageCookie], context.Request.Headers.AcceptLanguage); + var account = context.User.Identity?.IsAuthenticated == true && context.User.FindFirstValue(ClaimTypes.NameIdentifier) is { Length: > 0 } id + ? context.RequestServices.GetRequiredService().Load(id) : null; + var language = Prefs.Language(account?.Language, context.Request.Cookies[Prefs.LanguageCookie], context.Request.Headers.AcceptLanguage); context.Items[nameof(Prefs.Language)] = language; + context.Items[nameof(Prefs.Theme)] = Prefs.Theme(account?.Theme, context.Request.Cookies[Prefs.ThemeCookie]); using (Loc.Override(language)) await next(); }); @@ -75,6 +79,13 @@ public static WebApplication MapQueueifyUi(this WebApplication app) var options = new CookieOptions { MaxAge = TimeSpan.FromDays(365), SameSite = SameSiteMode.Lax, IsEssential = true, Secure = context.Request.IsHttps, HttpOnly = true }; if (language is "en" or "es") context.Response.Cookies.Append(Prefs.LanguageCookie, language, options); if (theme is "light" or "dark" or "system") context.Response.Cookies.Append(Prefs.ThemeCookie, theme, options); + // A signed-in account keeps its choice for every browser it uses; Settings shows and changes the same values. + if (context.User.Identity?.IsAuthenticated == true && context.User.FindFirstValue(ClaimTypes.NameIdentifier) is { Length: > 0 } id) + { + var store = context.RequestServices.GetRequiredService(); + var now = store.Load(id); + store.Save(id, now with { Language = language is "en" or "es" ? language : now.Language, Theme = theme is "light" or "dark" or "system" ? theme : now.Theme }); + } return Results.LocalRedirect(Prefs.LocalReturn(returnUrl)); }).AllowAnonymous(); From 606500a4529fd700543c52782a043ea5b44d1804 Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:07:12 -0300 Subject: [PATCH 34/66] test(web): the migration snapshot matches the model the app builds Co-Authored-By: Claude Sonnet 5.5 --- Queueify.Web.Tests/MigrationTests.cs | 59 ++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Queueify.Web.Tests/MigrationTests.cs diff --git a/Queueify.Web.Tests/MigrationTests.cs b/Queueify.Web.Tests/MigrationTests.cs new file mode 100644 index 0000000..4df026c --- /dev/null +++ b/Queueify.Web.Tests/MigrationTests.cs @@ -0,0 +1,59 @@ +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Queueify.Web.Data; + +namespace Queueify.Web.Tests; + +/// +/// The hand-kept migration snapshot must describe the model exactly, or every start of the app throws. The model +/// depends on Identity's options (schema version 3 adds passkeys), so these build the context the way the app does, +/// from its own service provider; a bare context would cache a different model for the whole process. +/// +public sealed class MigrationTests : IDisposable +{ + private readonly string _dir = Path.Combine(Path.GetTempPath(), "qw-mig-" + Guid.NewGuid().ToString("N")); + private WebApplicationFactory? _factory; + + public void Dispose() + { + _factory?.Dispose(); + Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); + try { Directory.Delete(_dir, true); } catch (IOException) { } + } + + private IServiceProvider App() => (_factory = new WebApplicationFactory().WithWebHostBuilder(b => + { + Directory.CreateDirectory(_dir); + b.UseSetting("ConnectionStrings:DefaultConnection", $"DataSource={Path.Combine(_dir, "app.db")};Pooling=False"); + b.UseSetting("Queueify:DataDir", Path.Combine(_dir, "data")); + })).Services; + + [Fact] + public void The_snapshot_matches_the_model_the_app_builds() + { + using var scope = App().CreateScope(); + Assert.False(scope.ServiceProvider.GetRequiredService().Database.HasPendingModelChanges(), + "Add a migration: the model changed since the last one."); + } + + [Fact] + public void The_app_starts_on_a_new_database_and_leaves_nothing_pending() + { + using var scope = App().CreateScope(); // starting the host ran the migrations + Assert.Empty(scope.ServiceProvider.GetRequiredService().Database.GetPendingMigrations()); + } + + [Fact] + public async Task Migrating_again_from_several_places_at_once_changes_nothing() + { + var services = App(); + var errors = new List(); + await Task.WhenAll(Enumerable.Range(0, 6).Select(_ => Task.Run(() => + { + try { using var scope = services.CreateScope(); scope.ServiceProvider.GetRequiredService().Database.Migrate(); } + catch (Exception ex) { lock (errors) errors.Add(ex); } + }))); + Assert.Empty(errors); + } +} From 7efc61df201e0e394d54a4626c1b27e803663a26 Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:13:08 -0300 Subject: [PATCH 35/66] chore(web): newer AngleSharp for the bUnit tests (advisory) Co-Authored-By: Claude Sonnet 5.5 --- Queueify.Web.Tests/Queueify.Web.Tests.csproj | 1 + 1 file changed, 1 insertion(+) diff --git a/Queueify.Web.Tests/Queueify.Web.Tests.csproj b/Queueify.Web.Tests/Queueify.Web.Tests.csproj index 5ee8d10..35ac9c5 100644 --- a/Queueify.Web.Tests/Queueify.Web.Tests.csproj +++ b/Queueify.Web.Tests/Queueify.Web.Tests.csproj @@ -9,6 +9,7 @@ + From 3c87f1f8f6b803f4fb6a718528d9ac7d9cdbcd2c Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:18:00 -0300 Subject: [PATCH 36/66] fix(web): load the component stylesheet bundle again Co-Authored-By: Claude Sonnet 5.5 --- Queueify.Web/Components/App.razor | 1 + 1 file changed, 1 insertion(+) diff --git a/Queueify.Web/Components/App.razor b/Queueify.Web/Components/App.razor index 064c66d..00f9944 100644 --- a/Queueify.Web/Components/App.razor +++ b/Queueify.Web/Components/App.razor @@ -15,6 +15,7 @@ + From 1073e48b2d9f5fad556fa9ef56248e64aacd1c4f Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:24:38 -0300 Subject: [PATCH 37/66] chore: ignore scratch folders Co-Authored-By: Claude Sonnet 5.5 --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index faf6791..ffdb971 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ publish/ .cache/ dist/ Queueify.Web/App_Data/ +.scratch/ From 193aa896c122af52ce04c98cd6465ab53007bf89 Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:42:12 -0300 Subject: [PATCH 38/66] fix(web): decode photos with SkiaSharp so Release publish works SixLabors.ImageSharp 4.x refuses dotnet publish -c Release without a license key. SkiaSharp is MIT and ImageGuard keeps its sniff, pixel cap, upright turn, downscale and metadata-free PNG output, now also tested for pixels. Co-Authored-By: Claude Sonnet 5.5 --- Queueify.Web.Tests/Ocr/ImageGuardTests.cs | 66 +++++++++++--------- Queueify.Web.Tests/Ocr/PhotoEndpointTests.cs | 7 +-- Queueify.Web.Tests/Ocr/PhotoReaderTests.cs | 8 +-- Queueify.Web.Tests/Support/TestImages.cs | 63 +++++++++++++++++++ Queueify.Web/Ocr/ImageGuard.cs | 65 +++++++++++++------ Queueify.Web/Queueify.Web.csproj | 5 +- README.md | 3 + SECURITY.md | 2 + docs/WEB_PORT.md | 2 +- docs/adr/0011-web-ocr.md | 5 +- 10 files changed, 159 insertions(+), 67 deletions(-) create mode 100644 Queueify.Web.Tests/Support/TestImages.cs diff --git a/Queueify.Web.Tests/Ocr/ImageGuardTests.cs b/Queueify.Web.Tests/Ocr/ImageGuardTests.cs index 7fdcbfb..7ea35d1 100644 --- a/Queueify.Web.Tests/Ocr/ImageGuardTests.cs +++ b/Queueify.Web.Tests/Ocr/ImageGuardTests.cs @@ -1,10 +1,7 @@ using System.Text; using Queueify.Web.Ocr; -using SixLabors.ImageSharp; -using SixLabors.ImageSharp.Formats.Jpeg; -using SixLabors.ImageSharp.Formats.Png; -using SixLabors.ImageSharp.Formats.Webp; -using SixLabors.ImageSharp.PixelFormats; +using Queueify.Web.Tests.Support; +using SkiaSharp; namespace Queueify.Web.Tests.Ocr; @@ -12,17 +9,17 @@ public class ImageGuardTests { private static readonly OcrOptions Defaults = new(); - private static byte[] Picture(int w, int h, string format = "png") + private static byte[] Picture(int w, int h, string format = "png") => TestImages.Encode(w, h, format switch { - using var image = new Image(w, h, new Rgb24(200, 30, 30)); - using var ms = new MemoryStream(); - switch (format) - { - case "jpeg": image.SaveAsJpeg(ms); break; - case "webp": image.SaveAsWebp(ms); break; - default: image.SaveAsPng(ms); break; - } - return ms.ToArray(); + "jpeg" => SKEncodedImageFormat.Jpeg, + "webp" => SKEncodedImageFormat.Webp, + _ => SKEncodedImageFormat.Png, + }); + + private static SKImageInfo Info(byte[] bytes) + { + using var codec = SKCodec.Create(new MemoryStream(bytes)); + return codec.Info; } private static PhotoProblem ProblemOf(byte[] bytes, OcrOptions? options = null) => @@ -43,17 +40,14 @@ public void Real_pictures_are_re_encoded_as_png(string format) [Fact] public void Metadata_such_as_GPS_does_not_survive_the_re_encode() { - using var image = new Image(20, 20); - image.Metadata.ExifProfile = new SixLabors.ImageSharp.Metadata.Profiles.Exif.ExifProfile(); - image.Metadata.ExifProfile.SetValue(SixLabors.ImageSharp.Metadata.Profiles.Exif.ExifTag.Make, "SecretCamera"); - using var jpeg = new MemoryStream(); - image.SaveAsJpeg(jpeg); - Assert.Contains("SecretCamera", Encoding.Latin1.GetString(jpeg.ToArray())); // the test input does carry it + var jpeg = TestImages.JpegWithExif(20, 20, make: "SecretCamera"); + Assert.Contains("SecretCamera", Encoding.Latin1.GetString(jpeg)); // the test input does carry it - var prepared = ImageGuard.Prepare(new MemoryStream(jpeg.ToArray()), Defaults); + var prepared = ImageGuard.Prepare(new MemoryStream(jpeg), Defaults); Assert.DoesNotContain("SecretCamera", Encoding.Latin1.GetString(prepared.Png)); - Assert.Null(Image.Load(prepared.Png).Metadata.ExifProfile); + Assert.DoesNotContain("Exif", Encoding.Latin1.GetString(prepared.Png)); + Assert.Equal((20, 20), (Info(prepared.Png).Width, Info(prepared.Png).Height)); } [Fact] @@ -73,17 +67,31 @@ public void A_small_photo_is_not_enlarged() [Fact] public void A_phone_photo_stored_rotated_is_turned_upright() { - using var image = new Image(60, 20); - image.Metadata.ExifProfile = new SixLabors.ImageSharp.Metadata.Profiles.Exif.ExifProfile(); - image.Metadata.ExifProfile.SetValue(SixLabors.ImageSharp.Metadata.Profiles.Exif.ExifTag.Orientation, (ushort)6); // rotate 90 clockwise - using var jpeg = new MemoryStream(); - image.SaveAsJpeg(jpeg); + var jpeg = TestImages.JpegWithExif(60, 20, orientation: 6); // rotate 90 clockwise - var prepared = ImageGuard.Prepare(new MemoryStream(jpeg.ToArray()), Defaults); + var prepared = ImageGuard.Prepare(new MemoryStream(jpeg), Defaults); Assert.Equal((20, 60), (prepared.Width, prepared.Height)); } + [Theory] + [InlineData(1, "TL")] + [InlineData(6, "TR")] // rotate 90 clockwise: the stored top-left ends at the top-right + [InlineData(3, "BR")] + [InlineData(8, "BL")] + public void The_upright_turn_moves_the_pixels_not_just_the_size(int orientation, string blueCorner) + { + var jpeg = TestImages.JpegWithExif(80, 40, (ushort)orientation, baseJpeg: TestImages.JpegWithBlueTopLeft(80, 40)); + + var prepared = ImageGuard.Prepare(new MemoryStream(jpeg), Defaults); + + using var bitmap = SKBitmap.Decode(prepared.Png); + bool Blue(int x, int y) { var c = bitmap.GetPixel(x, y); return c.Blue > 200 && c.Red < 80; } + var (w, h) = (bitmap.Width, bitmap.Height); + var corners = new Dictionary { ["TL"] = Blue(2, 2), ["TR"] = Blue(w - 3, 2), ["BL"] = Blue(2, h - 3), ["BR"] = Blue(w - 3, h - 3) }; + Assert.Equal([blueCorner], corners.Where(c => c.Value).Select(c => c.Key)); + } + [Fact] public void Text_pretending_to_be_a_picture_is_refused() => Assert.Equal(PhotoProblem.NotAnImage, ProblemOf(Encoding.UTF8.GetBytes(""))); diff --git a/Queueify.Web.Tests/Ocr/PhotoEndpointTests.cs b/Queueify.Web.Tests/Ocr/PhotoEndpointTests.cs index 61af090..965f56d 100644 --- a/Queueify.Web.Tests/Ocr/PhotoEndpointTests.cs +++ b/Queueify.Web.Tests/Ocr/PhotoEndpointTests.cs @@ -7,8 +7,6 @@ using Queueify.Services; using Queueify.Web.Ocr; using Queueify.Web.Tests.Support; -using SixLabors.ImageSharp; -using SixLabors.ImageSharp.PixelFormats; namespace Queueify.Web.Tests.Ocr; @@ -42,10 +40,7 @@ public Task RecognizeAsync(Stream image, string language, Cancellati private static byte[] Png(int w = 100, int h = 50) { - using var image = new Image(w, h); - using var ms = new MemoryStream(); - image.SaveAsPng(ms); - return ms.ToArray(); + return Support.TestImages.Png(w, h); } private static ByteArrayContent Body(byte[] bytes, string type = "image/png") diff --git a/Queueify.Web.Tests/Ocr/PhotoReaderTests.cs b/Queueify.Web.Tests/Ocr/PhotoReaderTests.cs index 0e1d51b..4180590 100644 --- a/Queueify.Web.Tests/Ocr/PhotoReaderTests.cs +++ b/Queueify.Web.Tests/Ocr/PhotoReaderTests.cs @@ -1,7 +1,5 @@ using Queueify.Services; using Queueify.Web.Ocr; -using SixLabors.ImageSharp; -using SixLabors.ImageSharp.PixelFormats; namespace Queueify.Web.Tests.Ocr; @@ -22,11 +20,7 @@ public async Task RecognizeAsync(Stream image, string language, Canc private static MemoryStream Photo(int w = 20, int h = 10) { - using var image = new Image(w, h); - var ms = new MemoryStream(); - image.SaveAsPng(ms); - ms.Position = 0; - return ms; + return Support.TestImages.PngStream(w, h); } private static PhotoReader Reader(IOcr ocr, OcrOptions? options = null) => diff --git a/Queueify.Web.Tests/Support/TestImages.cs b/Queueify.Web.Tests/Support/TestImages.cs new file mode 100644 index 0000000..206f007 --- /dev/null +++ b/Queueify.Web.Tests/Support/TestImages.cs @@ -0,0 +1,63 @@ +using System.Buffers.Binary; +using System.Text; +using SkiaSharp; + +namespace Queueify.Web.Tests.Support; + +/// Small real pictures for the photo tests, made with the same library the server decodes with. +internal static class TestImages +{ + public static byte[] Encode(int w, int h, SKEncodedImageFormat format = SKEncodedImageFormat.Png, SKColor? fill = null) + { + using var bitmap = new SKBitmap(w, h, SKColorType.Rgba8888, SKAlphaType.Opaque); + bitmap.Erase(fill ?? new SKColor(200, 30, 30)); + using var image = SKImage.FromBitmap(bitmap); + using var data = image.Encode(format, 90); + return data.ToArray(); + } + + public static byte[] Png(int w, int h) => Encode(w, h); + + /// A JPEG whose top-left quarter is blue and the rest red, to tell which way up it ended. + public static byte[] JpegWithBlueTopLeft(int w, int h) + { + using var bitmap = new SKBitmap(w, h, SKColorType.Rgba8888, SKAlphaType.Opaque); + bitmap.Erase(new SKColor(255, 0, 0)); + using (var canvas = new SKCanvas(bitmap)) canvas.DrawRect(0, 0, w / 2f, h / 2f, new SKPaint { Color = new SKColor(0, 0, 255) }); + using var image = SKImage.FromBitmap(bitmap); + return image.Encode(SKEncodedImageFormat.Jpeg, 95).ToArray(); + } + + public static MemoryStream PngStream(int w, int h) => new(Png(w, h)); + + /// A JPEG carrying an EXIF block with an orientation and/or a camera make, written by hand because Skia does not write EXIF. + public static byte[] JpegWithExif(int w, int h, ushort? orientation = null, string? make = null, byte[]? baseJpeg = null) + { + var jpeg = baseJpeg ?? Encode(w, h, SKEncodedImageFormat.Jpeg); + var entries = new List<(ushort Tag, ushort Type, uint Count, byte[] Value)>(); + var makeBytes = make is null ? [] : Encoding.ASCII.GetBytes(make + "\0"); + if (make is not null) entries.Add((0x010F, 2, (uint)makeBytes.Length, makeBytes)); + if (orientation is { } o) entries.Add((0x0112, 3, 1, [(byte)(o >> 8), (byte)o, 0, 0])); + + var tiff = new List { 0x4D, 0x4D, 0x00, 0x2A, 0, 0, 0, 8 }; + void U16(ushort v) { Span b = stackalloc byte[2]; BinaryPrimitives.WriteUInt16BigEndian(b, v); tiff.AddRange(b.ToArray()); } + void U32(uint v) { Span b = stackalloc byte[4]; BinaryPrimitives.WriteUInt32BigEndian(b, v); tiff.AddRange(b.ToArray()); } + U16((ushort)entries.Count); + var spill = (uint)(8 + 2 + 12 * entries.Count + 4); + var tail = new List(); + foreach (var (tag, type, count, value) in entries) + { + U16(tag); U16(type); U32(count); + if (value.Length > 4) { U32(spill + (uint)tail.Count); tail.AddRange(value); } + else tiff.AddRange(value.Concat(new byte[4 - value.Length])); + } + U32(0); + tiff.AddRange(tail); + + var payload = Encoding.ASCII.GetBytes("Exif\0\0").Concat(tiff).ToArray(); + var segment = new List { 0xFF, 0xE1, (byte)((payload.Length + 2) >> 8), (byte)(payload.Length + 2) }; + segment.AddRange(payload); + // SOI, then our APP1 first, then whatever Skia wrote (its own JFIF/APP0 segments follow). + return [.. jpeg[..2], .. segment, .. jpeg[2..]]; + } +} diff --git a/Queueify.Web/Ocr/ImageGuard.cs b/Queueify.Web/Ocr/ImageGuard.cs index 74cda50..528f16d 100644 --- a/Queueify.Web/Ocr/ImageGuard.cs +++ b/Queueify.Web/Ocr/ImageGuard.cs @@ -1,7 +1,4 @@ -using SixLabors.ImageSharp; -using SixLabors.ImageSharp.Formats; -using SixLabors.ImageSharp.Formats.Png; -using SixLabors.ImageSharp.Processing; +using SkiaSharp; namespace Queueify.Web.Ocr; @@ -29,30 +26,58 @@ public static PreparedImage Prepare(Stream input, OcrOptions options) try { - var info = Image.Identify(bytes); - if ((long)info.Width * info.Height > options.MaxPixels) throw new PhotoException(PhotoProblem.TooManyPixels); + // The codec reads the header only; nothing is decoded before the pixel budget is checked. + using var data = SKData.CreateCopy(bytes); + using var codec = SKCodec.Create(data) ?? throw new PhotoException(PhotoProblem.Corrupt); + var size = codec.Info; + if (size.Width <= 0 || size.Height <= 0) throw new PhotoException(PhotoProblem.Corrupt); + if ((long)size.Width * size.Height > options.MaxPixels) throw new PhotoException(PhotoProblem.TooManyPixels); - using var image = Image.Load(new DecoderOptions { MaxFrames = 1 }, bytes); - image.Mutate(x => - { - x.AutoOrient(); - if (Math.Max(image.Width, image.Height) > options.MaxSide) - x.Resize(new ResizeOptions { Mode = ResizeMode.Max, Size = new Size(options.MaxSide, options.MaxSide) }); - }); - image.Metadata.ExifProfile = null; - image.Metadata.IccProfile = null; - image.Metadata.XmpProfile = null; + using var decoded = new SKBitmap(new SKImageInfo(size.Width, size.Height, SKColorType.Rgba8888, SKAlphaType.Premul)); + // Only a complete decode counts: a truncated file is corrupt, not a half-grey picture. + if (codec.GetPixels(decoded.Info, decoded.GetPixels()) != SKCodecResult.Success) throw new PhotoException(PhotoProblem.Corrupt); - using var png = new MemoryStream(); - image.Save(png, new PngEncoder()); - return new PreparedImage(png.ToArray(), image.Width, image.Height); + var origin = codec.EncodedOrigin; + var (width, height) = origin is SKEncodedOrigin.LeftTop or SKEncodedOrigin.RightTop or SKEncodedOrigin.RightBottom or SKEncodedOrigin.LeftBottom + ? (size.Height, size.Width) : (size.Width, size.Height); + var scale = Math.Max(width, height) > options.MaxSide ? (double)options.MaxSide / Math.Max(width, height) : 1; + var outW = Math.Max(1, (int)Math.Round(width * scale)); + var outH = Math.Max(1, (int)Math.Round(height * scale)); + + // A fresh opaque surface: transparency becomes white (like the printed page) and none of the source + // metadata can be carried over, because only pixels are drawn. + using var surface = SKSurface.Create(new SKImageInfo(outW, outH, SKColorType.Rgba8888, SKAlphaType.Opaque)) + ?? throw new PhotoException(PhotoProblem.Corrupt); + var canvas = surface.Canvas; + canvas.Clear(SKColors.White); + canvas.Scale((float)outW / width, (float)outH / height); + canvas.Concat(Upright(size.Width, size.Height, origin)); + using var source = SKImage.FromBitmap(decoded); + canvas.DrawImage(source, 0, 0, new SKSamplingOptions(SKCubicResampler.Mitchell)); + + using var image = surface.Snapshot(); + using var png = image.Encode(SKEncodedImageFormat.Png, 100) ?? throw new PhotoException(PhotoProblem.Corrupt); + return new PreparedImage(png.ToArray(), outW, outH); } - catch (Exception ex) when (ex is ImageFormatException or InvalidOperationException or NotSupportedException or EndOfStreamException or IOException) + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or NotSupportedException or EndOfStreamException or IOException or OutOfMemoryException) { throw new PhotoException(PhotoProblem.Corrupt); } } + /// Maps the stored pixels to the way the camera was held (EXIF orientation values 1 to 8). + private static SKMatrix Upright(int w, int h, SKEncodedOrigin origin) => origin switch + { + SKEncodedOrigin.TopRight => new SKMatrix(-1, 0, w, 0, 1, 0, 0, 0, 1), + SKEncodedOrigin.BottomRight => new SKMatrix(-1, 0, w, 0, -1, h, 0, 0, 1), + SKEncodedOrigin.BottomLeft => new SKMatrix(1, 0, 0, 0, -1, h, 0, 0, 1), + SKEncodedOrigin.LeftTop => new SKMatrix(0, 1, 0, 1, 0, 0, 0, 0, 1), + SKEncodedOrigin.RightTop => new SKMatrix(0, -1, h, 1, 0, 0, 0, 0, 1), + SKEncodedOrigin.RightBottom => new SKMatrix(0, -1, h, -1, 0, w, 0, 0, 1), + SKEncodedOrigin.LeftBottom => new SKMatrix(0, 1, 0, -1, 0, w, 0, 0, 1), + _ => SKMatrix.Identity, + }; + private static byte[] ReadCapped(Stream input, long max) { using var buffer = new MemoryStream(); diff --git a/Queueify.Web/Queueify.Web.csproj b/Queueify.Web/Queueify.Web.csproj index d1ef63a..bc4bc56 100644 --- a/Queueify.Web/Queueify.Web.csproj +++ b/Queueify.Web/Queueify.Web.csproj @@ -17,10 +17,11 @@ - + - + + diff --git a/README.md b/README.md index 8990145..e800725 100644 --- a/README.md +++ b/README.md @@ -155,3 +155,6 @@ Conventional Commits, pull requests with adversarial review). Design documents l [GPL-3.0-or-later](LICENSE). Spotify and Tidal are trademarks of their owners; Queueify isn't affiliated with either. Their logos in the app come from [Simple Icons](https://simpleicons.org) (CC0). +The web app decodes photos with [SkiaSharp](https://github.com/mono/SkiaSharp) (MIT) and Tesseract +(Apache-2.0, run as a separate program); both are permissive and need no license key to build a release +([ADR-0011](docs/adr/0011-web-ocr.md)). diff --git a/SECURITY.md b/SECURITY.md index b3f46af..93bb7ef 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -47,6 +47,8 @@ web server (`Queueify.Web`, [ADR-0010](docs/adr/0010-web-app-and-shared-queue.md Out of scope: a compromised PC or user account, and the security of Spotify, Tidal and Google's services. +Photo decoding uses SkiaSharp (MIT), a native library: it is fed only bytes that passed the sniff, size and pixel checks above, and its licence (like Tesseract's Apache-2.0) needs no key to publish a release; see [ADR-0011](docs/adr/0011-web-ocr.md). + ## Threat model: the web app (`Queueify.Web`) | Asset / surface | Threat | Defence | diff --git a/docs/WEB_PORT.md b/docs/WEB_PORT.md index 9b82a1a..9c152a3 100644 --- a/docs/WEB_PORT.md +++ b/docs/WEB_PORT.md @@ -80,7 +80,7 @@ secrets needs real accounts. | `IOcr` + implementation | Windows OCR does not exist on Linux hosts. Options: **Tesseract** (NuGet `Tesseract`, `spa`/`eng` traineddata, free, runs anywhere); **Azure AI Vision Read** (best quality for magazine photos, small cost); or host on Windows and keep `Windows.Media.Ocr`. Recommended: Tesseract first, Azure behind the same interface later. | | `ILinkOpener` | Web: plain ``; deep links `https://open.spotify.com/...` and `https://tidal.com/browse/album/...` work in browsers. | | Per-request localization | `Loc` is static today. Wrap in a scoped `ILocalizer` (same string tables) keyed on the user's language; keeps Rioplatense ES. | -| Photo upload limits | Max size, content-type check, `ImageSharp`-based re-encode, delete after OCR (nothing stored). | +| Photo upload limits | Max size, content-type check, `SkiaSharp`-based re-encode (ADR-0011), delete after OCR (nothing stored). | | Backup / export | Download `queueify.db` as JSON/CSV; **import** from desktop (see §5). | | Health + logging | `/healthz`, structured logs, no secrets in logs. | diff --git a/docs/adr/0011-web-ocr.md b/docs/adr/0011-web-ocr.md index cab41cb..2708bad 100644 --- a/docs/adr/0011-web-ocr.md +++ b/docs/adr/0011-web-ocr.md @@ -24,8 +24,9 @@ Linux x64 hosts, with photo uploads treated as untrusted input ([ADR-0010](0010- SHA-256 matches the one in the code, replaced when a local copy doesn't match. An administrator who sets `Ocr:TessdataPath` takes over: nothing is downloaded or checked. The fast models are 2 MB (`spa`) and 4 MB (`eng`); the "best" models read photos slightly better and could be swapped in by that setting. -- **Image handling with ImageSharp** (Six Labors Split License: Apache-2.0 for software under an open source - license, which this GPL project is). An upload is sniffed by its bytes (JPEG, PNG or WebP; the declared type +- **Image handling with SkiaSharp** (MIT, with `SkiaSharp.NativeAssets.Linux.NoDependencies` for Linux hosts). + The first choice, SixLabors.ImageSharp 4.x, was dropped because `dotnet publish -c Release` refuses to build + without a Six Labors license key, so a release could not be produced by anyone without one. An upload is sniffed by its bytes (JPEG, PNG or WebP; the declared type is only a CSRF gate), its pixel count is read from the header before decoding (60 MP), it is turned upright, scaled to 3000 px and re-encoded as PNG, which drops EXIF (GPS), ICC and XMP. The upload and the PNG exist only in memory and are wiped after reading. From 18d0d7caa268da55cbaf03ff624fce160254edba Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:45:48 -0300 Subject: [PATCH 39/66] fix(web): registration confirmation answers the same for all addresses It looked the address up (404 for unknown, a working confirm link for known), so anyone could learn who has an account. No mail goes out, so it shows the generic text only. Co-Authored-By: Claude Sonnet 5.5 --- Queueify.Web.Tests/WebAppTests.cs | 20 +++++++ .../Account/IdentityNoOpEmailSender.cs | 2 +- .../Account/Pages/RegisterConfirmation.razor | 60 ++----------------- 3 files changed, 27 insertions(+), 55 deletions(-) diff --git a/Queueify.Web.Tests/WebAppTests.cs b/Queueify.Web.Tests/WebAppTests.cs index 820040b..7b0464c 100644 --- a/Queueify.Web.Tests/WebAppTests.cs +++ b/Queueify.Web.Tests/WebAppTests.cs @@ -106,6 +106,26 @@ public async Task After_the_owner_registration_is_closed_unless_the_server_opens Assert.Single(scope.ServiceProvider.GetRequiredService>().Users.ToList()); } + [Fact] + public async Task The_registration_confirmation_page_tells_nothing_about_who_has_an_account() + { + using var factory = Factory(); + await RegisterAsync(Client(factory), "owner@example.com"); + var anonymous = Client(factory); + + var known = await anonymous.GetAsync("/Account/RegisterConfirmation?email=owner@example.com", TestContext.Current.CancellationToken); + var unknown = await anonymous.GetAsync("/Account/RegisterConfirmation?email=nobody@example.com", TestContext.Current.CancellationToken); + + Assert.Equal(unknown.StatusCode, known.StatusCode); + var knownHtml = await known.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); + var unknownHtml = await unknown.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); + // The page links to itself (skip link), so only the address in that link may differ. + string Plain(string html, string address) => Regex.Replace(Regex.Replace(html.Replace(address, "X"), "", ""), "[-A-Za-z0-9_+/=]{40,}", "T"); // antiforgery tokens and component state differ per response + Assert.Equal(Plain(unknownHtml, "nobody@example.com"), Plain(knownHtml, "owner@example.com")); + Assert.DoesNotContain("ConfirmEmail", knownHtml); + Assert.DoesNotContain("userId", knownHtml); + } + [Fact] public async Task Two_simultaneous_first_registrations_make_one_owner() { diff --git a/Queueify.Web/Components/Account/IdentityNoOpEmailSender.cs b/Queueify.Web/Components/Account/IdentityNoOpEmailSender.cs index b5e43e2..2166219 100644 --- a/Queueify.Web/Components/Account/IdentityNoOpEmailSender.cs +++ b/Queueify.Web/Components/Account/IdentityNoOpEmailSender.cs @@ -4,7 +4,7 @@ namespace Queueify.Web.Components.Account; -// Remove the "else if (EmailSender is IdentityNoOpEmailSender)" block from RegisterConfirmation.razor after updating with a real implementation. +// This server sends no mail; a real sender must also bring back a confirmation flow that does not reveal which addresses have accounts. internal sealed class IdentityNoOpEmailSender : IEmailSender { private readonly IEmailSender emailSender = new NoOpEmailSender(); diff --git a/Queueify.Web/Components/Account/Pages/RegisterConfirmation.razor b/Queueify.Web/Components/Account/Pages/RegisterConfirmation.razor index 47ef526..a6b8f06 100644 --- a/Queueify.Web/Components/Account/Pages/RegisterConfirmation.razor +++ b/Queueify.Web/Components/Account/Pages/RegisterConfirmation.razor @@ -1,69 +1,21 @@ -@page "/Account/RegisterConfirmation" +@page "/Account/RegisterConfirmation" -@using System.Text -@using Microsoft.AspNetCore.Identity -@using Microsoft.AspNetCore.WebUtilities -@using Queueify.Web.Data - -@inject UserManager UserManager -@inject IEmailSender EmailSender -@inject NavigationManager NavigationManager @inject IdentityRedirectManager RedirectManager @Loc.T("web.acct.regconf.title")

@Loc.T("web.acct.regconf.title")

- - -@if (emailConfirmationLink is not null) -{ -

- @Loc.T("web.acct.regconf.nosender") @Loc.T("web.acct.regconf.docs") @Loc.T("web.acct.regconf.configure") - @Loc.T("web.acct.regconf.normally") @Loc.T("web.acct.regconf.click") -

-} -else -{ -

@Loc.T("web.acct.regconf.check")

-} +@* No mail leaves this server, so the page can neither look the address up nor show a confirmation link: it + answers the same for every address. *@ +

@Loc.T("web.acct.regconf.check")

@code { - private string? emailConfirmationLink; - private string? statusMessage; - - [CascadingParameter] - private HttpContext HttpContext { get; set; } = default!; - [SupplyParameterFromQuery] private string? Email { get; set; } - [SupplyParameterFromQuery] - private string? ReturnUrl { get; set; } - - protected override async Task OnInitializedAsync() + protected override void OnInitialized() { - if (Email is null) - { - RedirectManager.RedirectTo(""); - return; - } - - var user = await UserManager.FindByEmailAsync(Email); - if (user is null) - { - HttpContext.Response.StatusCode = StatusCodes.Status404NotFound; - statusMessage = "Error finding user for unspecified email"; - } - else if (EmailSender is IdentityNoOpEmailSender) - { - // Once you add a real email sender, you should remove this code that lets you confirm the account - var userId = await UserManager.GetUserIdAsync(user); - var code = await UserManager.GenerateEmailConfirmationTokenAsync(user); - code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); - emailConfirmationLink = NavigationManager.GetUriWithQueryParameters( - NavigationManager.ToAbsoluteUri("Account/ConfirmEmail").AbsoluteUri, - new Dictionary { ["userId"] = userId, ["code"] = code, ["returnUrl"] = ReturnUrl }); - } + if (Email is null) RedirectManager.RedirectTo(""); } } From fbdb099d7d7799ae729afe61f578b5b656038044 Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:47:19 -0300 Subject: [PATCH 40/66] fix(web): keep the account database in the data folder, not in git Queueify.Web/Data/app.db was tracked and copied to every build, so a redeploy could replace live accounts. It is now created on first run as identity.db under Queueify:DataDir; *.db is ignored. The smoke test uses a scratch folder. Co-Authored-By: Claude Sonnet 5.5 --- .gitignore | 5 +++ Queueify.Web.Tests/AccountDatabaseTests.cs | 41 ++++++++++++++++++ Queueify.Web.Tests/SmokeTests.cs | 18 +++++++- Queueify.Web/Data/app.db | Bin 118784 -> 0 bytes Queueify.Web/Program.cs | 4 +- Queueify.Web/Queueify.Web.csproj | 4 -- .../Services/QueueifyStorageExtensions.cs | 17 ++++++-- Queueify.Web/appsettings.json | 3 -- README.md | 3 +- docs/ARCHITECTURE.md | 3 +- docs/TESTING.md | 4 +- 11 files changed, 84 insertions(+), 18 deletions(-) create mode 100644 Queueify.Web.Tests/AccountDatabaseTests.cs delete mode 100644 Queueify.Web/Data/app.db diff --git a/.gitignore b/.gitignore index ffdb971..1925e73 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,8 @@ publish/ dist/ Queueify.Web/App_Data/ .scratch/ + +# Databases hold accounts and queues: never commit them +*.db +*.db-shm +*.db-wal diff --git a/Queueify.Web.Tests/AccountDatabaseTests.cs b/Queueify.Web.Tests/AccountDatabaseTests.cs new file mode 100644 index 0000000..b48bef0 --- /dev/null +++ b/Queueify.Web.Tests/AccountDatabaseTests.cs @@ -0,0 +1,41 @@ +using Microsoft.AspNetCore.Mvc.Testing; + +namespace Queueify.Web.Tests; + +/// Where the account database lives: with the rest of the server's data, never inside the source tree or the build output. +public sealed class AccountDatabaseTests : IDisposable +{ + private readonly string _dir = Path.Combine(Path.GetTempPath(), "qw-acct-" + Guid.NewGuid().ToString("N")); + + public void Dispose() + { + Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); + try { Directory.Delete(_dir, true); } catch (IOException) { } + } + + private static string RepoRoot() + { + var dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "Queueify.slnx"))) dir = dir.Parent; + return dir?.FullName ?? throw new InvalidOperationException("Queueify.slnx not found above the test output."); + } + + [Fact] + public async Task Without_a_connection_string_the_account_database_is_created_under_the_data_folder() + { + await using var factory = new WebApplicationFactory().WithWebHostBuilder(b => b.UseSetting("Queueify:DataDir", Path.Combine(_dir, "data"))); + using var client = factory.CreateClient(); // starting the host migrates the database + + Assert.True(File.Exists(Path.Combine(_dir, "data", "identity.db"))); + } + + [Fact] + public void No_account_database_is_part_of_the_source_or_the_build_output() + { + var web = Path.Combine(RepoRoot(), "Queueify.Web"); + Assert.False(File.Exists(Path.Combine(web, "Data", "app.db"))); + Assert.DoesNotContain("app.db", File.ReadAllText(Path.Combine(web, "Queueify.Web.csproj"))); + Assert.DoesNotContain("ConnectionStrings", File.ReadAllText(Path.Combine(web, "appsettings.json"))); + Assert.Contains("*.db", File.ReadAllLines(Path.Combine(RepoRoot(), ".gitignore")).Select(l => l.Trim())); + } +} diff --git a/Queueify.Web.Tests/SmokeTests.cs b/Queueify.Web.Tests/SmokeTests.cs index b9a658f..5593373 100644 --- a/Queueify.Web.Tests/SmokeTests.cs +++ b/Queueify.Web.Tests/SmokeTests.cs @@ -1,13 +1,27 @@ using Microsoft.AspNetCore.Mvc.Testing; +using Queueify.Web.Tests.Support; namespace Queueify.Web.Tests; -public sealed class SmokeTests(WebApplicationFactory factory) : IClassFixture> +public sealed class SmokeTests : IClassFixture>, IDisposable { + private readonly string _root = Path.Combine(Path.GetTempPath(), "qw-smoke-" + Guid.NewGuid().ToString("N")); + private readonly WebApplicationFactory _factory; + + // Its own data folder and account database: the smoke test must never create files in the source tree. + public SmokeTests(WebApplicationFactory factory) => _factory = ScratchHost.On(factory, _root); + + public void Dispose() + { + _factory.Dispose(); + Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); + try { Directory.Delete(_root, true); } catch (IOException) { } + } + [Fact] public async Task Health_endpoint_answers_without_signing_in() { - var response = await factory.CreateClient().GetAsync("/healthz"); + var response = await _factory.CreateClient().GetAsync("/healthz", TestContext.Current.CancellationToken); Assert.True(response.IsSuccessStatusCode); } } diff --git a/Queueify.Web/Data/app.db b/Queueify.Web/Data/app.db deleted file mode 100644 index ae41190d55c40dea2c508ec62e4332f8b6fba474..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 118784 zcmeI)O>^7E83%B}lt_uzn_m*dN!=h+rxiz%hxAL_dYW-*3bHw(NSUM@c`_arCSe<6 zl8^~7jxy;%mgAY^)DO{9KS7TE1UdAQX-}Q$^w4t;8BZ?VU0{U;35ZM_c4W?<6NLhH zvAg&^4;F7qDz^)Utt$`APD`_uOOb_$Bt`z9D3M4cN`B6hAO1N_ewpA4WWXrXzwOiEfZABT3ucE726 zlxw4wAs!BC`qo69up3Y{B$cgleluIXt8A!ul_lQIijs8OOu2oC&8+t|<2K8htntyT zm&$7XX3=e#x2KfVb+xP(b83a}F58UkYLe_jN+}hUHMO7;lU%lv%dV+EW(1VUs&Op; z2;8-)fDy3G!bdQhNPV;rlW#8%&I*S>ND8*%)H8iHE@v{*^KMU0Y-yJDSl<)Ug0Gni z%M4z@OO9MeZ|H5?(3&(0ZWKy44pT%C1Lups*Nl(?JfpZ^V7jeowicX;VrRZA;hhQj zHr=3?^4nZaQ?98bnO;`qAxgY?O`yt*pAIMWlXg89&B3!!qBXTk#I6nkM}%Ud1u zQ=_4Gf&r7fcthVCP-D%ocAMH>QETbErZ6QO6+kgczLekt77~ISmHuIqsX-j$!1=*x zbJTIaJ~P~;?T$u>y0d2XAd+A)|MF5#%yUi6XbCZQmQRMo+$r{AP7g>j_o_G5@({-) z-&zbncDq{27fFAcYOy-h@yS}L?(GKU1uMIwHM;?YVqW-;UT0XNj^WmHjGi{{vH-Xz zUQ2({)!TKwXEEX9?0ZfKt~n5 z-t8FnUd7g0y8-2-2U4L!4wuj>TaV1PUhKB+d*>hFoFSABG1}@=b6u<3W=Cz)%iJUO zt6m&wxBWHHocK^Ie((Ot-Cg&FipZ|T=?bg)( zy$P132a=Gb^dNDwl>Isxl%=f1KQs8QnS!&_-Ab4dcn*XlpO<7I6^;l#Wtkkz!p6jJ zXV^k)f9FJ8zIs)9R$?r*n!3JeJnU$;VYaPXhDCzE7q~L&rwXj&p&hn4@E8wiD8P|i zqcpm8`wqDsAcN(3=iWCFk$f~J-@6)?D1rUdGJ&h>B^sYJe6^bN}Xa z&55I&Xax^xmOP8)Jr_1iW=?m!#ml9;Zr1`%`$Upc%00Izz00bZa0SG_<0uX=z1R(IH3H&-*nf5&dNC!Rz z;D7)BrtKca3jqi~00Izz00bZa0SG_<0uX?}@B;MxKmG6j@qqvYAOHafKmY;|fB*y_ z009Uw?1Rwwb2tWV=5P$##AOHafZ~?sk=Mwma00bZa0SG_<0uX=z z1Rwwb2#l`)-v5tpY_Vq$fB*y_009U<00Izz00bZa0WN_1e=dP<2tWV=5P$##AOHaf zKmY;|fWY_);QoJnV~ah500bZa0SG_<0uX=z1Rwwb2yg-1|8og^LjVF0fB*y_009U< z00Izz00hQY0RR8L@r^C^3<3~<00bZa0SG_<0uX=z1R%f#@cy4m;2Q!EfB*y_009U< z00Izz00bZ~z5;mvKfbZWokp`Xcsfax(T!bZ6qFv=%)lMWra;X3V~?pN`3uRViY$8~SI~lcr(o zHLYu#Y`K=Tc8j{bZRwq=`B-mTwM_4tGY94QxV*e9z4*k|?l*O>ylgggt7mZ`S5~uC zRjFog6jUYIQ<_wkW)lkeBx#TNMpCJ&J5{AvB0t-O!irl+8xAYXm5P;WIh!w5mE_ij zFn%_gq_S1cZ)VGPl@0Z-vc$VtQIc+(DYp-?nf1PA+-6ymH9ng4Qd!O4EV?c8_LQ=^ zu9nqePOb3WWt)**O_F^`DW#&arWRCUlFL?d*){dYjDRv(HIC&Ufx9*pFaow&_y}eb zsrk#%f8JgmoD~j%kQ8jisb~6ZT+U>q=iQ#1*wQTPvA!py1z$54mKnT)mmIl{-q72& zp*3k1+$fZ89HxjO2F@3MuNff)ct&x-z;s*FY%Mqw#m;63AJbya$CrYBeh^P$leLgg&agayhe_QJ%Lw>svhMnmre115R#hQ2qT z#+qU6HnqK?*3x-RVM;hEfMS$4^MljosN;TpX1Gb)9gPrm zXU*(EB*9|-<)xmO=bD<)5@PNwpA3t+Q|!f@9*|`2Rd1^0A&yDDwHScxcD0l*lKwW; zVs)tFleJRa+YQPKR(3~gb^{8#EUJ#F4)0dP;emj0xxx9fV(V#3GY zQ@GS7hr|lmGIbD{>JKWNkewZJ4t;NV+SjUkF7}FlN>IhE2L_c^4m*t}f7YOS!y4(C zo18bFH)C;maZ&o}{hs4WIHat25IjF8yVp2J;EzNoq&{0LNcRPl?SFyF$Za_Kd zfmG;_!zHxJ)+4j67rU+d-uXv3X9%T3jJEpJT-WNh*-_i{GWUr6Dwy@hX4h8Rq>ghz zA#{3JIG~Yioy-E(I*Eba$eG=?-9N9Abh{Fd$@#^>=YQXIyEV0cZ-Qm%fh1%pJxJUv zWxq}aWhpE1&kVk6rr<1fw-ROqo&zDt=OtN4g(HGbStbXwurcx58MYAH-#HPNuU?g& zl^9E{rmk-q4?CJ|m~HEpVUghP1+I+xsRHYGXoqbMJjO#B3UDOXD2;C2zC&&Y$Y6Qi zx%W*(Bp;2*_pXK|N?<>=OyKGXa{oI;?}7KT61&EKwi=*C)7-x~U320nCtATn8sS`e@F(aktL9)97|Fe|uXc_gib~j`PTjo-JAJ zBz>+VJYFN$h)YTDtjb$Xrv7*?E`LCJoMt_;OSj(ce&KfK_T$wV(1~+>nEKN@aryeP zw11xUklzvRtDJK%{dd0M?H^nFp1;%3&3ebcHl{o4w3n>FLsmHPbw?8VILB#Ln07|;DE6a;nEV<~%<&e*c^Kq>hrth@fOijV;Maeqj`t|yyVbtgnx9DMyPjk69tD5@KjIr2G!Fp?KmY;| zfB*y_009U<00Iy=1_HSMKL$a-5Fh{n2tWV=5P$##AOHafKmYU00bZa0SG_<0uX=z1Rwwb2#i<&_x~dXM)MGW z00bZa0SG_<0uX=z1Rwx`V<3S0|6>pY3;_ZVfB*y_009U<00Izz00bZ~VgcO$j~E!u zLjVF0fB*y_009U<00Izz00fSK0Pg>fK@czm2tWV=5P$##AOHafKmY;|fWU|a{s;9z B<$nMG diff --git a/Queueify.Web/Program.cs b/Queueify.Web/Program.cs index 0c9171c..53827e8 100644 --- a/Queueify.Web/Program.cs +++ b/Queueify.Web/Program.cs @@ -25,10 +25,10 @@ }) .AddIdentityCookies(); -var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found."); +var connectionString = QueueifyStorageExtensions.AccountConnectionString(builder.Configuration, builder.Environment); builder.Services.AddDbContext(options => options.UseSqlite(connectionString)); -builder.Services.AddDatabaseDeveloperPageExceptionFilter(); +if (builder.Environment.IsDevelopment()) builder.Services.AddDatabaseDeveloperPageExceptionFilter(); builder.Services.AddIdentityCore(options => { diff --git a/Queueify.Web/Queueify.Web.csproj b/Queueify.Web/Queueify.Web.csproj index bc4bc56..68e66ce 100644 --- a/Queueify.Web/Queueify.Web.csproj +++ b/Queueify.Web/Queueify.Web.csproj @@ -8,10 +8,6 @@ true - - - - diff --git a/Queueify.Web/Services/QueueifyStorageExtensions.cs b/Queueify.Web/Services/QueueifyStorageExtensions.cs index 8fe47e8..cd6585a 100644 --- a/Queueify.Web/Services/QueueifyStorageExtensions.cs +++ b/Queueify.Web/Services/QueueifyStorageExtensions.cs @@ -3,10 +3,21 @@ namespace Queueify.Web.Services; public static class QueueifyStorageExtensions { /// - /// The data folder: Queueify:DataDir, or "App_Data" beside the app ("Data" already holds the account - /// database). Holds one folder per user (their ids are GUIDs) plus "keys" and "tessdata". The per-user stores and - /// the Data Protection key ring are registered by AddQueueifySync. + /// The data folder: Queueify:DataDir, or "App_Data" beside the app. Holds one folder per user (their ids are + /// GUIDs) plus "keys", "tessdata", the account database and the owner marker. The per-user stores and the Data + /// Protection key ring are registered by AddQueueifySync. Backing up this one folder backs up everything. /// public static string DataRootOf(IConfiguration config, IHostEnvironment env) => Path.GetFullPath(config["Queueify:DataDir"] is { Length: > 0 } root ? root : Path.Combine(env.ContentRootPath, "App_Data")); + + /// + /// The account database: ConnectionStrings:DefaultConnection when an administrator sets one, otherwise + /// identity.db in the data folder, created on first run (nothing ships with the app). + /// + public static string AccountConnectionString(IConfiguration config, IHostEnvironment env) + { + if (config.GetConnectionString("DefaultConnection") is { Length: > 0 } configured) return configured; + var root = Directory.CreateDirectory(DataRootOf(config, env)).FullName; + return $"DataSource={Path.Combine(root, "identity.db")}"; + } } diff --git a/Queueify.Web/appsettings.json b/Queueify.Web/appsettings.json index f5d9bae..10f68b8 100644 --- a/Queueify.Web/appsettings.json +++ b/Queueify.Web/appsettings.json @@ -1,7 +1,4 @@ { - "ConnectionStrings": { - "DefaultConnection": "DataSource=Data/app.db;Cache=Shared" - }, "Logging": { "LogLevel": { "Default": "Information", diff --git a/README.md b/README.md index e800725..efd2fb6 100644 --- a/README.md +++ b/README.md @@ -100,7 +100,8 @@ dotnet run --project Queueify.Web # then open the address it prints The first account that registers owns the server; after that registration is closed unless the server's configuration sets `Queueify:AllowRegistration` to `true`. Data lives under `Queueify:DataDir` -(default `./data`, one folder per user). Design notes are in [docs/WEB_DESIGN.md](docs/WEB_DESIGN.md), +(default `App_Data` beside the app: one folder per user, the Data Protection keys and `identity.db`, the account +database, created on first run; back the whole folder up as one). Design notes are in [docs/WEB_DESIGN.md](docs/WEB_DESIGN.md), the decision in [ADR-0010](docs/adr/0010-web-app-and-shared-queue.md). ## Magazine photos diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 9163f06..125b68e 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -122,7 +122,8 @@ reads its texts while it loads. `Queueify.Web` (Blazor Web App, Interactive Server, [ADR-0010](adr/0010-web-app-and-shared-queue.md)) keeps one folder per user under the data root (`Queueify:DataDir`, default `App_Data`): `queueify.db`, -`settings.json` and `prefs.json`. `UserStores` is the only door to them; with Data Protection (key ring in +`settings.json` and `prefs.json`; the same root holds the account database `identity.db` (created and migrated at start; +nothing ships with the app, `ConnectionStrings:DefaultConnection` can move it). `UserStores` is the only door to them; with Data Protection (key ring in `keys/`) it keeps the two client secrets encrypted in `secrets.dat`, bound to the user, never in `settings.json`. | Piece | Responsibility | diff --git a/docs/TESTING.md b/docs/TESTING.md index c404f0b..f4b87b0 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -57,6 +57,6 @@ folder, keeps its data in local app data (default mode), and a taskbar pin would decisions that would start something (an install) are pure functions tested on their own. - Texts asserted in English run under `Loc.Override("en")` when they contain numbers or dates, so the machine's regional format can't change them. -- Web tests never touch real data: `SyncFactory` points `Queueify:DataDir` and the Identity database at a scratch - folder and gives every test its own user, so tests share one server without seeing each other's data. +- Web tests never touch real data or the source tree: every host (smoke test included) points `Queueify:DataDir` and the Identity database at a scratch + folder (`SyncFactory`, `ScratchHost`) and gives every test its own user, so tests share one server without seeing each other's data. - Could the test pass with a wrong implementation? Flip a comparison mentally; a test should fail. From 4a7adffd6b4858246e19a608e4345618cf209a92 Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:47:47 -0300 Subject: [PATCH 41/66] fix(core): keep sync pages going, one transaction per page, UTC stamps - BacklogStore: schema/WAL work once per file and process, busy timeout, updated_at always written as UTC, ApplyRemoteBatch (one transaction), MergeBackup states BEGIN IMMEDIATE explicitly and is guarded by a test. - ServerSync: a full page keeps the sync going even when nothing on it was new; round limit raised for 50 pages; applies each page in one batch; service ids that are not plain tokens are dropped. - AlbumYear: the single year rule (1000-3000). - Desktop Play and ExternalLinks go through PlayLinks.Only. - Matcher.Normalize uses an ordinal StartsWith. Co-Authored-By: Claude Sonnet 5.5 --- Queueify.Core/Services/AlbumYear.cs | 19 ++ Queueify.Core/Services/BacklogStore.cs | 86 +++++-- Queueify.Core/Services/ExternalLinks.cs | 13 +- Queueify.Core/Services/Matcher.cs | 2 +- Queueify.Core/Services/PlayLinks.cs | 2 +- Queueify.Core/Services/ServerSync.cs | 33 +-- Queueify.Tests/AlbumYearTests.cs | 32 +++ Queueify.Tests/BacklogStoreSafetyTests.cs | 261 ++++++++++++++++++++++ Queueify.Tests/ServerSyncPagingTests.cs | 182 +++++++++++++++ Queueify.Tests/ServerSyncTests.cs | 5 +- Queueify/MainWindow.xaml.cs | 9 +- docs/ARCHITECTURE.md | 3 +- docs/adr/0010-web-app-and-shared-queue.md | 4 +- 13 files changed, 603 insertions(+), 48 deletions(-) create mode 100644 Queueify.Core/Services/AlbumYear.cs create mode 100644 Queueify.Tests/AlbumYearTests.cs create mode 100644 Queueify.Tests/BacklogStoreSafetyTests.cs create mode 100644 Queueify.Tests/ServerSyncPagingTests.cs diff --git a/Queueify.Core/Services/AlbumYear.cs b/Queueify.Core/Services/AlbumYear.cs new file mode 100644 index 0000000..d04915c --- /dev/null +++ b/Queueify.Core/Services/AlbumYear.cs @@ -0,0 +1,19 @@ +namespace Queueify.Services; + +/// +/// Which release years are believed. One rule for the PC app, the sync client, the web server and imports, so a +/// year one front end keeps is never thrown away by another (they would otherwise never converge). +/// +public static class AlbumYear +{ + public const int Min = 1000; + public const int Max = 3000; + + public static bool IsValid(int year) => year is >= Min and <= Max; + + /// + /// The year when it is believed, otherwise null. Takes 64-bit numbers so a value read from a file is + /// bounded before it is narrowed (a huge number must not wrap into range). + /// + public static int? OrNull(long? year) => year is long y && y is >= Min and <= Max ? (int)y : null; +} diff --git a/Queueify.Core/Services/BacklogStore.cs b/Queueify.Core/Services/BacklogStore.cs index a55e0ad..01618a0 100644 --- a/Queueify.Core/Services/BacklogStore.cs +++ b/Queueify.Core/Services/BacklogStore.cs @@ -13,14 +13,41 @@ public sealed class BacklogStore private const string Columns = "id, uid, artist, album, year, source, cover_url, spotify_id, tidal_id, added_at, listened_at, rating, updated_at, dirty, deleted"; + /// How long a writer waits for another one (a sync, an import, a page) before giving up. + private const int BusyTimeoutSeconds = 15; + + // Schema work (and the one-time switch to WAL) runs once per database file and process, not on every + // `new BacklogStore`: the web app builds one per page load, and the work writes, so it would queue behind a sync. + private static readonly object PrepareLock = new(); + private static readonly HashSet Prepared = + new(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); + private readonly string _connectionString; public BacklogStore(string path) { + path = Path.GetFullPath(path); Directory.CreateDirectory(Path.GetDirectoryName(path)!); - _connectionString = new SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString(); + _connectionString = new SqliteConnectionStringBuilder { DataSource = path, Pooling = false, DefaultTimeout = BusyTimeoutSeconds }.ToString(); + lock (PrepareLock) + { + // A file that was deleted (an account removed, a data folder cleared) needs its schema again. + if (Prepared.Contains(path) && File.Exists(path)) return; + Prepare(); + Prepared.Add(path); + } + } + + private void Prepare() + { using var db = Open(); + // Readers no longer block the writer and the other way round; the setting stays in the file. + using (var wal = db.CreateCommand()) + { + wal.CommandText = "PRAGMA journal_mode = WAL"; + wal.ExecuteScalar(); + } Execute(db, """ CREATE TABLE IF NOT EXISTS items ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -50,7 +77,7 @@ rating REAL NOT NULL DEFAULT -1 if (!existing.Contains("dirty")) Execute(db, "ALTER TABLE items ADD COLUMN dirty INTEGER NOT NULL DEFAULT 1"); if (!existing.Contains("deleted")) Execute(db, "ALTER TABLE items ADD COLUMN deleted INTEGER NOT NULL DEFAULT 0"); Execute(db, "UPDATE items SET uid = lower(hex(randomblob(16))) WHERE uid IS NULL"); - Execute(db, $"UPDATE items SET updated_at = '{Stamp(DateTime.UtcNow)}' WHERE updated_at IS NULL"); + Execute(db, $"UPDATE items SET updated_at = '{StampUtc(DateTime.UtcNow)}' WHERE updated_at IS NULL"); Execute(db, "CREATE UNIQUE INDEX IF NOT EXISTS items_uid ON items(uid)"); } @@ -114,18 +141,37 @@ public void Restore(BacklogItem item) public void ApplyRemote(BacklogItem remote) { using var db = Open(); + ApplyRemote(db, null, remote); + } + + /// + /// for a whole page of a sync in one transaction: one connection and one + /// commit instead of one of each per album, and a page is applied completely or not at all. Returns how many + /// albums changed here (those that were older or missing, not the ones this PC already had in a newer version). + /// + public int ApplyRemoteBatch(IEnumerable remote) + { + int changed = 0; + using var db = Open(); + using var tx = db.BeginTransaction(deferred: false); + foreach (var item in remote) changed += ApplyRemote(db, tx, item); + tx.Commit(); + return changed; + } + + private static int ApplyRemote(SqliteConnection db, SqliteTransaction? tx, BacklogItem remote) + { + using var cmd = db.CreateCommand(); + cmd.Transaction = tx; if (remote.Deleted) { - using var del = db.CreateCommand(); - del.CommandText = "DELETE FROM items WHERE uid = $uid AND updated_at < $updated"; - del.Parameters.AddWithValue("$uid", remote.Uid); - del.Parameters.AddWithValue("$updated", Stamp(remote.UpdatedAt)); - del.ExecuteNonQuery(); - return; + cmd.CommandText = "DELETE FROM items WHERE uid = $uid AND updated_at < $updated"; + cmd.Parameters.AddWithValue("$uid", remote.Uid); + cmd.Parameters.AddWithValue("$updated", StampUtc(remote.UpdatedAt)); + return cmd.ExecuteNonQuery(); } remote.Dirty = false; - using var cmd = db.CreateCommand(); cmd.CommandText = $""" INSERT INTO items ({Columns[4..]}) VALUES ($uid, $artist, $album, $year, $source, $cover, $spotify, $tidal, $added, $listened, $rating, $updated, $dirty, $deleted) @@ -136,7 +182,7 @@ ON CONFLICT(uid) DO UPDATE SET artist = excluded.artist, album = excluded.album, WHERE items.updated_at < excluded.updated_at """; Bind(cmd, remote); - cmd.ExecuteNonQuery(); + return cmd.ExecuteNonQuery(); } /// @@ -149,7 +195,9 @@ WHERE items.updated_at < excluded.updated_at { int added = 0, here = 0; using var db = Open(); - using var tx = db.BeginTransaction(); + // IMMEDIATE: the write lock is taken before anything is read. A deferred transaction that reads first and writes + // later is refused at once (no waiting) if a sync wrote in between. + using var tx = db.BeginTransaction(deferred: false); foreach (var item in items) { if (item.Uid.Length == 0) item.Uid = Guid.NewGuid().ToString("N"); @@ -165,7 +213,7 @@ WHERE items.updated_at < excluded.updated_at if (r.Read()) { here++; - if (r.GetInt64(0) != 0 || ParseDate(r.GetString(1)).ToUniversalTime() >= item.UpdatedAt.ToUniversalTime()) continue; + if (r.GetInt64(0) != 0 || ParseDate(r.GetString(1)).ToUniversalTime() >= AsUtc(item.UpdatedAt)) continue; using var update = db.CreateCommand(); update.Transaction = tx; update.CommandText = """ @@ -207,7 +255,7 @@ public void MarkUploaded(BacklogItem item) DELETE FROM items WHERE uid = $uid AND deleted = 1 AND dirty = 0; """; cmd.Parameters.AddWithValue("$uid", item.Uid); - cmd.Parameters.AddWithValue("$updated", Stamp(item.UpdatedAt)); + cmd.Parameters.AddWithValue("$updated", StampUtc(item.UpdatedAt)); cmd.ExecuteNonQuery(); } @@ -298,7 +346,7 @@ private static void Bind(SqliteCommand cmd, BacklogItem item) cmd.Parameters.AddWithValue("$added", Stamp(item.AddedAt)); cmd.Parameters.AddWithValue("$listened", item.ListenedAt is DateTime l ? Stamp(l) : DBNull.Value); cmd.Parameters.AddWithValue("$rating", item.Rating); - cmd.Parameters.AddWithValue("$updated", Stamp(item.UpdatedAt)); + cmd.Parameters.AddWithValue("$updated", StampUtc(item.UpdatedAt)); cmd.Parameters.AddWithValue("$dirty", item.Dirty ? 1 : 0); cmd.Parameters.AddWithValue("$deleted", item.Deleted ? 1 : 0); } @@ -309,6 +357,16 @@ private static void Bind(SqliteCommand cmd, BacklogItem item) /// private static string Stamp(DateTime d) => d.ToString("O", CultureInfo.InvariantCulture); + /// + /// updated_at is compared and matched as text, so it is always written as UTC ("Z"): a local time would + /// carry an offset and never equal what a query reads back, leaving the album dirty for ever. A time with no + /// zone is taken as UTC, like everywhere on the wire. + /// + private static string StampUtc(DateTime d) => Stamp(AsUtc(d)); + + private static DateTime AsUtc(DateTime d) => + d.Kind == DateTimeKind.Unspecified ? DateTime.SpecifyKind(d, DateTimeKind.Utc) : d.ToUniversalTime(); + private static DateTime ParseDate(string s) => DateTime.Parse(s, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); } diff --git a/Queueify.Core/Services/ExternalLinks.cs b/Queueify.Core/Services/ExternalLinks.cs index 87c5fad..276fe65 100644 --- a/Queueify.Core/Services/ExternalLinks.cs +++ b/Queueify.Core/Services/ExternalLinks.cs @@ -1,17 +1,16 @@ using System.Diagnostics; -using Queueify.Models; using Windows.System; namespace Queueify.Services; -/// Opens albums in the installed Spotify / Tidal app, falling back to the web player. +/// +/// Opens albums in the installed Spotify / Tidal app, falling back to the web player. It takes a +/// , which builds only from a plain id: ids can arrive from a sync +/// server, and nothing else may reach the OS protocol launcher. +/// public static class ExternalLinks { - public static Task OpenSpotifyAsync(string id) => OpenAsync(PlayLinks.For(MusicService.Spotify, id)); - - public static Task OpenTidalAsync(string id) => OpenAsync(PlayLinks.For(MusicService.Tidal, id)); - - private static async Task OpenAsync(PlayLink link) + public static async Task OpenAsync(PlayLink link) { var app = new Uri(link.App); try diff --git a/Queueify.Core/Services/Matcher.cs b/Queueify.Core/Services/Matcher.cs index 36bf500..7b6ce05 100644 --- a/Queueify.Core/Services/Matcher.cs +++ b/Queueify.Core/Services/Matcher.cs @@ -118,7 +118,7 @@ public static string Normalize(string s) } s = NonAlphanumeric().Replace(sb.ToString(), " ").Trim(); - if (s.StartsWith("the ")) s = s[4..]; + if (s.StartsWith("the ", StringComparison.Ordinal)) s = s[4..]; return s; } diff --git a/Queueify.Core/Services/PlayLinks.cs b/Queueify.Core/Services/PlayLinks.cs index 19c180d..496df9e 100644 --- a/Queueify.Core/Services/PlayLinks.cs +++ b/Queueify.Core/Services/PlayLinks.cs @@ -33,6 +33,6 @@ public static PlayLink For(MusicService service, string id) => service == MusicS return IsPlainId(id) ? For(service, id!) : null; } - private static bool IsPlainId(string? id) => + public static bool IsPlainId(string? id) => !string.IsNullOrEmpty(id) && id.Length <= 64 && id.All(char.IsAsciiLetterOrDigit); } diff --git a/Queueify.Core/Services/ServerSync.cs b/Queueify.Core/Services/ServerSync.cs index bf0f16c..1abd807 100644 --- a/Queueify.Core/Services/ServerSync.cs +++ b/Queueify.Core/Services/ServerSync.cs @@ -33,15 +33,16 @@ public sealed class ServerSync(HttpClient http, int maxBatch = ServerSync.MaxBat /// Largest answer read (about 50,000 albums); a bigger one is not a Queueify server. public const long MaxAnswerBytes = 16L * 1024 * 1024; - private const int MaxExtraRounds = 20; + // A full queue (50,000 albums) arrives in 50 pages, so the limit that stops a server that never ends must be above that. + private const int MaxExtraRounds = 60; private const int MaxUidLength = 64; private static readonly TimeSpan FutureTolerance = TimeSpan.FromMinutes(5); /// The client for a web server: it never follows a redirect, so the token can't be handed to another host. public static HttpClient CreateClient() { - var http = new HttpClient(new SocketsHttpHandler { AllowAutoRedirect = false }) { Timeout = TimeSpan.FromSeconds(30) }; - http.DefaultRequestHeaders.UserAgent.ParseAdd("Queueify/1.0"); + var http = new HttpClient(new SocketsHttpHandler { AllowAutoRedirect = false, PooledConnectionLifetime = TimeSpan.FromMinutes(5) }) { Timeout = TimeSpan.FromSeconds(30) }; + http.DefaultRequestHeaders.UserAgent.ParseAdd("Queueify/" + AppInfo.Version); return http; } @@ -82,17 +83,15 @@ public async Task SyncAsync(BacklogStore store, AppSettings s, Cance settingsToSend = null; } - int applied = 0; + // One transaction per page. The store keeps the newer of the two versions of each album, and tells how + // many changed here, so rows already known (the overlap, or ones just sent) don't count. + var remotes = new List(answer.Albums.Count); foreach (var wire in answer.Albums) { if (wire.Uid is not { Length: > 0 and <= MaxUidLength }) continue; - var remote = ToItem(wire, now); - var local = store.FindByUid(remote.Uid); - if (local == null && remote.Deleted) continue; // deleted before this PC saw it - if (local != null && local.UpdatedAt >= remote.UpdatedAt) continue; // same or newer here - store.ApplyRemote(remote); - applied++; + remotes.Add(ToItem(wire, now)); } + int applied = store.ApplyRemoteBatch(remotes); downloaded += applied; if (answer.Settings is { } shared) @@ -105,11 +104,14 @@ public async Task SyncAsync(BacklogStore store, AppSettings s, Cance } } + // The server answers at most MaxBatch albums and then says where it stopped, so a full page that moved the + // position means "maybe more" even when nothing on it was new to this PC (deletions it never had, say). + bool fullPage = answer.Albums.Count >= MaxBatch && answer.ServerTime > (since ?? DateTime.MinValue); since = answer.ServerTime; s.WebLastServerTime = since; // Rows already known (the overlap, or ones just sent) don't count, or an idle sync would never end. - bool more = sent < dirty.Count || applied > 0; + bool more = sent < dirty.Count || applied > 0 || fullPage; if (!more && firstConnection && !serverHadSettings && s.SharedSettingsUpdatedAt == null && (s.SpotifyConfigured || s.TidalConfigured)) { @@ -214,11 +216,11 @@ private static void TakeSettings(AppSettings s, SyncSettings shared, DateTime no Uid = a.Uid, Artist = Cut(a.Artist) ?? "", Album = Cut(a.Album) ?? "", - Year = a.Year is >= 1000 and <= 3000 ? a.Year : null, + Year = AlbumYear.OrNull(a.Year), Source = Cut(a.Source), CoverUrl = Cut(a.CoverUrl), - SpotifyId = Cut(a.SpotifyId), - TidalId = Cut(a.TidalId), + SpotifyId = PlainId(a.SpotifyId), + TidalId = PlainId(a.TidalId), AddedAt = Utc(a.AddedAt).ToLocalTime(), ListenedAt = a.ListenedAt is DateTime l ? Utc(l).ToLocalTime() : null, Rating = double.IsNaN(a.Rating) || a.Rating < 0 ? -1 : Math.Min(a.Rating, 5), @@ -235,6 +237,9 @@ private static DateTime Past(DateTime t, DateTime now) var utc = Utc(t); return utc > now + FutureTolerance ? now : utc; // one fixed "now" per sync, so the same row isn't "newer" every round } + /// A service id is kept only when it is a plain token (it ends up in a link the OS opens), as the server checks uids. + private static string? PlainId(string? id) => PlayLinks.IsPlainId(id) ? id : null; + private static string? Cut(string? text) => text is { Length: > MaxTextLength } ? text[..MaxTextLength] : text; diff --git a/Queueify.Tests/AlbumYearTests.cs b/Queueify.Tests/AlbumYearTests.cs new file mode 100644 index 0000000..87a414a --- /dev/null +++ b/Queueify.Tests/AlbumYearTests.cs @@ -0,0 +1,32 @@ +using Queueify.Services; + +namespace Queueify.Tests; + +/// The one rule for which release years are believed, shared by the PC app, the sync and the web server. +public class AlbumYearTests +{ + [Theory] + [InlineData(1000, true)] + [InlineData(1973, true)] + [InlineData(3000, true)] + [InlineData(999, false)] + [InlineData(3001, false)] + [InlineData(0, false)] + [InlineData(-1973, false)] + [InlineData(int.MaxValue, false)] + public void Years_between_1000_and_3000_are_believed(int year, bool believed) + { + Assert.Equal(believed, AlbumYear.IsValid(year)); + Assert.Equal(believed ? year : (int?)null, AlbumYear.OrNull(year)); + } + + [Fact] + public void No_year_stays_no_year() => Assert.Null(AlbumYear.OrNull((int?)null)); + + [Fact] + public void A_long_from_a_database_is_bounded_before_it_is_narrowed() + { + Assert.Equal(1983, AlbumYear.OrNull(1983L)); + Assert.Null(AlbumYear.OrNull(4_294_969_279L)); // would wrap to 1983 as an int + } +} diff --git a/Queueify.Tests/BacklogStoreSafetyTests.cs b/Queueify.Tests/BacklogStoreSafetyTests.cs new file mode 100644 index 0000000..b31ab66 --- /dev/null +++ b/Queueify.Tests/BacklogStoreSafetyTests.cs @@ -0,0 +1,261 @@ +using Microsoft.Data.Sqlite; +using Queueify.Models; +using Queueify.Services; + +namespace Queueify.Tests; + +/// How behaves with several writers (sync, imports, web pages) and with times that are not UTC. +public sealed class BacklogStoreSafetyTests : IDisposable +{ + private readonly string _dir = Path.Combine(Path.GetTempPath(), "queueify-tests", Guid.NewGuid().ToString("N")); + private string DbPath => Path.Combine(_dir, "queueify.db"); + + public void Dispose() + { + SqliteConnection.ClearAllPools(); + if (Directory.Exists(_dir)) Directory.Delete(_dir, true); + } + + private static readonly DateTime Old = new(2026, 1, 2, 0, 0, 0, DateTimeKind.Utc); + private static readonly DateTime New = new(2026, 6, 1, 0, 0, 0, DateTimeKind.Utc); + + private static BacklogItem Item(string uid, string album, DateTime updated, bool deleted = false) => new() + { + Uid = uid, Artist = "A", Album = album, AddedAt = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc), + UpdatedAt = updated, Deleted = deleted, + }; + + private SqliteConnection Raw() + { + var db = new SqliteConnection($"Data Source={DbPath};Pooling=False"); + db.Open(); + return db; + } + + private static void Run(SqliteConnection db, string sql) + { + using var cmd = db.CreateCommand(); + cmd.CommandText = sql; + cmd.ExecuteNonQuery(); + } + + // ───────────── one-time schema work, WAL ───────────── + + [Fact] + public void The_database_uses_a_write_ahead_log_so_readers_and_a_writer_do_not_block_each_other() + { + _ = new BacklogStore(DbPath); + + using var db = Raw(); + using var cmd = db.CreateCommand(); + cmd.CommandText = "PRAGMA journal_mode"; + Assert.Equal("wal", cmd.ExecuteScalar()); + } + + [Fact] + public void Opening_a_known_database_again_does_no_schema_work_so_it_never_waits_for_a_writer() + { + _ = new BacklogStore(DbPath); + using var writer = Raw(); + Run(writer, "BEGIN IMMEDIATE"); // another sync or import holds the write lock + + var started = DateTime.UtcNow; + var again = new BacklogStore(DbPath); + var shown = again.LoadAll(); // reads are not blocked in WAL mode + + Assert.Empty(shown); + Assert.True(DateTime.UtcNow - started < TimeSpan.FromSeconds(3)); + } + + [Fact] + public void A_database_deleted_and_created_again_in_the_same_process_gets_its_schema_again() + { + var first = new BacklogStore(DbPath); + first.Insert(Item("u1", "One", Old)); + SqliteConnection.ClearAllPools(); + File.Delete(DbPath); + foreach (var extra in Directory.GetFiles(_dir, "queueify.db-*")) File.Delete(extra); + + var second = new BacklogStore(DbPath); + + Assert.Empty(second.LoadAll()); + second.Insert(Item("u2", "Two", Old)); + Assert.Single(second.LoadAll()); + } + + // ───────────── times are stored as UTC ───────────── + + [Theory] + [InlineData(DateTimeKind.Local)] + [InlineData(DateTimeKind.Unspecified)] + public void A_backup_album_with_a_non_UTC_edit_time_is_not_dirty_for_ever_once_uploaded(DateTimeKind kind) + { + var store = new BacklogStore(DbPath); + var edited = kind == DateTimeKind.Local ? Old.ToLocalTime() : DateTime.SpecifyKind(Old, DateTimeKind.Unspecified); + + store.MergeBackup([Item("u1", "One", edited)]); + var stored = store.FindByUid("u1")!; + store.MarkUploaded(stored); + + Assert.Equal(Old, stored.UpdatedAt); + Assert.False(store.FindByUid("u1")!.Dirty); + } + + [Fact] + public void A_remote_row_with_a_local_kind_time_compares_by_the_instant() + { + var store = new BacklogStore(DbPath); + store.MergeBackup([Item("u1", "Old title", Old)]); + + store.ApplyRemote(Item("u1", "New title", New.ToLocalTime())); + + Assert.Equal("New title", store.FindByUid("u1")!.Album); + Assert.Equal(New, store.FindByUid("u1")!.UpdatedAt); + } + + [Fact] + public void A_merge_compares_a_local_kind_backup_time_by_the_instant() + { + var store = new BacklogStore(DbPath); + store.MergeBackup([Item("u1", "Current", New)]); + + store.MergeBackup([Item("u1", "Older backup", Old.ToLocalTime())]); + + Assert.Equal("Current", store.FindByUid("u1")!.Album); + } + + // ───────────── MergeBackup ───────────── + + [Fact] + public void MergeBackup_gives_an_album_without_an_id_a_new_one() + { + var store = new BacklogStore(DbPath); + var noId = Item("", "No id", Old); + + store.MergeBackup([noId]); + + Assert.Equal(32, noId.Uid.Length); + Assert.Equal("No id", Assert.Single(store.LoadAll()).Album); + } + + [Fact] + public void MergeBackup_overwrites_every_field_of_an_older_album_and_queues_it_for_upload() + { + var store = new BacklogStore(DbPath); + store.MergeBackup([Item("u1", "Old", Old)]); + store.MarkUploaded(store.FindByUid("u1")!); + var newer = new BacklogItem + { + Uid = "u1", Artist = "Other artist", Album = "New", Year = 1999, Source = "Mag", CoverUrl = "https://c/x.jpg", + SpotifyId = "sp1", TidalId = "td1", AddedAt = new DateTime(2025, 5, 5, 0, 0, 0, DateTimeKind.Utc), + ListenedAt = new DateTime(2026, 2, 2, 0, 0, 0, DateTimeKind.Utc), Rating = 4, UpdatedAt = New, Deleted = true, + }; + + store.MergeBackup([newer]); + + var s = store.FindByUid("u1")!; + Assert.Equal(("Other artist", "New", 1999, "Mag"), (s.Artist, s.Album, s.Year, s.Source)); + Assert.Equal(("https://c/x.jpg", "sp1", "td1"), (s.CoverUrl, s.SpotifyId, s.TidalId)); + Assert.Equal(new DateTime(2025, 5, 5, 0, 0, 0, DateTimeKind.Utc), s.AddedAt.ToUniversalTime()); + Assert.Equal(new DateTime(2026, 2, 2, 0, 0, 0, DateTimeKind.Utc), s.ListenedAt!.Value.ToUniversalTime()); + Assert.Equal(4, s.Rating); + Assert.Equal(New, s.UpdatedAt); + Assert.True(s.Dirty); + Assert.False(s.Deleted); // a backup never brings a deletion with it + } + + [Fact] + public void MergeBackup_counts_an_id_that_appears_twice_once_as_added_and_once_as_already_here() + { + var store = new BacklogStore(DbPath); + + var result = store.MergeBackup([Item("u1", "First", Old), Item("u1", "Second", New)]); + + Assert.Equal((1, 1), result); + Assert.Equal("Second", store.FindByUid("u1")!.Album); + } + + [Fact] + public void MergeBackup_that_fails_halfway_changes_nothing() + { + var store = new BacklogStore(DbPath); + IEnumerable Broken() + { + yield return Item("u1", "One", Old); + throw new InvalidOperationException("boom"); + } + + Assert.Throws(() => store.MergeBackup(Broken())); + + Assert.Empty(store.LoadAll()); + } + + [Fact] + public async Task MergeBackup_takes_the_write_lock_first_so_a_sync_writing_meanwhile_cannot_make_it_fail() + { + var store = new BacklogStore(DbPath); + store.MergeBackup([Item("known", "Known", New)]); + + Task? sync = null; + IEnumerable Slow() + { + yield return Item("known", "Older copy", Old); // looked up, then skipped: a read before any write + // A sync commits a write now. Had MergeBackup not locked the file yet, its read is out of date and its next + // write is refused at once (SQLITE_BUSY_SNAPSHOT: waiting cannot help). With the lock taken first, the + // sync waits for MergeBackup instead. + sync = Task.Run(() => new BacklogStore(DbPath).Insert(Item("other", "Other", New))); + sync.Wait(TimeSpan.FromMilliseconds(600)); + yield return Item("fresh", "Fresh", New); + } + + var result = await Task.Run(() => store.MergeBackup(Slow())); + + Assert.Equal((1, 1), result); + await sync!; + Assert.Equal(["Fresh", "Known", "Other"], store.LoadAll().Select(i => i.Album).Order()); + } + + // ───────────── ApplyRemoteBatch ───────────── + + [Fact] + public void ApplyRemoteBatch_adds_updates_and_removes_in_one_go_and_counts_what_changed() + { + var store = new BacklogStore(DbPath); + store.MergeBackup([Item("update", "Old", Old), Item("gone", "Gone", Old), Item("newer here", "Mine", New)]); + + var applied = store.ApplyRemoteBatch( + [ + Item("update", "Updated", New), + Item("gone", "Gone", New, deleted: true), + Item("newer here", "Theirs", Old), // older than ours: kept out + Item("added", "Added", New), + Item("never seen", "Never seen", New, deleted: true), + ]); + + Assert.Equal(3, applied); + Assert.Equal(["Added", "Mine", "Updated"], store.LoadAll().Select(i => i.Album).Order()); + Assert.False(store.FindByUid("added")!.Dirty); + } + + [Fact] + public void ApplyRemoteBatch_that_fails_halfway_applies_none_of_it() + { + var store = new BacklogStore(DbPath); + IEnumerable Broken() + { + yield return Item("u1", "One", New); + yield return Item("u2", "Two", New); + throw new InvalidOperationException("boom"); + } + + Assert.Throws(() => store.ApplyRemoteBatch(Broken())); + + Assert.Empty(store.LoadAll()); + } + + [Fact] + public void ApplyRemoteBatch_of_nothing_is_fine() + { + Assert.Equal(0, new BacklogStore(DbPath).ApplyRemoteBatch([])); + } +} diff --git a/Queueify.Tests/ServerSyncPagingTests.cs b/Queueify.Tests/ServerSyncPagingTests.cs new file mode 100644 index 0000000..6e9649a --- /dev/null +++ b/Queueify.Tests/ServerSyncPagingTests.cs @@ -0,0 +1,182 @@ +using System.Net; +using System.Text; +using System.Text.Json; +using Microsoft.Data.Sqlite; +using Queueify.Models; +using Queueify.Services; + +namespace Queueify.Tests; + +/// Paging, validation and the size limit of , against scripted answers. +public sealed class ServerSyncPagingTests : IDisposable +{ + private const string Token = "qw_SECRET-TOKEN-123"; + private const string Url = "https://queue.example.com"; + private static readonly DateTime T0 = new(2026, 10, 1, 12, 0, 0, DateTimeKind.Utc); + private static readonly DateTime Edited = new(2026, 10, 10, 0, 0, 0, DateTimeKind.Utc); + + private readonly string _dir = Path.Combine(Path.GetTempPath(), "queueify-tests", Guid.NewGuid().ToString("N")); + private BacklogStore NewStore() => new(Path.Combine(_dir, Guid.NewGuid().ToString("N") + ".db")); + private static AppSettings Connected() => new() { WebServerUrl = Url, WebToken = Token }; + + public void Dispose() + { + SqliteConnection.ClearAllPools(); + if (Directory.Exists(_dir)) Directory.Delete(_dir, true); + } + + private sealed class Scripted(Func answer) : HttpMessageHandler + { + public readonly List Requests = []; + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + var body = await request.Content!.ReadAsStringAsync(ct); + var req = JsonSerializer.Deserialize(body, SyncJson.Default.SyncRequest)!; + Requests.Add(req); + return answer(Requests.Count, req); + } + } + + private static HttpResponseMessage Ok(DateTime serverTime, List albums) => new(HttpStatusCode.OK) + { + Content = new StringContent(JsonSerializer.Serialize(new SyncResponse(serverTime, albums, null), SyncJson.Default.SyncResponse), + Encoding.UTF8, "application/json"), + }; + + private static SyncAlbum Wire(string uid, string album = "Album", int? year = 1973, string? spotify = null, string? tidal = null, + bool deleted = false, DateTime? updated = null) => + new(uid, "Spinetta", album, year, null, null, spotify, tidal, Edited, null, -1, updated ?? Edited, deleted); + + private static List Tombstones(int count) => + Enumerable.Range(0, count).Select(i => Wire("gone" + i, deleted: true)).ToList(); + + // ───────────── a full page means "maybe more" ───────────── + + [Fact] + public async Task A_full_page_with_nothing_new_on_it_does_not_end_the_sync() + { + // A new PC meets 1000 old deletions first: nothing to apply, but the real albums are on the next page. + var server = new Scripted((call, _) => call switch + { + 1 => Ok(T0.AddSeconds(1), Tombstones(ServerSync.MaxBatch)), + 2 => Ok(T0.AddSeconds(2), [Wire("real", "The real album")]), + _ => Ok(T0.AddSeconds(3), []), + }); + var store = NewStore(); + + var result = await new ServerSync(new HttpClient(server)).SyncAsync(store, Connected(), CancellationToken.None); + + Assert.Equal("The real album", Assert.Single(store.LoadAll()).Album); + Assert.Equal(1, result.Downloaded); + Assert.Equal(T0.AddSeconds(2), server.Requests[2].Since); + } + + [Fact] + public async Task A_full_page_that_does_not_move_the_position_ends_the_sync_instead_of_looping() + { + var server = new Scripted((_, _) => Ok(T0.AddSeconds(1), Tombstones(ServerSync.MaxBatch))); + var settings = Connected(); + + await new ServerSync(new HttpClient(server)).SyncAsync(NewStore(), settings, CancellationToken.None); + + Assert.Equal(2, server.Requests.Count); + Assert.Equal(T0.AddSeconds(1), settings.WebLastServerTime); + } + + [Fact] + public async Task A_big_first_download_of_fifty_thousand_albums_is_not_cut_short_by_the_round_limit() + { + // 50 full pages is what the server's per-user quota allows. + var server = new Scripted((call, _) => call <= 50 + ? Ok(T0.AddSeconds(call), Tombstones(ServerSync.MaxBatch)) + : Ok(T0.AddSeconds(51), [])); + + await new ServerSync(new HttpClient(server)).SyncAsync(NewStore(), Connected(), CancellationToken.None); + + Assert.Equal(51, server.Requests.Count); + } + + [Fact] + public async Task By_default_a_request_carries_at_most_1000_albums() + { + var server = new Scripted((call, _) => Ok(T0.AddSeconds(call), [])); + var store = NewStore(); + foreach (var uid in Enumerable.Range(0, 1001)) + store.Insert(new BacklogItem { Uid = "u" + uid, Artist = "A", Album = "B", AddedAt = DateTime.Now }); + + await new ServerSync(new HttpClient(server)).SyncAsync(store, Connected(), CancellationToken.None); + + Assert.Equal([1000, 1], server.Requests.Select(r => r.Albums.Count)); + } + + // ───────────── what is stored from an answer ───────────── + + [Theory] + [InlineData(999, null)] + [InlineData(1000, 1000)] + [InlineData(2026, 2026)] + [InlineData(3000, 3000)] + [InlineData(3001, null)] + [InlineData(0, null)] + [InlineData(-5, null)] + public async Task A_year_outside_the_one_shared_rule_is_dropped(int year, int? kept) + { + var server = new Scripted((_, _) => Ok(T0, [Wire("y", year: year)])); + var store = NewStore(); + + await new ServerSync(new HttpClient(server)).SyncAsync(store, Connected(), CancellationToken.None); + + Assert.Equal(kept, store.FindByUid("y")!.Year); + } + + [Fact] + public async Task A_service_id_that_is_not_a_plain_token_is_not_stored() + { + var server = new Scripted((_, _) => Ok(T0, + [ + Wire("bad", spotify: "a b/../c", tidal: new string('9', 65)), + Wire("good", spotify: "4aawyAB9vmqN3uQ7FjRGTy", tidal: "12345"), + ])); + var store = NewStore(); + + await new ServerSync(new HttpClient(server)).SyncAsync(store, Connected(), CancellationToken.None); + + var bad = store.FindByUid("bad")!; + Assert.Null(bad.SpotifyId); + Assert.Null(bad.TidalId); + Assert.Equal(("4aawyAB9vmqN3uQ7FjRGTy", "12345"), (store.FindByUid("good")!.SpotifyId, store.FindByUid("good")!.TidalId)); + } + + // ───────────── the answer size limit ───────────── + + private sealed class EndlessContent(long bytes) : HttpContent + { + protected override async Task SerializeToStreamAsync(Stream stream, TransportContext? context) + { + var chunk = new byte[64 * 1024]; + Array.Fill(chunk, (byte)' '); + for (long sent = 0; sent < bytes; sent += chunk.Length) await stream.WriteAsync(chunk); + } + + protected override bool TryComputeLength(out long length) + { + length = 0; + return false; // chunked: no Content-Length to check up front + } + } + + [Fact] + public async Task An_answer_that_grows_past_the_limit_without_announcing_its_size_is_refused() + { + var server = new Scripted((_, _) => new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new EndlessContent(ServerSync.MaxAnswerBytes + 1024 * 1024), + }); + + var ex = await Assert.ThrowsAsync(() => + new ServerSync(new HttpClient(server)).SyncAsync(NewStore(), Connected(), CancellationToken.None)); + + Assert.Equal(Loc.T("webSync.err.bad_reply"), ex.Message); + } +} diff --git a/Queueify.Tests/ServerSyncTests.cs b/Queueify.Tests/ServerSyncTests.cs index 5fe634c..19f9fa8 100644 --- a/Queueify.Tests/ServerSyncTests.cs +++ b/Queueify.Tests/ServerSyncTests.cs @@ -157,7 +157,9 @@ public async Task Downloaded_text_is_cut_the_uid_checked_and_the_year_bounded() var got = Assert.Single(store.LoadAll()); Assert.Equal("ok1", got.Uid); - Assert.All(new[] { got.Artist, got.Album, got.Source!, got.CoverUrl!, got.SpotifyId!, got.TidalId! }, x => Assert.Equal(500, x.Length)); + Assert.All(new[] { got.Artist, got.Album, got.Source!, got.CoverUrl! }, x => Assert.Equal(500, x.Length)); + Assert.Null(got.SpotifyId); // a service id that is not a plain token is not kept + Assert.Null(got.TidalId); Assert.Null(got.Year); Assert.Equal(5, got.Rating); } @@ -275,7 +277,6 @@ public async Task An_oversized_answer_is_refused_without_reading_it() var ex = await Assert.ThrowsAsync(() => Client(server).SyncAsync(NewStore(), Connected(), CancellationToken.None)); Assert.Equal(Loc.T("webSync.err.bad_reply"), ex.Message); - Assert.True(ServerSync.MaxAnswerBytes <= 16 * 1024 * 1024); } [Fact] diff --git a/Queueify/MainWindow.xaml.cs b/Queueify/MainWindow.xaml.cs index 70d44ed..cc968a9 100644 --- a/Queueify/MainWindow.xaml.cs +++ b/Queueify/MainWindow.xaml.cs @@ -672,12 +672,9 @@ private async void OnItemDoubleTapped(object sender, DoubleTappedRoutedEventArgs } private static Task PlayAsync(BacklogItem item, MusicService? service = null) => - (service ?? item.PlayService) switch - { - MusicService.Spotify when item.SpotifyId != null => ExternalLinks.OpenSpotifyAsync(item.SpotifyId), - MusicService.Tidal when item.TidalId != null => ExternalLinks.OpenTidalAsync(item.TidalId), - _ => Task.CompletedTask, - }; + (service ?? item.PlayService) is { } which && PlayLinks.Only(item, which) is { } link + ? ExternalLinks.OpenAsync(link) + : Task.CompletedTask; private void OnToggleListened(object sender, RoutedEventArgs e) { diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 9163f06..317919d 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -44,7 +44,8 @@ flowchart LR | Service | Responsibility | | --- | --- | -| `BacklogStore` | SQLite queue. Rows carry a stable `uid`, `updated_at`, `dirty` and soft `deleted`, for sync. | +| `BacklogStore` | SQLite queue. Rows carry a stable `uid`, `updated_at` (always UTC), `dirty` and soft `deleted`, for sync. Schema work and the switch to WAL run once per database file and process; a sync page is applied in one transaction (`ApplyRemoteBatch`) and `MergeBackup` takes the write lock first. | +| `AlbumYear` | The one rule for which release years are believed (1000-3000), used by the PC app, the sync client and the web server. | | `Matcher` | Splits a typed line into text and year, merges Spotify and Tidal results, scores them. | | `SpotifyCatalog`, `TidalCatalog` | Album search with the Client Credentials flow; tokens cached per ID and secret. | | `CloudSync` | Firestore REST: uploads dirty rows, downloads rows newer than the last server time, shared settings. | diff --git a/docs/adr/0010-web-app-and-shared-queue.md b/docs/adr/0010-web-app-and-shared-queue.md index 14d26c7..e622ed3 100644 --- a/docs/adr/0010-web-app-and-shared-queue.md +++ b/docs/adr/0010-web-app-and-shared-queue.md @@ -46,8 +46,8 @@ SHA-256 hashes, revocable, per user. The text a PC is given is `queueify-web| Date: Wed, 14 Oct 2026 22:48:27 -0300 Subject: [PATCH 42/66] fix(web): deleting the last account no longer reopens registration An owner-exists marker in the data folder remembers that the first account was made; servers that ran before it get the marker the first time the gate is asked. Co-Authored-By: Claude Sonnet 5.5 --- Queueify.Web.Tests/WebAppTests.cs | 31 +++++++++++++++++++++ Queueify.Web/Services/RegistrationGate.cs | 34 +++++++++++++++++++---- SECURITY.md | 2 +- 3 files changed, 61 insertions(+), 6 deletions(-) diff --git a/Queueify.Web.Tests/WebAppTests.cs b/Queueify.Web.Tests/WebAppTests.cs index 7b0464c..9c47f35 100644 --- a/Queueify.Web.Tests/WebAppTests.cs +++ b/Queueify.Web.Tests/WebAppTests.cs @@ -126,6 +126,37 @@ public async Task The_registration_confirmation_page_tells_nothing_about_who_has Assert.DoesNotContain("userId", knownHtml); } + [Fact] + public async Task Deleting_the_only_account_does_not_hand_the_server_to_the_next_visitor() + { + using var factory = Factory(allowRegistration: false); + await RegisterAsync(Client(factory), "owner@example.com"); + + using (var scope = factory.Services.CreateScope()) + { + var users = scope.ServiceProvider.GetRequiredService>(); + Assert.True((await users.DeleteAsync((await users.FindByEmailAsync("owner@example.com"))!)).Succeeded); + Assert.Empty(users.Users.ToList()); + } + + var visitor = Client(factory); + Assert.DoesNotContain("Input.Email", await visitor.GetStringAsync("/Account/Register", TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task An_existing_server_without_the_marker_gets_it_the_first_time_the_gate_is_asked() + { + using var factory = Factory(allowRegistration: false); + using (var scope = factory.Services.CreateScope()) + { + var users = scope.ServiceProvider.GetRequiredService>(); + Assert.True((await users.CreateAsync(new ApplicationUser { UserName = "old@example.com", Email = "old@example.com" }, "Passw0rd!x")).Succeeded); + Assert.False(await scope.ServiceProvider.GetRequiredService().IsOpenAsync()); + await users.DeleteAsync((await users.FindByEmailAsync("old@example.com"))!); + Assert.False(await scope.ServiceProvider.GetRequiredService().IsOpenAsync()); + } + } + [Fact] public async Task Two_simultaneous_first_registrations_make_one_owner() { diff --git a/Queueify.Web/Services/RegistrationGate.cs b/Queueify.Web/Services/RegistrationGate.cs index 22ebfc1..d2cbdea 100644 --- a/Queueify.Web/Services/RegistrationGate.cs +++ b/Queueify.Web/Services/RegistrationGate.cs @@ -1,17 +1,34 @@ using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Queueify.Web.Data; +using Queueify.Web.Sync; namespace Queueify.Web.Services; -/// Whether a new account may be created now: always for the first one (its owner), then only if `Queueify:AllowRegistration` says so. -public sealed class RegistrationGate(IConfiguration config, UserManager users) +/// +/// Whether a new account may be created now: always for the first one (its owner), then only if +/// `Queueify:AllowRegistration` says so. "The first one" is remembered in a marker file in the data folder, so +/// deleting the last account (or losing the account database) does not hand the server to the next visitor. +/// To start over on purpose, delete owner-exists from the data folder together with the account database. +/// +public sealed class RegistrationGate(IConfiguration config, UserManager users, DataLocation data) { // One creation at a time per server, so "nobody exists yet" is still true when the account is written. private static readonly SemaphoreSlim OneAtATime = new(1, 1); - public async Task IsOpenAsync() => - QueueifyUi.RegistrationOpen(config.GetValue("Queueify:AllowRegistration", false), await users.Users.AnyAsync()); + private string MarkerPath => Path.Combine(data.Root, "owner-exists"); + + public async Task IsOpenAsync() + { + var ownerExists = File.Exists(MarkerPath); + if (!ownerExists && await users.Users.AnyAsync()) + { + // A server that ran before the marker existed. + Mark(); + ownerExists = true; + } + return QueueifyUi.RegistrationOpen(config.GetValue("Queueify:AllowRegistration", false), ownerExists); + } /// Runs only if registration is open, with the check and the write inside one lock. public async Task RunIfOpenAsync(Func create) @@ -21,8 +38,15 @@ public async Task RunIfOpenAsync(Func create) { if (!await IsOpenAsync()) return false; await create(); + if (await users.Users.AnyAsync()) Mark(); return true; } finally { OneAtATime.Release(); } } -} \ No newline at end of file + + private void Mark() + { + Directory.CreateDirectory(data.Root); + File.WriteAllText(MarkerPath, "The first account of this server was created; registration stays closed unless Queueify:AllowRegistration is true.\n"); + } +} diff --git a/SECURITY.md b/SECURITY.md index 93bb7ef..0accaf2 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -54,7 +54,7 @@ Photo decoding uses SkiaSharp (MIT), a native library: it is fed only bytes that | Asset / surface | Threat | Defence | | --- | --- | --- | | Sign-in | Guessing passwords | ASP.NET Core Identity with passkeys; failed passwords count towards lockout (5 tries, then locked for 5 minutes). Not covered: a global rate limit in front of the server, so put the site behind a reverse proxy that has one. | -| Registration | A stranger creating an account on a public server | The first account owns the server (checked and written under one lock, so two first sign-ups can't both win); after that registration is closed unless `Queueify:AllowRegistration` is `true`. A fresh public server belongs to whoever registers first: register before exposing it. | +| Registration | A stranger creating an account on a public server | The first account owns the server (checked and written under one lock, so two first sign-ups can't both win); after that registration is closed unless `Queueify:AllowRegistration` is `true`. A fresh public server belongs to whoever registers first: register before exposing it. The first account is remembered in an `owner-exists` marker in the data folder, so deleting the last account (or losing `identity.db`) does not reopen registration; to start over on purpose, delete the marker and the account database together. | | Cross-site requests | Forged form posts (sign out, language, delete) | Antiforgery tokens on every form post, including `/prefs` and sign out; cookies are `SameSite=Lax`, `HttpOnly`, and `Secure` over HTTPS. | | Page content | Script injection, clickjacking, tracking pixels | Razor encodes everything; no raw HTML is rendered. Every response carries a Content-Security-Policy (own scripts only, `frame-ancestors 'none'`, `object-src 'none'`, forms only to the site; album covers may come from any HTTPS host and are fetched without a referrer), `X-Content-Type-Options: nosniff` and `Referrer-Policy: no-referrer`. | | Other users' data | Seeing or changing another queue | Each user's queue and settings live in a folder named by their account id (never by anything the browser sends); ids are checked against path tricks. | From cbaec30d4207ad94813fe5a800f3dc93af49476a Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:51:55 -0300 Subject: [PATCH 43/66] fix(web): sync tokens need the password and end with a credential change Minting a token on /connect asks for the password again (counted towards lockout). Each token stores the owner's security stamp and is refused once it changes (password change or reset, sign out everywhere). Co-Authored-By: Claude Sonnet 5.5 --- Queueify.Web.Tests/Sync/ConnectPcTests.cs | 51 ++- .../Sync/PersonalAccessTokenTests.cs | 42 ++ Queueify.Web/Components/Pages/ConnectPc.razor | 17 + ...0000_BindTokensToSecurityStamp.Designer.cs | 401 ++++++++++++++++++ ...0261014130000_BindTokensToSecurityStamp.cs | 29 ++ .../ApplicationDbContextModelSnapshot.cs | 3 + Queueify.Web/Sync/PersonalAccessToken.cs | 3 + Queueify.Web/Sync/PersonalAccessTokens.cs | 41 +- Queueify.Web/Sync/Reauthentication.cs | 24 ++ Queueify.Web/Sync/SyncExtensions.cs | 1 + Queueify.Web/Sync/TokenAuthentication.cs | 2 +- SECURITY.md | 2 +- 12 files changed, 595 insertions(+), 21 deletions(-) create mode 100644 Queueify.Web/Data/Migrations/20261014130000_BindTokensToSecurityStamp.Designer.cs create mode 100644 Queueify.Web/Data/Migrations/20261014130000_BindTokensToSecurityStamp.cs create mode 100644 Queueify.Web/Sync/Reauthentication.cs diff --git a/Queueify.Web.Tests/Sync/ConnectPcTests.cs b/Queueify.Web.Tests/Sync/ConnectPcTests.cs index f99c77a..9f9605c 100644 --- a/Queueify.Web.Tests/Sync/ConnectPcTests.cs +++ b/Queueify.Web.Tests/Sync/ConnectPcTests.cs @@ -21,6 +21,8 @@ public override Task GetAuthenticationStateAsync() => Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, id)], "test")))); } + private const string Password = "Passw0rd!-secret"; + private readonly SqliteConnection _db = new("DataSource=:memory:"); private IRenderedComponent Open(string userId) @@ -29,13 +31,16 @@ private IRenderedComponent Open(string userId) Services.AddDbContext(o => o.UseSqlite(_db)); Services.AddSingleton(TimeProvider.System); Services.AddScoped(); + Services.AddScoped(); + Services.AddLogging(); + Services.AddIdentityCore().AddEntityFrameworkStores(); Services.AddSingleton(new SignedIn(userId)); using (var scope = Services.BuildServiceProvider().CreateScope()) { var context = scope.ServiceProvider.GetRequiredService(); context.Database.EnsureCreated(); - context.Users.Add(new ApplicationUser { Id = userId, UserName = "u", NormalizedUserName = "U", SecurityStamp = "s" }); - context.SaveChanges(); + var users = scope.ServiceProvider.GetRequiredService>(); + Assert.True(users.CreateAsync(new ApplicationUser { Id = userId, UserName = "u" }, Password).GetAwaiter().GetResult().Succeeded); } return Render(); } @@ -45,6 +50,7 @@ public void Creating_a_token_shows_the_connect_text_once_and_lists_it() { var page = Open("user-1"); page.Find("#token-name").Input("Studio PC"); + page.Find("#token-password").Input(Password); page.Find("form").Submit(); var text = page.Find("#connect-text").GetAttribute("value")!; @@ -58,6 +64,47 @@ public void Creating_a_token_shows_the_connect_text_once_and_lists_it() Assert.DoesNotContain("qw_", page.Markup); } + [Fact] + public void A_wrong_password_makes_no_token_and_says_so() + { + var page = Open("user-2"); + page.Find("#token-name").Input("Studio PC"); + page.Find("#token-password").Input("not-the-password"); + page.Find("form").Submit(); + + Assert.Empty(page.FindAll("#connect-text")); + Assert.Contains(Loc.T("web.acct.m.bad_pw"), page.Markup); + Assert.Empty(page.FindAll("li.q-row")); + } + + [Fact] + public void An_empty_password_makes_no_token() + { + var page = Open("user-3"); + page.Find("#token-name").Input("Studio PC"); + page.Find("form").Submit(); + + Assert.Empty(page.FindAll("#connect-text")); + Assert.Empty(page.FindAll("li.q-row")); + } + + [Fact] + public void Wrong_passwords_here_count_towards_the_accounts_lockout() + { + var page = Open("user-4"); + for (var i = 0; i < 6; i++) + { + page.Find("#token-name").Input("PC"); + page.Find("#token-password").Input("wrong-" + i); + page.Find("form").Submit(); + } + + page.Find("#token-name").Input("PC"); + page.Find("#token-password").Input(Password); + page.Find("form").Submit(); + Assert.Empty(page.FindAll("#connect-text")); + } + [Fact] public void Every_text_on_the_page_exists_in_both_languages() { diff --git a/Queueify.Web.Tests/Sync/PersonalAccessTokenTests.cs b/Queueify.Web.Tests/Sync/PersonalAccessTokenTests.cs index fce30e3..8d5c8cf 100644 --- a/Queueify.Web.Tests/Sync/PersonalAccessTokenTests.cs +++ b/Queueify.Web.Tests/Sync/PersonalAccessTokenTests.cs @@ -1,3 +1,4 @@ +using System.Net; using System.Security.Cryptography; using System.Text; using Microsoft.Extensions.DependencyInjection; @@ -55,6 +56,47 @@ public async Task Using_a_token_records_when() Assert.NotNull(await WithTokens(async (tokens, _) => (await tokens.ListAsync(userId)).Single().LastUsedAt)); } + private async Task WithUsers(string userId, Func, ApplicationUser, Task> body) + { + using var scope = app.Services.CreateScope(); + var users = scope.ServiceProvider.GetRequiredService>(); + await body(users, (await users.FindByIdAsync(userId))!); + } + + [Fact] + public async Task A_token_stops_working_when_the_password_is_changed() + { + var (userId, token) = await app.NewUserAsync("pw-change"); + Assert.Equal(HttpStatusCode.OK, (await app.SyncAsync(token, new Queueify.Services.SyncRequest(null, [], null))).Status); + + await WithUsers(userId, async (users, user) => + Assert.True((await users.ChangePasswordAsync(user, "Passw0rd!-" + user.UserName!.Split('@')[0], "An0ther-Passw0rd!")).Succeeded)); + + Assert.Equal(HttpStatusCode.Unauthorized, (await app.SyncAsync(token, new Queueify.Services.SyncRequest(null, [], null))).Status); + } + + [Fact] + public async Task A_token_stops_working_when_the_password_is_reset() + { + var (userId, token) = await app.NewUserAsync("pw-reset"); + + await WithUsers(userId, async (users, user) => + Assert.True((await users.ResetPasswordAsync(user, await users.GeneratePasswordResetTokenAsync(user), "An0ther-Passw0rd!")).Succeeded)); + + Assert.Equal(HttpStatusCode.Unauthorized, (await app.SyncAsync(token, new Queueify.Services.SyncRequest(null, [], null))).Status); + } + + [Fact] + public async Task Signing_out_everywhere_also_ends_the_tokens_and_a_new_token_works_again() + { + var (userId, token) = await app.NewUserAsync("stamp"); + await WithUsers(userId, async (users, user) => Assert.True((await users.UpdateSecurityStampAsync(user)).Succeeded)); + Assert.Equal(HttpStatusCode.Unauthorized, (await app.SyncAsync(token, new Queueify.Services.SyncRequest(null, [], null))).Status); + + var fresh = await WithTokens(async (tokens, _) => (await tokens.CreateAsync(userId, "after")).Token); + Assert.Equal(HttpStatusCode.OK, (await app.SyncAsync(fresh, new Queueify.Services.SyncRequest(null, [], null))).Status); + } + [Fact] public async Task Tokens_are_revoked_only_by_their_owner() { diff --git a/Queueify.Web/Components/Pages/ConnectPc.razor b/Queueify.Web/Components/Pages/ConnectPc.razor index 0afcc16..44aaa03 100644 --- a/Queueify.Web/Components/Pages/ConnectPc.razor +++ b/Queueify.Web/Components/Pages/ConnectPc.razor @@ -3,6 +3,7 @@ @using Microsoft.AspNetCore.Authorization @using Queueify.Web.Sync @inject PersonalAccessTokens Tokens +@inject Reauthentication Reauth @inject AuthenticationStateProvider Auth @inject NavigationManager Navigation @@ -34,11 +35,20 @@ } + @if (_wrongPassword) + { + + } +
+
+ + +
@@ -78,6 +88,8 @@ private string _name = ""; private string? _connectText; private bool _limitReached; + private bool _wrongPassword; + private string _password = ""; private string? _userId; protected override async Task OnInitializedAsync() @@ -92,6 +104,11 @@ { if (_userId == null || string.IsNullOrWhiteSpace(_name)) return; _limitReached = false; + // A token outlives this session, so a session alone cannot make one. + var password = _password; + _password = ""; + _wrongPassword = !await Reauth.ConfirmPasswordAsync(_userId, password); + if (_wrongPassword) return; try { var created = await Tokens.CreateAsync(_userId, _name); diff --git a/Queueify.Web/Data/Migrations/20261014130000_BindTokensToSecurityStamp.Designer.cs b/Queueify.Web/Data/Migrations/20261014130000_BindTokensToSecurityStamp.Designer.cs new file mode 100644 index 0000000..a7b4fd1 --- /dev/null +++ b/Queueify.Web/Data/Migrations/20261014130000_BindTokensToSecurityStamp.Designer.cs @@ -0,0 +1,401 @@ +// +using System; +using Queueify.Web.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Queueify.Web.Migrations +{ + [DbContext(typeof(ApplicationDbContext))] + [Migration("20261014130000_BindTokensToSecurityStamp")] + partial class BindTokensToSecurityStamp + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.0"); + + modelBuilder.Entity("Queueify.Web.Data.ApplicationUser", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("AccessFailedCount") + .HasColumnType("INTEGER"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Email") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("EmailConfirmed") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnabled") + .HasColumnType("INTEGER"); + + b.Property("LockoutEnd") + .HasColumnType("TEXT"); + + b.Property("NormalizedEmail") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedUserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PasswordHash") + .HasColumnType("TEXT"); + + b.Property("PhoneNumber") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("PhoneNumberConfirmed") + .HasColumnType("INTEGER"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TwoFactorEnabled") + .HasColumnType("INTEGER"); + + b.Property("UserName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedEmail") + .HasDatabaseName("EmailIndex"); + + b.HasIndex("NormalizedUserName") + .IsUnique() + .HasDatabaseName("UserNameIndex"); + + b.ToTable("AspNetUsers", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => + { + b.Property("Id") + .HasColumnType("TEXT"); + + b.Property("ConcurrencyStamp") + .IsConcurrencyToken() + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("NormalizedName") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedName") + .IsUnique() + .HasDatabaseName("RoleNameIndex"); + + b.ToTable("AspNetRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetRoleClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClaimType") + .HasColumnType("TEXT"); + + b.Property("ClaimValue") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserClaims", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.Property("LoginProvider") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ProviderKey") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("ProviderDisplayName") + .HasColumnType("TEXT"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("LoginProvider", "ProviderKey"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserLogins", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserPasskey", b => + { + b.Property("CredentialId") + .HasMaxLength(1024) + .HasColumnType("BLOB"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("CredentialId"); + + b.HasIndex("UserId"); + + b.ToTable("AspNetUserPasskeys", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("RoleId") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("RoleId"); + + b.ToTable("AspNetUserRoles", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.Property("UserId") + .HasColumnType("TEXT"); + + b.Property("LoginProvider") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Name") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Value") + .HasColumnType("TEXT"); + + b.HasKey("UserId", "LoginProvider", "Name"); + + b.ToTable("AspNetUserTokens", (string)null); + }); + + modelBuilder.Entity("Queueify.Web.Sync.PersonalAccessToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("LastUsedAt") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("RevokedAt") + .HasColumnType("TEXT"); + + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("BLOB"); + + b.Property("UserId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("PersonalAccessTokens", (string)null); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim", b => + { + b.HasOne("Queueify.Web.Data.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin", b => + { + b.HasOne("Queueify.Web.Data.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserPasskey", b => + { + b.HasOne("Queueify.Web.Data.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.OwnsOne("Microsoft.AspNetCore.Identity.IdentityPasskeyData", "Data", b1 => + { + b1.Property("IdentityUserPasskeyCredentialId") + .HasColumnType("BLOB"); + + b1.Property("AttestationObject") + .IsRequired() + .HasColumnType("BLOB"); + + b1.Property("ClientDataJson") + .IsRequired() + .HasColumnType("BLOB"); + + b1.Property("CreatedAt") + .HasColumnType("TEXT"); + + b1.Property("IsBackedUp") + .HasColumnType("INTEGER"); + + b1.Property("IsBackupEligible") + .HasColumnType("INTEGER"); + + b1.Property("IsUserVerified") + .HasColumnType("INTEGER"); + + b1.Property("Name") + .HasColumnType("TEXT"); + + b1.Property("PublicKey") + .IsRequired() + .HasColumnType("BLOB"); + + b1.Property("SignCount") + .HasColumnType("INTEGER"); + + b1.PrimitiveCollection("Transports") + .HasColumnType("TEXT"); + + b1.HasKey("IdentityUserPasskeyCredentialId"); + + b1.ToTable("AspNetUserPasskeys"); + + b1.ToJson("Data"); + + b1.WithOwner() + .HasForeignKey("IdentityUserPasskeyCredentialId"); + }); + + b.Navigation("Data") + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole", b => + { + b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) + .WithMany() + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Queueify.Web.Data.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken", b => + { + b.HasOne("Queueify.Web.Data.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Queueify.Web.Sync.PersonalAccessToken", b => + { + b.HasOne("Queueify.Web.Data.ApplicationUser", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Queueify.Web/Data/Migrations/20261014130000_BindTokensToSecurityStamp.cs b/Queueify.Web/Data/Migrations/20261014130000_BindTokensToSecurityStamp.cs new file mode 100644 index 0000000..57b2ef9 --- /dev/null +++ b/Queueify.Web/Data/Migrations/20261014130000_BindTokensToSecurityStamp.cs @@ -0,0 +1,29 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Queueify.Web.Migrations +{ + /// + public partial class BindTokensToSecurityStamp : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + // Tokens made before this column existed have no stamp and stop working (the user makes a new one). + migrationBuilder.AddColumn( + name: "SecurityStamp", + table: "PersonalAccessTokens", + type: "TEXT", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "SecurityStamp", + table: "PersonalAccessTokens"); + } + } +} diff --git a/Queueify.Web/Data/Migrations/ApplicationDbContextModelSnapshot.cs b/Queueify.Web/Data/Migrations/ApplicationDbContextModelSnapshot.cs index d22fa3b..f0bb514 100644 --- a/Queueify.Web/Data/Migrations/ApplicationDbContextModelSnapshot.cs +++ b/Queueify.Web/Data/Migrations/ApplicationDbContextModelSnapshot.cs @@ -251,6 +251,9 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("RevokedAt") .HasColumnType("TEXT"); + b.Property("SecurityStamp") + .HasColumnType("TEXT"); + b.Property("TokenHash") .IsRequired() .HasMaxLength(32) diff --git a/Queueify.Web/Sync/PersonalAccessToken.cs b/Queueify.Web/Sync/PersonalAccessToken.cs index 24d86f8..c0ef2e4 100644 --- a/Queueify.Web/Sync/PersonalAccessToken.cs +++ b/Queueify.Web/Sync/PersonalAccessToken.cs @@ -14,6 +14,9 @@ public sealed class PersonalAccessToken public DateTime? LastUsedAt { get; set; } public DateTime? RevokedAt { get; set; } + /// The owner's Identity security stamp when the token was made. A password change or reset, or "sign out everywhere", changes the stamp and so ends every older token. + public string? SecurityStamp { get; set; } + internal static void Configure(ModelBuilder model) => model.Entity(t => { diff --git a/Queueify.Web/Sync/PersonalAccessTokens.cs b/Queueify.Web/Sync/PersonalAccessTokens.cs index a0ef72e..3ffefd8 100644 --- a/Queueify.Web/Sync/PersonalAccessTokens.cs +++ b/Queueify.Web/Sync/PersonalAccessTokens.cs @@ -22,49 +22,56 @@ private static bool LooksLikeToken(string token) => && token.AsSpan(Prefix.Length).IndexOfAnyExcept("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_") < 0; /// The token text is returned here and nowhere else: only its hash is stored. - public async Task CreateAsync(string userId, string name) + public async Task CreateAsync(string userId, string name, CancellationToken ct = default) { name = name.Trim(); if (name.Length > MaxNameLength) name = name[..MaxNameLength]; - if (await db.PersonalAccessTokens.CountAsync(t => t.UserId == userId && t.RevokedAt == null) >= MaxPerUser) + if (await db.PersonalAccessTokens.CountAsync(t => t.UserId == userId && t.RevokedAt == null, ct) >= MaxPerUser) throw new InvalidOperationException("Too many tokens."); + var stamp = await db.Users.Where(u => u.Id == userId).Select(u => u.SecurityStamp).FirstOrDefaultAsync(ct) + ?? throw new InvalidOperationException("No such user."); + var token = Prefix + Base64Url(RandomNumberGenerator.GetBytes(32)); var row = new PersonalAccessToken { - Id = Guid.NewGuid(), UserId = userId, Name = name, TokenHash = Hash(token), CreatedAt = clock.GetUtcNow().UtcDateTime, + Id = Guid.NewGuid(), UserId = userId, Name = name, TokenHash = Hash(token), CreatedAt = clock.GetUtcNow().UtcDateTime, SecurityStamp = stamp, }; db.PersonalAccessTokens.Add(row); - await db.SaveChangesAsync(); + await db.SaveChangesAsync(ct); return new NewToken(row, token); } - public async Task> ListAsync(string userId) => - await db.PersonalAccessTokens.AsNoTracking().Where(t => t.UserId == userId).OrderBy(t => t.CreatedAt).ToListAsync(); + public async Task> ListAsync(string userId, CancellationToken ct = default) => + await db.PersonalAccessTokens.AsNoTracking().Where(t => t.UserId == userId).OrderBy(t => t.CreatedAt).ToListAsync(ct); /// Revokes one of the user's own tokens; false when it isn't theirs or doesn't exist. - public async Task RevokeAsync(string userId, Guid id) + public async Task RevokeAsync(string userId, Guid id, CancellationToken ct = default) { - var row = await db.PersonalAccessTokens.FirstOrDefaultAsync(t => t.Id == id && t.UserId == userId); - if (row == null) return false; - row.RevokedAt ??= clock.GetUtcNow().UtcDateTime; - await db.SaveChangesAsync(); - return true; + var now = clock.GetUtcNow().UtcDateTime; + // One statement, and an already revoked token keeps its first revocation time. + var revoked = await db.PersonalAccessTokens.Where(t => t.Id == id && t.UserId == userId && t.RevokedAt == null) + .ExecuteUpdateAsync(s => s.SetProperty(t => t.RevokedAt, now), ct); + return revoked > 0 || await db.PersonalAccessTokens.AnyAsync(t => t.Id == id && t.UserId == userId, ct); } - /// The id of the user a live token belongs to, or null for anything else. - public async Task ValidateAsync(string token) + /// The id of the user a live token belongs to, or null for anything else (unknown, revoked, or older than the owner's last security-stamp change). + public async Task ValidateAsync(string token, CancellationToken ct = default) { if (!LooksLikeToken(token)) return null; var hash = Hash(token); - var row = await db.PersonalAccessTokens.FirstOrDefaultAsync(t => t.TokenHash == hash); - if (row == null || !CryptographicOperations.FixedTimeEquals(row.TokenHash, hash) || row.RevokedAt != null) return null; + var row = await (from t in db.PersonalAccessTokens.AsNoTracking() + join u in db.Users on t.UserId equals u.Id + where t.TokenHash == hash + select new { t.Id, t.UserId, t.RevokedAt, t.LastUsedAt, TokenStamp = t.SecurityStamp, UserStamp = u.SecurityStamp }) + .FirstOrDefaultAsync(ct); + if (row == null || row.RevokedAt != null || row.TokenStamp == null || row.TokenStamp != row.UserStamp) return null; var now = clock.GetUtcNow().UtcDateTime; if (row.LastUsedAt == null || now - row.LastUsedAt > TimeSpan.FromMinutes(1)) { // Only the timestamp changes, so a revocation made meanwhile is never undone. - await db.PersonalAccessTokens.Where(t => t.Id == row.Id).ExecuteUpdateAsync(s => s.SetProperty(t => t.LastUsedAt, now)); + await db.PersonalAccessTokens.Where(t => t.Id == row.Id).ExecuteUpdateAsync(s => s.SetProperty(t => t.LastUsedAt, now), ct); } return row.UserId; } diff --git a/Queueify.Web/Sync/Reauthentication.cs b/Queueify.Web/Sync/Reauthentication.cs new file mode 100644 index 0000000..dac3ff2 --- /dev/null +++ b/Queueify.Web/Sync/Reauthentication.cs @@ -0,0 +1,24 @@ +using Microsoft.AspNetCore.Identity; +using Queueify.Web.Data; + +namespace Queueify.Web.Sync; + +/// +/// Asks for the password again before something that outlives the session is handed out (a sync token). A stolen +/// or left-open session therefore cannot mint one, and wrong guesses count towards the account's lockout like at sign-in. +/// +public sealed class Reauthentication(UserManager users) +{ + public async Task ConfirmPasswordAsync(string userId, string? password) + { + if (string.IsNullOrEmpty(password) || await users.FindByIdAsync(userId) is not { } user) return false; + if (await users.IsLockedOutAsync(user)) return false; + if (await users.CheckPasswordAsync(user, password)) + { + await users.ResetAccessFailedCountAsync(user); + return true; + } + await users.AccessFailedAsync(user); + return false; + } +} diff --git a/Queueify.Web/Sync/SyncExtensions.cs b/Queueify.Web/Sync/SyncExtensions.cs index 1f24fcd..4671cbc 100644 --- a/Queueify.Web/Sync/SyncExtensions.cs +++ b/Queueify.Web/Sync/SyncExtensions.cs @@ -36,6 +36,7 @@ public static IServiceCollection AddQueueifySync(this IServiceCollection service sp.GetRequiredService().GetValue("Queueify:Sync:MaxAlbumsPerUser", SyncEngine.DefaultMaxRowsPerUser))); services.AddSingleton(); services.AddScoped(); + services.AddScoped(); services.AddHostedService(); services.AddTransient(); diff --git a/Queueify.Web/Sync/TokenAuthentication.cs b/Queueify.Web/Sync/TokenAuthentication.cs index cf25ef7..752cf48 100644 --- a/Queueify.Web/Sync/TokenAuthentication.cs +++ b/Queueify.Web/Sync/TokenAuthentication.cs @@ -29,7 +29,7 @@ protected override async Task HandleAuthenticateAsync() const string bearer = "Bearer "; if (!header.StartsWith(bearer, StringComparison.Ordinal)) return AuthenticateResult.NoResult(); - var userId = await tokens.ValidateAsync(header[bearer.Length..].Trim()); + var userId = await tokens.ValidateAsync(header[bearer.Length..].Trim(), Context.RequestAborted); if (userId == null) return AuthenticateResult.Fail("bad token"); var identity = new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, userId)], Scheme); diff --git a/SECURITY.md b/SECURITY.md index 0accaf2..519a89b 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -27,7 +27,7 @@ web server (`Queueify.Web`, [ADR-0010](docs/adr/0010-web-app-and-shared-queue.md | Cover addresses (from the services and from other PCs through sync) | A file or network path reading local files or sending the Windows login to another machine | Only `http` and `https` addresses are loaded (`CoverUrls`, tested). | | The app's unpacked copy (`%LOCALAPPDATA%\Queueify\app`) | Changed files run as Queueify | Only the user (or an admin) can write there, as with any per-user app. The starter is native code and loads its imports from System32 only; the app's working folder is its own. A version's folder is used only once fully unpacked and checked against the SHA-256 in the download. | | Updates (the exe itself) | A tampered or broken download replacing Queueify | Offered only from Queueify's GitHub releases over HTTPS; the download must match the SHA-256 GitHub lists for it, or it's thrown away and the exe left as it was; it's always written to a new file, never into one someone left next to the exe; installing waits for the user's click ([ADR-0009](docs/adr/0009-update-from-github-releases.md)). Not covered: a release published from a taken-over maintainer account (the exe isn't signed). | -| Personal access tokens (the web server's `/connect` page) | A stolen database or backup yields usable tokens; a token leaks from a PC | Only the SHA-256 hash is stored (the tokens are 256 random bits, so a fast hash is enough), compared in constant time. A token is shown once, can be revoked at any time (a revoked token is refused at once), is bound to one user and is limited to `/api/sync`. At most 20 live tokens per user. Not covered: a token stolen from a PC works until the user revokes it. | +| Personal access tokens (the web server's `/connect` page) | A stolen database or backup yields usable tokens; a token leaks from a PC | Only the SHA-256 hash is stored (the tokens are 256 random bits, so a fast hash is enough), compared in constant time. Making one asks for the account password again (wrong guesses count towards lockout), so a stolen or left-open session cannot mint one. A token is shown once, ends by itself when the account's password is changed or reset or "sign out everywhere" is used (it is bound to the account's security stamp; make a new one afterwards), can be revoked at any time (a revoked token is refused at once), is bound to one user and is limited to `/api/sync`. At most 20 live tokens per user. Not covered: a token stolen from a PC works until the user revokes it. | | `POST /api/sync` on the web server | Unauthenticated access; guessing tokens; reading or changing another user's queue; oversized or malformed bodies; a PC with a wrong clock overwriting everything | Bearer tokens only (the login cookie is not accepted, so no CSRF); a bad, missing or revoked token is 401 with an empty body; every attempt counts against a per-address limit (429); the user comes from the token, never from the request, and each user has their own folder and database (ids are checked never to leave the data folder); bodies are capped (413) and read through a cap; at most 1,000 albums per request, text cut at 500 characters, ids limited to `[A-Za-z0-9_-]{1,64}`; an `updatedAt` more than ten minutes ahead of the server is pulled back. Behind a reverse proxy, set `Queueify:Proxy:KnownProxies` (addresses) or `Queueify:Proxy:KnownNetworks` (CIDR): `X-Forwarded-For/Proto` is trusted only from those, otherwise ignored (and then all users share the proxy's address). A user's queue is capped at 50,000 rows (`Queueify:Sync:MaxAlbumsPerUser`; 413 beyond it). A token also reaches the Spotify and Tidal secrets (they sync to the PCs), and tokens keep working while an account is locked out until the user revokes them. Deleted rows are kept for 90 days (they are how other PCs delete) and then purged; a PC offline for longer may keep an album that was deleted elsewhere. | | Spotify and Tidal secrets on the web server | Someone reads `settings.json` or a backup of a user's folder | The secrets are encrypted with ASP.NET Data Protection (per-user purpose) into `secrets.dat`, never written to `settings.json`, and never sent to a browser; they are sent to the user's own PCs over HTTPS when those sync. Not covered: the Data Protection keys sit in `DataDir\keys` (unencrypted on Linux), so a copy of the whole data folder opens the secrets: back up and protect it as one. | | Clipboard | Leaking data | Written only on explicit "Copy" clicks (sync code, security rules); read only on Ctrl+V or Paste. | From 6d9c42204b35cb4b7e913d1083d8164452098621 Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:52:55 -0300 Subject: [PATCH 44/66] test: run the real ServerSync client against the real SyncEngine Adds ServerSyncEndToEndTests (two PCs and the web, conflicts both ways, deletions, tombstone-only first page, >1000 albums, shared keys, revoked token) and SyncEngine edge cases found by pseudo-mutation (purge of unstamped tombstones, settings re-stamp, duplicate uids, surrogate-pair cut). Uploads no longer split a surrogate pair at the 500-character limit. Co-Authored-By: Claude Sonnet 5.5 --- Queueify.Core/Services/CloudSync.cs | 9 +- Queueify.Core/Services/ServerSync.cs | 2 +- Queueify.Tests/ServerSyncPagingTests.cs | 51 +++ .../Sync/ServerSyncEndToEndTests.cs | 367 ++++++++++++++++++ 4 files changed, 427 insertions(+), 2 deletions(-) create mode 100644 Queueify.Web.Tests/Sync/ServerSyncEndToEndTests.cs diff --git a/Queueify.Core/Services/CloudSync.cs b/Queueify.Core/Services/CloudSync.cs index be3b6ce..81aff02 100644 --- a/Queueify.Core/Services/CloudSync.cs +++ b/Queueify.Core/Services/CloudSync.cs @@ -42,6 +42,13 @@ private static string LoadRules() /// Longest text the security rules accept per field; longer text is shortened on upload. public const int MaxTextLength = 500; + /// The text cut to , never in the middle of a surrogate pair (a lone half would not survive JSON). + public static string CutText(string text) + { + if (text.Length <= MaxTextLength) return text; + return char.IsHighSurrogate(text[MaxTextLength - 1]) ? text[..(MaxTextLength - 1)] : text[..MaxTextLength]; + } + /// Re-check a few seconds before the last seen change, in case of near-simultaneous commits. private static readonly TimeSpan Overlap = TimeSpan.FromSeconds(5); @@ -285,7 +292,7 @@ private static string Describe(HttpStatusCode status, string body) private static JsonObject Null() => new() { ["nullValue"] = null }; private static JsonObject TextValue(string? value) => - value == null ? Null() : new JsonObject { ["stringValue"] = value.Length <= MaxTextLength ? value : value[..MaxTextLength] }; + value == null ? Null() : new JsonObject { ["stringValue"] = CutText(value) }; private static JsonObject TimeValue(DateTime utc) => new() { diff --git a/Queueify.Core/Services/ServerSync.cs b/Queueify.Core/Services/ServerSync.cs index 1abd807..417be65 100644 --- a/Queueify.Core/Services/ServerSync.cs +++ b/Queueify.Core/Services/ServerSync.cs @@ -242,7 +242,7 @@ private static DateTime Past(DateTime t, DateTime now) private static string? Cut(string? text) => - text is { Length: > MaxTextLength } ? text[..MaxTextLength] : text; + text == null ? null : CloudSync.CutText(text); /// A time with no zone is taken as UTC, the zone every time on the wire is in. private static DateTime Utc(DateTime t) => diff --git a/Queueify.Tests/ServerSyncPagingTests.cs b/Queueify.Tests/ServerSyncPagingTests.cs index 6e9649a..cbc8cff 100644 --- a/Queueify.Tests/ServerSyncPagingTests.cs +++ b/Queueify.Tests/ServerSyncPagingTests.cs @@ -180,3 +180,54 @@ public async Task An_answer_that_grows_past_the_limit_without_announcing_its_siz Assert.Equal(Loc.T("webSync.err.bad_reply"), ex.Message); } } + +public class TextCutTests +{ + [Fact] + public void Text_within_the_limit_is_untouched() => + Assert.Equal("short", CloudSync.CutText("short")); + + [Fact] + public void Longer_text_is_cut_at_the_limit() => + Assert.Equal(new string('a', CloudSync.MaxTextLength), CloudSync.CutText(new string('a', 900))); + + [Fact] + public void A_cut_never_leaves_half_a_surrogate_pair() + { + var text = new string('a', CloudSync.MaxTextLength - 1) + "\U0001F600" + "tail"; + + var cut = CloudSync.CutText(text); + + Assert.Equal(new string('a', CloudSync.MaxTextLength - 1), cut); + } + + [Fact] + public async Task What_goes_up_is_cut_at_a_character_boundary() + { + var sent = new List(); + var server = new Scripted2(sent); + var dir = Path.Combine(Path.GetTempPath(), "queueify-tests", Guid.NewGuid().ToString("N")); + try + { + var store = new BacklogStore(Path.Combine(dir, "q.db")); + store.Insert(new BacklogItem { Artist = "A", Album = new string('a', CloudSync.MaxTextLength - 1) + "\U0001F600", AddedAt = DateTime.Now }); + + await new ServerSync(new HttpClient(server)).SyncAsync(store, new AppSettings { WebServerUrl = "https://queue.example.com", WebToken = "qw_TOKEN" }, CancellationToken.None); + + Assert.Equal(new string('a', CloudSync.MaxTextLength - 1), sent[0].Albums[0].Album); + } + finally { SqliteConnection.ClearAllPools(); if (Directory.Exists(dir)) Directory.Delete(dir, true); } + } + + private sealed class Scripted2(List sent) : HttpMessageHandler + { + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + sent.Add(JsonSerializer.Deserialize(await request.Content!.ReadAsStringAsync(ct), SyncJson.Default.SyncRequest)!); + return new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent(JsonSerializer.Serialize(new SyncResponse(new DateTime(2026, 10, 1, 12, 0, 0, DateTimeKind.Utc), [], null), SyncJson.Default.SyncResponse), Encoding.UTF8, "application/json"), + }; + } + } +} diff --git a/Queueify.Web.Tests/Sync/ServerSyncEndToEndTests.cs b/Queueify.Web.Tests/Sync/ServerSyncEndToEndTests.cs new file mode 100644 index 0000000..67ab675 --- /dev/null +++ b/Queueify.Web.Tests/Sync/ServerSyncEndToEndTests.cs @@ -0,0 +1,367 @@ +using Microsoft.Data.Sqlite; +using Microsoft.Extensions.DependencyInjection; +using Queueify.Models; +using Queueify.Services; +using Queueify.Web.Sync; + +namespace Queueify.Web.Tests.Sync; + +/// +/// The desktop client (, from Core) against the real server (), in +/// process. The fake server in Queueify.Tests re-implements the server's rules and can drift from it; these pin the two +/// together. Each PC is a scratch ; users are unique per test, so the host is shared. +/// +public sealed class ServerSyncEndToEndTests(SyncFactory app) : IClassFixture, IDisposable +{ + private readonly string _dir = Path.Combine(Path.GetTempPath(), "qw-e2e-" + Guid.NewGuid().ToString("N")); + + public void Dispose() + { + SqliteConnection.ClearAllPools(); + try { Directory.Delete(_dir, true); } catch (IOException) { } catch (UnauthorizedAccessException) { } + } + + /// One desktop PC: its own database and settings, and the real client with an in-process connection. + private sealed class Pc(string path, string token, HttpClient http) + { + public readonly string Path = path; + public readonly BacklogStore Store = new(path); + public readonly AppSettings Settings = new() { WebServerUrl = "http://localhost", WebToken = token }; + private readonly ServerSync _client = new(http); + + public Task SyncAsync() => _client.SyncAsync(Store, Settings, CancellationToken.None); + + public BacklogItem Add(string artist, string album) + { + var item = new BacklogItem { Artist = artist, Album = album, Year = 1973, AddedAt = DateTime.Now }; + Store.Insert(item); + return item; + } + + public void Edit(string uid, Action change) + { + var item = Store.FindByUid(uid)!; + change(item); + Store.Update(item); + } + + public IEnumerable<(string, string, string, int?, double, DateTime, DateTime?)> Snapshot() => + Store.LoadAll().OrderBy(i => i.Uid).Select(i => (i.Uid, i.Artist, i.Album, i.Year, i.Rating, i.UpdatedAt, i.ListenedAt?.ToUniversalTime())); + } + + private Pc NewPc(string token) => new(Path.Combine(_dir, Guid.NewGuid().ToString("N") + ".db"), token, app.CreateClient()); + + private static void Execute(string path, string sql) + { + using var db = new SqliteConnection($"Data Source={path};Pooling=False"); + db.Open(); + using var cmd = db.CreateCommand(); + cmd.CommandText = sql; + cmd.ExecuteNonQuery(); + } + + // ───────────── two PCs and the web ───────────── + + [Fact] + public async Task Two_PCs_and_the_web_pages_end_up_with_the_same_queue() + { + var (userId, token) = await app.NewUserAsync("e2e"); + var pc1 = NewPc(token); + var pc2 = NewPc(token); + pc1.Add("Sonic Youth", "Daydream Nation"); + pc1.Add("Spinetta", "Artaud"); + await pc1.SyncAsync(); + + var first = await pc2.SyncAsync(); + Assert.Equal(2, first.Downloaded); + Assert.Equal(pc1.Snapshot(), pc2.Snapshot()); + + // the web page adds an album through the same store the pages use + app.Stores.QueueOf(userId).Insert(new BacklogItem { Artist = "Charly García", Album = "Clics Modernos", Year = 1983, AddedAt = DateTime.UtcNow }); + var uid = pc2.Store.LoadAll().First(i => i.Album == "Artaud").Uid; + pc2.Edit(uid, i => { i.Rating = 5; i.ListenedAt = DateTime.Now; }); + await pc2.SyncAsync(); + await pc1.SyncAsync(); + await pc2.SyncAsync(); + + Assert.Equal(3, pc1.Store.LoadAll().Count); + Assert.Equal(pc1.Snapshot(), pc2.Snapshot()); + Assert.Equal(5, pc1.Store.FindByUid(uid)!.Rating); + Assert.Empty(pc1.Store.LoadDirty()); + Assert.Empty(pc2.Store.LoadDirty()); + Assert.Equal(0, (await pc1.SyncAsync()).Downloaded); // nothing left to say + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task When_two_PCs_edit_the_same_album_the_later_edit_wins_whichever_syncs_first(bool theNewerEditSyncsFirst) + { + var (_, token) = await app.NewUserAsync("conflict"); + var pc1 = NewPc(token); + var pc2 = NewPc(token); + var uid = pc1.Add("Virus", "Locura").Uid; + await pc1.SyncAsync(); + await pc2.SyncAsync(); + + pc1.Edit(uid, i => i.Album = "Older edit"); + pc2.Edit(uid, i => i.Album = "Newer edit"); + if (theNewerEditSyncsFirst) { await pc2.SyncAsync(); await pc1.SyncAsync(); } + else { await pc1.SyncAsync(); await pc2.SyncAsync(); } + await pc1.SyncAsync(); + await pc2.SyncAsync(); + + Assert.Equal("Newer edit", pc1.Store.FindByUid(uid)!.Album); + Assert.Equal(pc1.Snapshot(), pc2.Snapshot()); + Assert.Empty(pc1.Store.LoadDirty()); + Assert.Empty(pc2.Store.LoadDirty()); + } + + // ───────────── deletions ───────────── + + [Fact] + public async Task A_deletion_reaches_the_other_PC_and_is_forgotten_by_the_one_that_made_it() + { + var (_, token) = await app.NewUserAsync("delete"); + var pc1 = NewPc(token); + var pc2 = NewPc(token); + var gone = pc1.Add("Gone", "Soon"); + pc1.Add("Stays", "Here"); + await pc1.SyncAsync(); + await pc2.SyncAsync(); + + pc1.Store.Delete(gone); + await pc1.SyncAsync(); + await pc2.SyncAsync(); + + Assert.Equal(["Here"], pc2.Store.LoadAll().Select(i => i.Album)); + Assert.Null(pc2.Store.FindByUid(gone.Uid)); + Assert.Null(pc1.Store.FindByUid(gone.Uid)); // the uploaded deletion is removed for good on the PC + Assert.Equal(pc1.Snapshot(), pc2.Snapshot()); + } + + [Fact] + public async Task A_PC_that_joins_later_never_sees_an_album_that_was_already_deleted() + { + var (_, token) = await app.NewUserAsync("late"); + var pc1 = NewPc(token); + var gone = pc1.Add("Gone", "Soon"); + pc1.Add("Stays", "Here"); + await pc1.SyncAsync(); + pc1.Store.Delete(gone); + await pc1.SyncAsync(); + + var late = NewPc(token); + var result = await late.SyncAsync(); + + Assert.Equal(["Here"], late.Store.LoadAll().Select(i => i.Album)); + Assert.Equal(1, result.Downloaded); + Assert.Null(late.Store.FindByUid(gone.Uid)); + } + + [Fact] + public async Task An_edit_made_after_a_deletion_on_another_PC_brings_the_album_back() + { + var (_, token) = await app.NewUserAsync("undelete"); + var pc1 = NewPc(token); + var pc2 = NewPc(token); + var album = pc1.Add("Virus", "Locura"); + await pc1.SyncAsync(); + await pc2.SyncAsync(); + + pc1.Store.Delete(album); + pc2.Edit(album.Uid, i => i.Rating = 4); // later than the deletion + await pc1.SyncAsync(); + await pc2.SyncAsync(); + await pc1.SyncAsync(); + + Assert.Equal(4, pc1.Store.FindByUid(album.Uid)!.Rating); + Assert.Equal(pc1.Snapshot(), pc2.Snapshot()); + } + + // ───────────── paging ───────────── + + private static BacklogItem Backup(int i) => new() + { + Uid = "u" + i.ToString("D5"), Artist = "Artist " + i, Album = "Album " + i, AddedAt = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc), + UpdatedAt = new DateTime(2026, 6, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(i), + }; + + [Fact] + public async Task A_queue_of_more_than_1000_albums_goes_up_and_comes_down_in_pages() + { + var (_, token) = await app.NewUserAsync("big"); + var pc1 = NewPc(token); + pc1.Store.MergeBackup(Enumerable.Range(0, 2500).Select(Backup)); + + var up = await pc1.SyncAsync(); + var pc2 = NewPc(token); + var down = await pc2.SyncAsync(); + + Assert.Equal(2500, up.Uploaded); + Assert.Equal(2500, down.Downloaded); + Assert.Equal(2500, pc2.Store.LoadAll().Count); + Assert.Equal(pc1.Snapshot(), pc2.Snapshot()); + Assert.Equal(0, (await pc2.SyncAsync()).Downloaded); + } + + [Fact] + public async Task A_new_PC_gets_the_albums_even_when_the_first_page_holds_only_old_deletions() + { + var (_, token) = await app.NewUserAsync("tombstones"); + var pc1 = NewPc(token); + pc1.Store.MergeBackup(Enumerable.Range(0, 1200).Select(Backup)); + // The first 1100 are deleted here, so the server's oldest 1000 rows are all deletions. + Execute(pc1.Path, $"UPDATE items SET deleted = 1, dirty = 1, updated_at = '{BacklogStore.Now():O}' WHERE rowid <= 1100"); + await pc1.SyncAsync(); + + var pc2 = NewPc(token); + await pc2.SyncAsync(); + + Assert.Equal(100, pc2.Store.LoadAll().Count); + Assert.Equal(pc1.Store.LoadAll().Count, pc2.Store.LoadAll().Count); + } + + // ───────────── settings and tokens ───────────── + + [Fact] + public async Task The_first_PC_with_keys_makes_them_the_shared_keys_and_the_next_PC_receives_them() + { + var (_, token) = await app.NewUserAsync("settings"); + var pc1 = NewPc(token); + pc1.Settings.SpotifyClientId = "spotify-id"; + pc1.Settings.SpotifyClientSecret = "spotify-secret"; + pc1.Settings.PreferredService = "Spotify"; + pc1.Settings.CountryCode = "AR"; + pc1.Settings.SharedSettingsUpdatedAt = null; + await pc1.SyncAsync(); + + var pc2 = NewPc(token); + var result = await pc2.SyncAsync(); + + Assert.True(result.SettingsChanged); + Assert.Equal(("spotify-id", "spotify-secret", "Spotify", "AR"), + (pc2.Settings.SpotifyClientId, pc2.Settings.SpotifyClientSecret, pc2.Settings.PreferredService, pc2.Settings.CountryCode)); + } + + [Fact] + public async Task A_revoked_token_stops_the_sync_with_a_plain_message() + { + var (userId, _) = await app.NewUserAsync("revoked"); + NewToken created; + using (var scope = app.Services.CreateScope()) + created = await scope.ServiceProvider.GetRequiredService().CreateAsync(userId, "second PC"); + var pc = NewPc(created.Token); + await pc.SyncAsync(); + + using (var scope = app.Services.CreateScope()) + Assert.True(await scope.ServiceProvider.GetRequiredService().RevokeAsync(userId, created.Info.Id)); + pc.Add("After", "Revocation"); + + var ex = await Assert.ThrowsAsync(() => pc.SyncAsync()); + + Assert.Equal(Loc.T("webSync.err.unauthorized"), ex.Message); + Assert.DoesNotContain(created.Token, ex.Message); + Assert.Single(pc.Store.LoadDirty()); // nothing was lost: it is sent when a valid token is entered + } + + [Fact] + public async Task Text_cut_on_upload_never_ends_in_half_an_emoji() + { + var (_, token) = await app.NewUserAsync("emoji"); + var pc1 = NewPc(token); + pc1.Add("Artist", new string('a', ServerSync.MaxTextLength - 1) + "\U0001F600" + "tail"); + + await pc1.SyncAsync(); + var pc2 = NewPc(token); + await pc2.SyncAsync(); + + var album = Assert.Single(pc2.Store.LoadAll()).Album; + Assert.DoesNotContain(album, c => char.IsSurrogate(c)); + Assert.Equal(new string('a', ServerSync.MaxTextLength - 1), album); + } +} + +/// Edge cases of the server's merge that the contract tests did not pin, found by removing one condition at a time. +public sealed class SyncEngineEdgeTests(SyncFactory app) : IClassFixture +{ + private static readonly DateTime T = new(2026, 6, 1, 12, 0, 0, DateTimeKind.Utc); + + private static SyncAlbum Wire(string uid, string album, DateTime updated, string artist = "Artist", bool deleted = false) => + new(uid, artist, album, 1999, null, null, null, null, T, null, -1, updated, deleted); + + private async Task Pull(string token, DateTime? since = null) => + (await app.SyncAsync(token, new SyncRequest(since, [], null))).Body!; + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task The_same_album_twice_in_one_request_keeps_the_newer_whichever_comes_first(bool newerFirst) + { + var (_, token) = await app.NewUserAsync("dup"); + var older = Wire("dup1", "Older", T); + var newer = Wire("dup1", "Newer", T.AddMinutes(1)); + + var (status, _) = await app.SyncAsync(token, new SyncRequest(null, newerFirst ? [newer, older] : [older, newer], null)); + + Assert.Equal(System.Net.HttpStatusCode.OK, status); + Assert.Equal("Newer", Assert.Single((await Pull(token)).Albums).Album); + } + + [Fact] + public async Task Text_is_cut_at_500_characters_without_leaving_half_a_surrogate_pair() + { + var (_, token) = await app.NewUserAsync("cut"); + var text = new string('a', SyncEngine.MaxText - 1) + "\U0001F600" + "tail"; + + await app.SyncAsync(token, new SyncRequest(null, [Wire("cut1", text, T, artist: text)], null)); + + var stored = Assert.Single((await Pull(token)).Albums); + Assert.Equal(new string('a', SyncEngine.MaxText - 1), stored.Album); + Assert.Equal(new string('a', SyncEngine.MaxText - 1), stored.Artist); + } + + [Fact] + public async Task A_deletion_made_on_the_web_and_not_yet_sent_to_any_PC_is_not_purged_however_old() + { + var (userId, token) = await app.NewUserAsync("purge"); + var first = await Pull(token); // creates the server's columns in the user's file + var item = new BacklogItem { Artist = "Gone", Album = "Soon", AddedAt = DateTime.UtcNow }; + var queue = app.Stores.QueueOf(userId); + queue.Insert(item); + queue.Delete(item); + // Older than the 90 days tombstones are kept, but never stamped: no PC has been told yet. + using (var db = new SqliteConnection($"Data Source={app.Stores.QueuePathOf(userId)};Pooling=False")) + { + db.Open(); + using var cmd = db.CreateCommand(); + cmd.CommandText = "UPDATE items SET updated_at = $old WHERE uid = $uid"; + cmd.Parameters.AddWithValue("$old", DateTime.UtcNow.AddDays(-120).ToString("O")); + cmd.Parameters.AddWithValue("$uid", item.Uid); + cmd.ExecuteNonQuery(); + } + + var answer = await Pull(token, first.ServerTime); + + var tombstone = Assert.Single(answer.Albums); + Assert.Equal(item.Uid, tombstone.Uid); + Assert.True(tombstone.Deleted); + } + + [Fact] + public async Task Settings_saved_on_the_web_are_sent_once_not_with_every_sync() + { + var (userId, token) = await app.NewUserAsync("seen"); + var settings = app.Stores.LoadSettings(userId); + settings.SpotifyClientId = "web-id"; + settings.SpotifyClientSecret = "web-secret"; + settings.SharedSettingsUpdatedAt = DateTime.UtcNow; + app.Stores.SaveSettings(userId, settings); + + var first = await Pull(token); + var second = await Pull(token, first.ServerTime); + + Assert.Equal("web-id", first.Settings!.SpotifyClientId); + Assert.Null(second.Settings); + } +} From dd07219075d1e01846126e6886b14f178d9861ce Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:54:50 -0300 Subject: [PATCH 45/66] fix(web): force Secure cookies outside Development Behind a proxy that is not a trusted hop the app sees plain http and issued sign-in, antiforgery, language and theme cookies without Secure. Outside Development every request now counts as https; Queueify:AllowInsecureCookies opts out for plain-http LANs. Co-Authored-By: Claude Sonnet 5.5 --- Queueify.Web.Tests/WebAppTests.cs | 76 +++++++++++++++++++++++++++++ Queueify.Web/Program.cs | 1 + Queueify.Web/Services/QueueifyUi.cs | 27 +++++++++- SECURITY.md | 2 +- 4 files changed, 104 insertions(+), 2 deletions(-) diff --git a/Queueify.Web.Tests/WebAppTests.cs b/Queueify.Web.Tests/WebAppTests.cs index 9c47f35..3766bf6 100644 --- a/Queueify.Web.Tests/WebAppTests.cs +++ b/Queueify.Web.Tests/WebAppTests.cs @@ -1,5 +1,6 @@ using System.Net; using System.Text.RegularExpressions; +using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.Extensions.DependencyInjection; @@ -157,6 +158,81 @@ public async Task An_existing_server_without_the_marker_gets_it_the_first_time_t } } + private WebApplicationFactory ProductionFactory(bool allowInsecureCookies = false) => + new WebApplicationFactory().WithWebHostBuilder(b => + { + Directory.CreateDirectory(_root); + b.UseEnvironment("Production"); + b.UseSetting("ConnectionStrings:DefaultConnection", $"DataSource={Path.Combine(_root, "prod.db")}"); + b.UseSetting("Queueify:DataDir", Path.Combine(_root, "prod-users")); + if (allowInsecureCookies) b.UseSetting("Queueify:AllowInsecureCookies", "true"); + }); + + // A secure cookie is not stored by a client talking http, so the test hands it back by hand, like a browser behind the proxy would. + private static HttpClient PlainHttpClient(WebApplicationFactory factory) => + factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false, HandleCookies = false, BaseAddress = new Uri("http://localhost") }); + + private static void SendBack(HttpClient client, IEnumerable setCookies) => + client.DefaultRequestHeaders.Add("Cookie", string.Join("; ", setCookies.Select(c => c.Split(';')[0]))); + + private static async Task> CookiesSetBySigningUpOverPlainHttpAsync(WebApplicationFactory factory) + { + var client = PlainHttpClient(factory); + var cookies = new List(); + var page = await client.GetAsync("/Account/Register", TestContext.Current.CancellationToken); + cookies.AddRange(page.Headers.TryGetValues("Set-Cookie", out var first) ? first : []); + SendBack(client, cookies); + var token = Token().Match(await page.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)).Groups[1].Value; + var signUp = await client.PostAsync("/Account/Register", new FormUrlEncodedContent(new Dictionary + { + ["__RequestVerificationToken"] = token, ["_handler"] = "register", ["Input.Email"] = "owner@example.com", + ["Input.Password"] = "Passw0rd!x", ["Input.ConfirmPassword"] = "Passw0rd!x", + }), TestContext.Current.CancellationToken); + cookies.AddRange(signUp.Headers.TryGetValues("Set-Cookie", out var second) ? second : []); + return cookies; + } + + [Fact] + public async Task In_production_the_sign_in_and_antiforgery_cookies_are_secure_even_when_the_proxy_hides_https() + { + using var factory = ProductionFactory(); + var cookies = await CookiesSetBySigningUpOverPlainHttpAsync(factory); + + var session = Assert.Single(cookies, c => c.StartsWith(".AspNetCore.Identity.Application=", StringComparison.Ordinal)); + var antiforgery = Assert.Single(cookies, c => c.StartsWith(".AspNetCore.Antiforgery.")); + Assert.Contains("secure", session, StringComparison.OrdinalIgnoreCase); + Assert.Contains("secure", antiforgery, StringComparison.OrdinalIgnoreCase); + Assert.Contains("httponly", session, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task A_server_kept_on_plain_http_on_purpose_can_say_so() + { + using var factory = ProductionFactory(allowInsecureCookies: true); + var cookies = await CookiesSetBySigningUpOverPlainHttpAsync(factory); + + Assert.DoesNotContain(cookies, c => c.Contains("secure", StringComparison.OrdinalIgnoreCase)); + } + + [Fact] + public async Task The_language_and_theme_cookies_are_secure_in_production_too() + { + using var factory = ProductionFactory(); + var client = PlainHttpClient(factory); + var login = await client.GetAsync("/Account/Login", TestContext.Current.CancellationToken); + SendBack(client, login.Headers.GetValues("Set-Cookie")); + var token = Token().Match(await login.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)).Groups[1].Value; + + var response = await client.PostAsync("/prefs", new FormUrlEncodedContent(new Dictionary + { + ["__RequestVerificationToken"] = token, ["language"] = "es", ["theme"] = "dark", + }), TestContext.Current.CancellationToken); + + var set = response.Headers.GetValues("Set-Cookie").Where(c => c.StartsWith("qlang=") || c.StartsWith("qtheme=")).ToList(); + Assert.Equal(2, set.Count); + Assert.All(set, c => Assert.Contains("secure", c, StringComparison.OrdinalIgnoreCase)); + } + [Fact] public async Task Two_simultaneous_first_registrations_make_one_owner() { diff --git a/Queueify.Web/Program.cs b/Queueify.Web/Program.cs index 53827e8..74f33ec 100644 --- a/Queueify.Web/Program.cs +++ b/Queueify.Web/Program.cs @@ -46,6 +46,7 @@ builder.Services.AddQueueifySync(); var app = builder.Build(); +app.UseQueueifySecureScheme(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) diff --git a/Queueify.Web/Services/QueueifyUi.cs b/Queueify.Web/Services/QueueifyUi.cs index 2a6f760..f49c694 100644 --- a/Queueify.Web/Services/QueueifyUi.cs +++ b/Queueify.Web/Services/QueueifyUi.cs @@ -26,11 +26,25 @@ public static class QueueifyUi "font-src 'self' data:; connect-src 'self' ws: wss:; manifest-src 'self'; worker-src 'self'; " + "object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'"; + /// + /// Cookies carry the Secure flag everywhere except Development, whatever the proxy forwards: behind a TLS-terminating + /// proxy that is not a trusted hop the app sees plain http and would otherwise issue cookies a plain-http hit could read. + /// A server that really is kept on plain http (a home LAN) says so with Queueify:AllowInsecureCookies. + /// + public static bool SecureCookies(IConfiguration config, IHostEnvironment env) => + !env.IsDevelopment() && !config.GetValue("Queueify:AllowInsecureCookies", false); + public static WebApplicationBuilder AddQueueifyUi(this WebApplicationBuilder builder) { var services = builder.Services; services.AddFluentUIComponents(); + if (SecureCookies(builder.Configuration, builder.Environment)) + { + services.PostConfigureAll(o => o.Cookie.SecurePolicy = CookieSecurePolicy.Always); + services.AddAntiforgery(o => o.Cookie.SecurePolicy = CookieSecurePolicy.Always); + } + services.AddHttpClient(HttpCatalogs.ClientName, c => { c.Timeout = TimeSpan.FromSeconds(20); // ENGINEERING.md: explicit 20 s for HTTP @@ -51,6 +65,17 @@ public static WebApplicationBuilder AddQueueifyUi(this WebApplicationBuilder bui return builder; } + /// + /// Outside Development (unless Queueify:AllowInsecureCookies) every request counts as https: TLS is meant to end at a + /// reverse proxy, and the antiforgery and sign-in cookies insist on a secure request. Must run before anything that reads the scheme. + /// + public static WebApplication UseQueueifySecureScheme(this WebApplication app) + { + if (SecureCookies(app.Configuration, app.Environment)) + app.Use((context, next) => { context.Request.Scheme = "https"; return next(context); }); + return app; + } + public static WebApplication MapQueueifyUi(this WebApplication app) { // Each request answers in the language of the cookie, or of the browser; circuits do the same @@ -76,7 +101,7 @@ public static WebApplication MapQueueifyUi(this WebApplication app) // [FromForm] parameters make the endpoint require the antiforgery token, like every other form post. app.MapPost("/prefs", (HttpContext context, [FromForm] string? language, [FromForm] string? theme, [FromForm] string? returnUrl) => { - var options = new CookieOptions { MaxAge = TimeSpan.FromDays(365), SameSite = SameSiteMode.Lax, IsEssential = true, Secure = context.Request.IsHttps, HttpOnly = true }; + var options = new CookieOptions { MaxAge = TimeSpan.FromDays(365), SameSite = SameSiteMode.Lax, IsEssential = true, Secure = context.Request.IsHttps || SecureCookies(context.RequestServices.GetRequiredService(), context.RequestServices.GetRequiredService()), HttpOnly = true }; if (language is "en" or "es") context.Response.Cookies.Append(Prefs.LanguageCookie, language, options); if (theme is "light" or "dark" or "system") context.Response.Cookies.Append(Prefs.ThemeCookie, theme, options); // A signed-in account keeps its choice for every browser it uses; Settings shows and changes the same values. diff --git a/SECURITY.md b/SECURITY.md index 519a89b..bcb56ad 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -55,7 +55,7 @@ Photo decoding uses SkiaSharp (MIT), a native library: it is fed only bytes that | --- | --- | --- | | Sign-in | Guessing passwords | ASP.NET Core Identity with passkeys; failed passwords count towards lockout (5 tries, then locked for 5 minutes). Not covered: a global rate limit in front of the server, so put the site behind a reverse proxy that has one. | | Registration | A stranger creating an account on a public server | The first account owns the server (checked and written under one lock, so two first sign-ups can't both win); after that registration is closed unless `Queueify:AllowRegistration` is `true`. A fresh public server belongs to whoever registers first: register before exposing it. The first account is remembered in an `owner-exists` marker in the data folder, so deleting the last account (or losing `identity.db`) does not reopen registration; to start over on purpose, delete the marker and the account database together. | -| Cross-site requests | Forged form posts (sign out, language, delete) | Antiforgery tokens on every form post, including `/prefs` and sign out; cookies are `SameSite=Lax`, `HttpOnly`, and `Secure` over HTTPS. | +| Cross-site requests | Forged form posts (sign out, language, delete) | Antiforgery tokens on every form post, including `/prefs` and sign out; cookies are `SameSite=Lax` and `HttpOnly`, and outside Development always `Secure` (sign-in, antiforgery, language and theme): the server then treats every request as https, so TLS must end at a reverse proxy in front of it. A server kept on plain http on purpose (a home network) sets `Queueify:AllowInsecureCookies` to `true`. | | Page content | Script injection, clickjacking, tracking pixels | Razor encodes everything; no raw HTML is rendered. Every response carries a Content-Security-Policy (own scripts only, `frame-ancestors 'none'`, `object-src 'none'`, forms only to the site; album covers may come from any HTTPS host and are fetched without a referrer), `X-Content-Type-Options: nosniff` and `Referrer-Policy: no-referrer`. | | Other users' data | Seeing or changing another queue | Each user's queue and settings live in a folder named by their account id (never by anything the browser sends); ids are checked against path tricks. | | Spotify/Tidal keys | Leaking to the browser, or abuse of the server's address | Keys are read only on the server and never rendered; each user gets 30 catalog searches a minute so one account can't get the server's address blocked. The keys sit unencrypted in the user's `settings.json` on the server's disk: protect the data folder. | From fd22590b2e5370dd263e72204aa8d428ddef10a2 Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:55:10 -0300 Subject: [PATCH 46/66] test(core): pin matcher scores and merge rule, drop sleeps Exact scores for the year bands, single penalty and typo edges, the twelve-result cap and the same-title merge rule. A title with no letters or digits no longer merges unrelated albums. Sleeps that only waited for the clock are spin-waits on the stamp itself; restated constants are gone. Co-Authored-By: Claude Sonnet 5.5 --- Queueify.Core/Services/Matcher.cs | 3 +- Queueify.Tests/BacklogStoreTests.cs | 2 +- Queueify.Tests/CloudSyncTests.cs | 2 +- Queueify.Tests/MatcherScoringTests.cs | 141 ++++++++++++++++++++++++++ Queueify.Tests/MatcherTests.cs | 1 + Queueify.Tests/ServerSyncTests.cs | 6 -- 6 files changed, 146 insertions(+), 9 deletions(-) create mode 100644 Queueify.Tests/MatcherScoringTests.cs diff --git a/Queueify.Core/Services/Matcher.cs b/Queueify.Core/Services/Matcher.cs index 7b6ce05..58f6b54 100644 --- a/Queueify.Core/Services/Matcher.cs +++ b/Queueify.Core/Services/Matcher.cs @@ -60,7 +60,8 @@ public static List Combine(IEnumerable spotify, IEnumer var results = new List(); foreach (var m in all.OrderByDescending(m => m.Score)) { - var titleKey = Normalize(m.Title); + // A title with no letters or digits ("???") normalizes to nothing: keep what was typed, or every such album would merge. + var titleKey = Normalize(m.Title) is { Length: > 0 } t ? t : m.Title.Trim().ToLowerInvariant(); var artistKey = m.Artists.Count > 0 ? Normalize(m.Artists[0]) : ""; var existing = results.FirstOrDefault(r => r.TitleKey == titleKey && (r.ArtistKey == artistKey || r.ArtistKey.Length == 0 || artistKey.Length == 0)); diff --git a/Queueify.Tests/BacklogStoreTests.cs b/Queueify.Tests/BacklogStoreTests.cs index e34258e..4d7d058 100644 --- a/Queueify.Tests/BacklogStoreTests.cs +++ b/Queueify.Tests/BacklogStoreTests.cs @@ -75,7 +75,7 @@ public void MarkUploaded_KeepsChangesMadeWhileUploading() store.Insert(item); var uploaded = store.FindByUid(item.Uid)!; - Thread.Sleep(2); + SpinWait.SpinUntil(() => BacklogStore.Now() > uploaded.UpdatedAt); // the edit below must carry a later stamp item.Rating = 5; store.Update(item); store.MarkUploaded(uploaded); diff --git a/Queueify.Tests/CloudSyncTests.cs b/Queueify.Tests/CloudSyncTests.cs index 0e3f7ca..ca749e8 100644 --- a/Queueify.Tests/CloudSyncTests.cs +++ b/Queueify.Tests/CloudSyncTests.cs @@ -231,7 +231,7 @@ public async Task Conflict_TheNewerEditWinsOnBothPcs() var onA = a.FindByUid(vasos.Uid)!; onA.Source = "Rolling Stone #12"; a.Update(onA); - await Task.Delay(20); + SpinWait.SpinUntil(() => BacklogStore.Now() > onA.UpdatedAt); // the second edit must carry a later stamp var onB = b.FindByUid(vasos.Uid)!; onB.Source = "Inrockuptibles #3"; b.Update(onB); diff --git a/Queueify.Tests/MatcherScoringTests.cs b/Queueify.Tests/MatcherScoringTests.cs new file mode 100644 index 0000000..ac7cd70 --- /dev/null +++ b/Queueify.Tests/MatcherScoringTests.cs @@ -0,0 +1,141 @@ +using Queueify.Models; +using Queueify.Services; + +namespace Queueify.Tests; + +/// Exact scores and the merge rule of , so a changed weight or band is noticed. +public class MatcherScoringTests +{ + private static AlbumMatch Match(string title, string[] artists, int? year = null, string type = "album", + MusicService service = MusicService.Spotify, string? id = null) => + new() { Service = service, Id = id ?? service + ":" + title, Title = title, Artists = artists, Year = year, AlbumType = type }; + + // "artaud spinetta" fully explains title and artist, so only the year and the type move the score: + // 0.4 + 0.25 + 0.25 = 0.9 plus 0.1 times the year score. + private static double Score(int? queryYear, int? albumYear, string type = "album") => + Matcher.ScoreQuery("artaud spinetta", queryYear, Match("Artaud", ["Spinetta"], albumYear, type)); + + [Fact] + public void Without_a_year_in_the_query_the_year_counts_half() + => Assert.Equal(0.95, Score(null, 1973), 10); + + [Theory] + [InlineData(1973, 1.0)] // same year + [InlineData(1974, 1.0)] // one off: magazines date by review + [InlineData(1972, 1.0)] + [InlineData(1975, 0.95)] // two or three off: half + [InlineData(1976, 0.95)] + [InlineData(1977, 0.9)] // four or more: nothing, but never a veto + [InlineData(1900, 0.9)] + public void The_year_band_moves_the_score_by_up_to_a_tenth(int albumYear, double expected) + => Assert.Equal(expected, Score(1973, albumYear), 10); + + [Fact] + public void An_album_with_no_year_counts_half_when_the_query_has_one() + => Assert.Equal(0.95, Score(1973, null), 10); + + [Theory] + [InlineData("single", 0.90)] + [InlineData("SINGLE", 0.90)] + [InlineData("album", 0.95)] + [InlineData("compilation", 0.95)] + public void A_single_scores_a_little_below_the_album(string type, double expected) + => Assert.Equal(expected, Score(null, 1973, type), 10); + + [Fact] + public void The_weights_are_title_artist_and_unexplained_words() + { + // Naming only the title: title 0.4, no artist, the one typed word is explained (0.25), year unknown (0.05). + var titleOnly = Matcher.ScoreQuery("artaud", null, Match("Artaud", ["Spinetta"])); + var artistOnly = Matcher.ScoreQuery("spinetta", null, Match("Artaud", ["Spinetta"])); + var nothing = Matcher.ScoreQuery("zzzzzz", null, Match("Artaud", ["Spinetta"])); + + Assert.Equal(0.4 + 0.25 * 0 + 0.25 * 1 + 0.05, titleOnly, 10); + Assert.Equal(0.25 + 0.25 + 0.05, artistOnly, 10); + Assert.Equal(0.05, nothing, 10); + } + + [Theory] + [InlineData("abcd", "abce", true)] // 4 letters: one typo is fine + [InlineData("abc", "abd", false)] // under 4 letters: exact only + [InlineData("abcd", "abcdef", false)] // too different in length + [InlineData("abcdefg", "abcdefx", true)] // 7 letters: one typo + [InlineData("abcdefg", "abcdexy", false)] // 7 letters: two typos are too many + [InlineData("abcdefgh", "abcdefxy", true)] // 8 letters or more: two typos + [InlineData("abcdefgh", "abcdexyz", false)] // three are too many + public void Typo_tolerance_has_these_edges(string typed, string title, bool same) + { + var score = Matcher.ScoreQuery(typed, null, Match(title, ["Zed"])); + + Assert.Equal(same ? 0.7 : 0.05, score, 10); + } + + [Fact] + public void Results_are_best_first_and_at_most_twelve() + { + var spotify = Enumerable.Range(0, 15).Select(i => Match("Album " + (char)('a' + i) + "x" + i, ["Artist " + i], 2000 + i)).ToArray(); + + var results = Matcher.Combine(spotify, [], "album"); + + Assert.Equal(12, results.Count); + Assert.Equal(results.OrderByDescending(r => r.Score), results); + } + + [Fact] + public void The_results_carry_the_scores_Combine_gave_the_matches() + { + var spotify = Match("Artaud", ["Spinetta"], 1973); + + var results = Matcher.Combine([spotify], [], "spinetta artaud 1973"); + + Assert.Equal(spotify.Score, results[0].Score); + Assert.True(spotify.Score > 0.9); + } + + // ───────────── the same album on both services ───────────── + + [Fact] + public void The_same_title_and_artist_on_both_services_is_one_row_with_both_links() + { + var results = Matcher.Combine( + [Match("Artaud", ["Spinetta"], 1973)], + [Match("Artaud (Remastered)", ["Spinetta"], 1973, service: MusicService.Tidal)], "spinetta artaud"); + + var one = Assert.Single(results); + Assert.NotNull(one.Spotify); + Assert.NotNull(one.Tidal); + } + + [Fact] + public void A_result_with_no_artist_joins_the_same_title_from_the_other_service() + { + var results = Matcher.Combine( + [Match("Greatest Hits", ["Queen"])], + [Match("Greatest Hits", [], service: MusicService.Tidal)], "queen greatest hits"); + + var one = Assert.Single(results); + Assert.NotNull(one.Spotify); + Assert.NotNull(one.Tidal); + } + + [Fact] + public void The_same_title_by_different_artists_stays_two_rows() + { + var results = Matcher.Combine( + [Match("Greatest Hits", ["Queen"])], + [Match("Greatest Hits", ["ABBA"], service: MusicService.Tidal)], "greatest hits"); + + Assert.Equal(2, results.Count); + } + + [Fact] + public void Titles_with_no_letters_or_digits_are_not_merged_by_mistake() + { + // Both normalize to nothing, so their keys are equal; they are still different albums. + var results = Matcher.Combine( + [Match("???", ["Artist One"])], + [Match("!!!", [], service: MusicService.Tidal)], "artist"); + + Assert.Equal(2, results.Count); + } +} diff --git a/Queueify.Tests/MatcherTests.cs b/Queueify.Tests/MatcherTests.cs index 5a2ab69..edfe305 100644 --- a/Queueify.Tests/MatcherTests.cs +++ b/Queueify.Tests/MatcherTests.cs @@ -22,6 +22,7 @@ public void Combine_FindsAlbumsNamedAfterAYear(string raw, string title, string { var results = Search(raw, [Spotify(title, artist, released), Spotify("Greatest Hits", artist, released - 3)], []); + Assert.NotEmpty(results); Assert.Equal(title, results[0].Title); Assert.True(results[0].Score >= 0.8, $"score {results[0].Score}"); } diff --git a/Queueify.Tests/ServerSyncTests.cs b/Queueify.Tests/ServerSyncTests.cs index 19f9fa8..f7bec26 100644 --- a/Queueify.Tests/ServerSyncTests.cs +++ b/Queueify.Tests/ServerSyncTests.cs @@ -373,12 +373,6 @@ public async Task Repeats_until_the_server_has_nothing_more_and_sends_at_most_10 Assert.Empty(store.LoadDirty()); } - [Fact] - public void The_default_batch_is_the_contracts_1000() - { - Assert.Equal(1000, ServerSync.MaxBatch); - } - [Fact] public async Task Downloads_that_arrive_in_several_rounds_are_all_applied() { From fe199aff6b9c96d4d301e2b0cc6963b8b7fd602d Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:56:34 -0300 Subject: [PATCH 47/66] refactor(app): use QueueView for filter, saved lookup and typed albums The window kept its own copies, which had drifted (sort culture). The queue now sorts by the app language like the web pages do. Co-Authored-By: Claude Sonnet 5.5 --- Queueify/MainWindow.xaml.cs | 38 ++++++------------------------------- 1 file changed, 6 insertions(+), 32 deletions(-) diff --git a/Queueify/MainWindow.xaml.cs b/Queueify/MainWindow.xaml.cs index cc968a9..6ede494 100644 --- a/Queueify/MainWindow.xaml.cs +++ b/Queueify/MainWindow.xaml.cs @@ -406,12 +406,7 @@ private void ShowAddWithoutLink(string raw) private string? QueueStateOf(AlbumResult r) { - var titleKey = Matcher.Normalize(r.Title); - var artistKey = Matcher.Normalize(r.Artist); - var saved = _all.FirstOrDefault(i => - (r.Spotify != null && i.SpotifyId == r.Spotify.Id) || - (r.Tidal != null && i.TidalId == r.Tidal.Id) || - (Matcher.Normalize(i.Album) == titleKey && Matcher.Normalize(i.Artist) == artistKey)); + var saved = QueueView.FindSaved(r, _all); return saved == null ? null : saved.IsListened ? Loc.T("search.state.listened") : Loc.T("search.state.queued"); } @@ -445,17 +440,8 @@ private void AddResult(AlbumResult r) private void OnAddWithoutLink(object sender, RoutedEventArgs e) { - var (text, year) = Matcher.ExtractYear(SearchBox.Text.Trim()); - if (text.Length == 0) return; - - // "Artist - Album" is split; anything else is kept whole as the album line. - var parts = text.Split([" - ", " – ", " — "], 2, StringSplitOptions.TrimEntries); - AddItem(new BacklogItem - { - Artist = parts.Length == 2 ? parts[0] : "", - Album = parts.Length == 2 ? parts[1] : text, - Year = year, - }); + if (QueueView.ParseTyped(SearchBox.Text) is not { } typed) return; + AddItem(new BacklogItem { Artist = typed.Artist, Album = typed.Album, Year = typed.Year }); } private void AddItem(BacklogItem item) @@ -500,20 +486,8 @@ private void RefreshQueue() bool queuePage = _page is Page.Queue or Page.Listened; bool listened = _page == Page.Listened; - var filter = Matcher.Normalize(FilterBox.Text); - - var items = _all - .Where(i => i.IsListened == listened) - .Where(i => filter.Length == 0 || Matcher.Normalize($"{i.Artist} {i.Album} {i.Source} {i.Year}").Contains(filter)); - items = _ui.Sort switch - { - "newest" => items.OrderByDescending(i => i.AddedAt), - "artist" => items.OrderBy(i => i.Artist, StringComparer.CurrentCultureIgnoreCase).ThenBy(i => i.Year), - "year" => items.OrderBy(i => i.Year ?? int.MaxValue).ThenBy(i => i.Artist), - "source" => items.OrderBy(i => i.Source ?? "￿", StringComparer.CurrentCultureIgnoreCase).ThenBy(i => i.AddedAt), - _ => listened ? items.OrderByDescending(i => i.ListenedAt) : items.OrderBy(i => i.AddedAt), - }; - var list = items.ToList(); + bool filtering = Matcher.Normalize(FilterBox.Text).Length > 0; + var list = QueueView.Apply(_all, listened, FilterBox.Text, _ui.Sort); QueueList.ItemsSource = _ui.CoverView ? null : Items(list); QueueGrid.ItemsSource = _ui.CoverView ? Items(list) : null; @@ -549,7 +523,7 @@ private void RefreshQueue() EmptyState.Visibility = list.Count == 0 ? Visibility.Visible : Visibility.Collapsed; (EmptyIcon.Glyph, EmptyTitle.Text, EmptyText.Text) = - filter.Length > 0 ? ("", Loc.T("empty.filter.title"), Loc.T("empty.filter.text")) + filtering ? ("", Loc.T("empty.filter.title"), Loc.T("empty.filter.text")) : listened ? ("", Loc.T("empty.listened.title"), Loc.T("empty.listened.text")) : ("", Loc.T("empty.queue.title"), Loc.T("empty.queue.text")); } From 6ea5b21513d9fcf3ef869c47d7957fcfd35ee77e Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:58:48 -0300 Subject: [PATCH 48/66] refactor(core): SyncSetup tries a connection on a copy of the settings The setup dialog's connect logic moves to Core with unit tests (it had none). While it runs, the debounced sync is stopped and SyncNowAsync declines, so an older run cannot clear the dirty marks the trial needs. Co-Authored-By: Claude Sonnet 5.5 --- Queueify.Core/Services/ISyncProvider.cs | 2 +- Queueify.Core/Services/SyncSetup.cs | 46 +++++++++ Queueify.Tests/SyncSetupTests.cs | 130 ++++++++++++++++++++++++ Queueify/MainWindow.xaml.cs | 33 +++--- 4 files changed, 193 insertions(+), 18 deletions(-) create mode 100644 Queueify.Core/Services/SyncSetup.cs create mode 100644 Queueify.Tests/SyncSetupTests.cs diff --git a/Queueify.Core/Services/ISyncProvider.cs b/Queueify.Core/Services/ISyncProvider.cs index 6ffb04a..189646e 100644 --- a/Queueify.Core/Services/ISyncProvider.cs +++ b/Queueify.Core/Services/ISyncProvider.cs @@ -13,7 +13,7 @@ public interface ISyncProvider public static class SyncProviders { - public static ISyncProvider For(SyncKind kind, CloudSync cloud, ServerSync web) => kind switch + public static ISyncProvider For(SyncKind kind, ISyncProvider cloud, ISyncProvider web) => kind switch { SyncKind.Web => web, SyncKind.Cloud => cloud, diff --git a/Queueify.Core/Services/SyncSetup.cs b/Queueify.Core/Services/SyncSetup.cs new file mode 100644 index 0000000..16c3c53 --- /dev/null +++ b/Queueify.Core/Services/SyncSetup.cs @@ -0,0 +1,46 @@ +using Queueify.Models; + +namespace Queueify.Services; + +/// Where the sync setup dialog connects this PC: a Queueify web server, or a Firestore queue (created or joined). +public sealed record SyncTarget(SyncKind Kind, string Where, string Secret, bool Joining) +{ + public static SyncTarget Web(string serverUrl, string token) => new(SyncKind.Web, serverUrl, token, true); + + public static SyncTarget JoinCloud(string projectId, string queueKey) => new(SyncKind.Cloud, projectId, queueKey, true); + + public static SyncTarget CreateCloud(string projectId, string queueKey) => new(SyncKind.Cloud, projectId, queueKey, false); +} + +/// Connecting a PC to an online queue: tried on a copy of the settings, so a failure leaves nothing half-connected. +public static class SyncSetup +{ + /// + /// Connects a copy of to and runs the first sync with it. Returns + /// the connected settings for the caller to keep; throws whatever the sync throws, and then + /// has not been touched. , if one is still finishing, ends first: its "uploaded" marks + /// would otherwise undo the "everything is dirty" below. + /// + public static async Task TryConnectAsync( + BacklogStore store, AppSettings current, SyncTarget target, ISyncProvider cloud, ISyncProvider web, + Task? previousSync, CancellationToken ct) + { + var trial = current.Clone(); + if (target.Kind == SyncKind.Web) trial.ConnectWeb(target.Where, target.Secret); + else trial.ConnectCloud(target.Where, target.Secret); + + // Creating: this PC's keys go up. Joining: the online queue's keys win (or this PC's, if the queue has none yet). + trial.SharedSettingsUpdatedAt = target.Joining ? null + : trial.SpotifyConfigured || trial.TidalConfigured ? BacklogStore.Now() : null; + + if (previousSync != null) + { + try { await previousSync; } + catch (Exception) { /* that sync reported its own failure when it ran; it only matters that it has ended */ } + } + // Albums synced to an earlier queue are marked clean; this queue needs all of them. + store.MarkAllDirty(); + await Task.Run(() => SyncProviders.For(trial.ActiveSync, cloud, web).SyncAsync(store, trial, ct), ct); + return trial; + } +} diff --git a/Queueify.Tests/SyncSetupTests.cs b/Queueify.Tests/SyncSetupTests.cs new file mode 100644 index 0000000..03d39f2 --- /dev/null +++ b/Queueify.Tests/SyncSetupTests.cs @@ -0,0 +1,130 @@ +using Microsoft.Data.Sqlite; +using Queueify.Models; +using Queueify.Services; + +namespace Queueify.Tests; + +/// Connecting to an online queue is tried on a copy of the settings (nothing half-connected on failure). +public sealed class SyncSetupTests : IDisposable +{ + private readonly string _dir = Path.Combine(Path.GetTempPath(), "queueify-tests", Guid.NewGuid().ToString("N")); + private BacklogStore NewStore() => new(Path.Combine(_dir, Guid.NewGuid().ToString("N") + ".db")); + + public void Dispose() + { + SqliteConnection.ClearAllPools(); + if (Directory.Exists(_dir)) Directory.Delete(_dir, true); + } + + private sealed class Recorder(Exception? failWith = null) : ISyncProvider + { + public readonly List<(AppSettings Settings, int DirtyAtStart)> Calls = []; + + public Task SyncAsync(BacklogStore store, AppSettings settings, CancellationToken ct) + { + Calls.Add((settings, store.LoadDirty().Count)); + return failWith == null ? Task.FromResult(new SyncResult(0, 0, false)) : Task.FromException(failWith); + } + } + + private static BacklogItem Item(string album) => new() { Artist = "A", Album = album, AddedAt = DateTime.Now }; + + [Fact] + public async Task A_cloud_connection_syncs_everything_with_the_new_queue_and_leaves_the_live_settings_alone() + { + var store = NewStore(); + store.Insert(Item("One")); + store.MarkUploaded(store.LoadDirty().Single()); // synced to an earlier queue: clean + var live = new AppSettings(); + Recorder cloud = new(), web = new(); + + var trial = await SyncSetup.TryConnectAsync(store, live, SyncTarget.JoinCloud("proj-1a2b3", "abc"), cloud, web, null, default); + + Assert.Equal(SyncKind.Cloud, trial.ActiveSync); + Assert.Equal(SyncKind.None, live.ActiveSync); + Assert.Same(trial, cloud.Calls.Single().Settings); + Assert.Empty(web.Calls); + Assert.Equal(1, cloud.Calls[0].DirtyAtStart); + } + + [Fact] + public async Task A_web_connection_uses_the_web_provider() + { + Recorder cloud = new(), web = new(); + + var trial = await SyncSetup.TryConnectAsync(NewStore(), new AppSettings(), SyncTarget.Web("https://q.example.com", "qw_token"), cloud, web, null, default); + + Assert.Equal(SyncKind.Web, trial.ActiveSync); + Assert.Equal(("https://q.example.com", "qw_token"), (trial.WebServerUrl, trial.WebToken)); + Assert.Empty(cloud.Calls); + Assert.Single(web.Calls); + } + + [Fact] + public async Task A_failed_first_sync_throws_and_nothing_is_connected() + { + var live = new AppSettings(); + Recorder cloud = new(new SyncException("no")), web = new(); + + await Assert.ThrowsAsync(() => + SyncSetup.TryConnectAsync(NewStore(), live, SyncTarget.JoinCloud("proj-1a2b3", "abc"), cloud, web, null, default)); + + Assert.False(live.SyncConfigured); + } + + [Theory] + [InlineData(false, true)] // creating a queue with keys on this PC: the keys go up + [InlineData(true, false)] // joining: the queue's keys win + public async Task Keys_go_up_only_when_creating_a_queue(bool joining, bool keysStamped) + { + var live = new AppSettings { SpotifyClientId = "id", SpotifyClientSecret = "secret" }; + Recorder cloud = new(), web = new(); + var target = joining ? SyncTarget.JoinCloud("proj-1a2b3", "abc") : SyncTarget.CreateCloud("proj-1a2b3", "abc"); + + var trial = await SyncSetup.TryConnectAsync(NewStore(), live, target, cloud, web, null, default); + + Assert.Equal(keysStamped, trial.SharedSettingsUpdatedAt != null); + } + + [Fact] + public async Task Creating_a_queue_without_keys_stamps_nothing() + { + Recorder cloud = new(), web = new(); + + var trial = await SyncSetup.TryConnectAsync(NewStore(), new AppSettings(), SyncTarget.CreateCloud("proj-1a2b3", "abc"), cloud, web, null, default); + + Assert.Null(trial.SharedSettingsUpdatedAt); + } + + [Fact] + public async Task A_sync_still_finishing_ends_before_everything_is_marked_for_upload() + { + var store = NewStore(); + store.Insert(Item("One")); + store.MarkUploaded(store.LoadDirty().Single()); + var previous = new TaskCompletionSource(); + Recorder cloud = new(), web = new(); + + var connecting = SyncSetup.TryConnectAsync(store, new AppSettings(), SyncTarget.JoinCloud("proj-1a2b3", "abc"), cloud, web, previous.Task, default); + await Task.Delay(100, TestContext.Current.CancellationToken); // nothing may happen while the earlier sync is running + Assert.False(connecting.IsCompleted); + Assert.Empty(cloud.Calls); + Assert.Empty(store.LoadDirty()); + + previous.SetResult(); + await connecting; + + Assert.Equal(1, cloud.Calls.Single().DirtyAtStart); + } + + [Fact] + public async Task An_earlier_sync_that_failed_does_not_stop_the_connection() + { + var failed = Task.FromException(new SyncException("old failure")); + Recorder cloud = new(), web = new(); + + var trial = await SyncSetup.TryConnectAsync(NewStore(), new AppSettings(), SyncTarget.JoinCloud("proj-1a2b3", "abc"), cloud, web, failed, default); + + Assert.True(trial.SyncConfigured); + } +} diff --git a/Queueify/MainWindow.xaml.cs b/Queueify/MainWindow.xaml.cs index 6ede494..c60820f 100644 --- a/Queueify/MainWindow.xaml.cs +++ b/Queueify/MainWindow.xaml.cs @@ -1158,6 +1158,7 @@ private void ScheduleSync() private Task? _syncTask; private Task? _followUpSync; + private bool _syncSetupRunning; // the setup dialog is trying a connection: no other sync may run /// /// Downloads other PCs' changes and uploads this PC's. Returns an error message, or null when it @@ -1167,7 +1168,7 @@ private void ScheduleSync() /// private Task SyncNowAsync() { - if (!_settings.SyncConfigured) return Task.FromResult(null); + if (!_settings.SyncConfigured || _syncSetupRunning) return Task.FromResult(null); if (_syncTask is { IsCompleted: false } running) return _followUpSync ??= AfterAsync(running); return _syncTask = RunSyncAsync(); @@ -1378,38 +1379,36 @@ void ShowOnly(StackPanel shown) key = CloudSync.NewQueueKey(); } - // Try the connection on a copy; the live settings only change if the first sync works. - var trial = _settings.Clone(); - if (toWeb) trial.ConnectWeb(webUrl, webToken); - else trial.ConnectCloud(project, key); - // Creating: this PC's keys go up. Joining: the online queue's keys win (or this PC's, - // if the queue has none yet). - trial.SharedSettingsUpdatedAt = joined ? null - : trial.SpotifyConfigured || trial.TidalConfigured ? BacklogStore.Now() : null; + SyncTarget target = toWeb ? SyncTarget.Web(webUrl, webToken) + : joined ? SyncTarget.JoinCloud(project, key) + : SyncTarget.CreateCloud(project, key); progress.Visibility = Visibility.Visible; error.IsOpen = false; d.IsPrimaryButtonEnabled = false; string? problem = null; + AppSettings? trial = null; + // A debounced sync of the old queue must not run between "mark everything" and the first sync here. + _syncDebounce.Stop(); + _syncSetupRunning = true; try { - // A sync for the previous queue may still be finishing; let it end first, or its - // "uploaded" marks could undo the next line. - if (_syncTask is { } previous) await previous; - // Albums synced to an earlier queue are marked clean; this queue needs all of them. - _store.MarkAllDirty(); - await Task.Run(() => SyncProviders.For(trial.ActiveSync, _cloud, _web).SyncAsync(_store, trial, CancellationToken.None)); + trial = await SyncSetup.TryConnectAsync(_store, _settings, target, _cloud, _web, _syncTask, CancellationToken.None); } catch (Exception ex) { problem = DescribeSyncError(ex); } + finally + { + _syncSetupRunning = false; + } progress.Visibility = Visibility.Collapsed; d.IsPrimaryButtonEnabled = true; - if (problem != null) + if (trial == null) { - Fail(problem); + Fail(problem!); return; } From c4ce4068af056e471c9468882d6a7854169a655c Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:59:42 -0300 Subject: [PATCH 49/66] refactor(app): split MainWindow into partial classes by area Photo, Sync, Updates and Settings move to MainWindow.*.cs unchanged. Co-Authored-By: Claude Sonnet 5.5 --- Queueify/MainWindow.Photo.cs | 403 +++++++++ Queueify/MainWindow.Settings.cs | 427 +++++++++ Queueify/MainWindow.Sync.cs | 446 ++++++++++ Queueify/MainWindow.Updates.cs | 317 +++++++ Queueify/MainWindow.xaml.cs | 1484 ------------------------------- 5 files changed, 1593 insertions(+), 1484 deletions(-) create mode 100644 Queueify/MainWindow.Photo.cs create mode 100644 Queueify/MainWindow.Settings.cs create mode 100644 Queueify/MainWindow.Sync.cs create mode 100644 Queueify/MainWindow.Updates.cs diff --git a/Queueify/MainWindow.Photo.cs b/Queueify/MainWindow.Photo.cs new file mode 100644 index 0000000..515d884 --- /dev/null +++ b/Queueify/MainWindow.Photo.cs @@ -0,0 +1,403 @@ +using System.Globalization; +using Microsoft.UI.Dispatching; +using Microsoft.UI.Windowing; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Automation; +using Microsoft.UI.Xaml.Automation.Peers; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Input; +using Microsoft.UI.Xaml.Media; +using Microsoft.UI.Xaml.Media.Imaging; +using Queueify.Controls; +using Queueify.Models; +using Queueify.Services; +using Windows.ApplicationModel.DataTransfer; +using Windows.Graphics; +using Windows.Storage; +using Windows.Storage.Pickers; +using Windows.Storage.Streams; +using Windows.System; +using Windows.UI; +using DispatcherQueuePriority = Microsoft.UI.Dispatching.DispatcherQueuePriority; +using DispatcherQueueTimer = Microsoft.UI.Dispatching.DispatcherQueueTimer; + +namespace Queueify; + +public sealed partial class MainWindow +{ + // ───────────────────────── Magazine photo (OCR) ───────────────────────── + + private async void OnOpenPhoto(object sender, RoutedEventArgs e) + { + var picker = new FileOpenPicker { SuggestedStartLocation = PickerLocationId.PicturesLibrary }; + foreach (var ext in new[] { ".jpg", ".jpeg", ".png", ".bmp", ".webp", ".heic", ".tif", ".tiff" }) + picker.FileTypeFilter.Add(ext); + WinRT.Interop.InitializeWithWindow.Initialize(picker, WinRT.Interop.WindowNative.GetWindowHandle(this)); + + await GuardPhotoAsync(async () => + { + if (await picker.PickSingleFileAsync() is StorageFile file) + await LoadPhotoFromFileAsync(file); + }); + } + + /// + /// Photo files can be locked, cloud-only or unreadable, and the clipboard can be busy: show the + /// problem on the photo page instead of letting it crash the app. + /// + private async Task GuardPhotoAsync(Func work) + { + try + { + await work(); + } + catch (Exception ex) + { + GoTo(Page.Photo); + ShowOcrInfo(InfoBarSeverity.Error, Loc.F("photo.open_failed", ex.Message)); + } + } + + private void OnPastePhoto(object sender, RoutedEventArgs e) => _ = GuardPhotoAsync(() => PastePhotoAsync(reportEmpty: true)); + + private void OnPasteShortcut(KeyboardAccelerator sender, KeyboardAcceleratorInvokedEventArgs args) + { + // Text boxes keep their normal paste; anywhere else Ctrl+V loads an image. + if (FocusManager.GetFocusedElement(Root.XamlRoot) is TextBox or PasswordBox) return; + args.Handled = true; + _ = GuardPhotoAsync(() => PastePhotoAsync(reportEmpty: false)); + } + + private async Task PastePhotoAsync(bool reportEmpty) + { + var content = Clipboard.GetContent(); + if (content.Contains(StandardDataFormats.Bitmap)) + { + using var stream = await (await content.GetBitmapAsync()).OpenReadAsync(); + await LoadPhotoAsync(stream); + } + else if (content.Contains(StandardDataFormats.StorageItems) + && (await content.GetStorageItemsAsync()).OfType().FirstOrDefault() is { } file) + { + await LoadPhotoFromFileAsync(file); + } + else if (reportEmpty) + { + GoTo(Page.Photo); + ShowOcrInfo(InfoBarSeverity.Informational, Loc.T("photo.clipboard_empty")); + } + } + + private void OnPhotoDragOver(object sender, DragEventArgs e) + { + if (e.DataView.Contains(StandardDataFormats.StorageItems) || e.DataView.Contains(StandardDataFormats.Bitmap)) + { + e.AcceptedOperation = DataPackageOperation.Copy; + e.DragUIOverride.Caption = Loc.T("photo.drop_caption"); + } + } + + private async void OnPhotoDrop(object sender, DragEventArgs e) + { + var deferral = e.GetDeferral(); + try + { + await GuardPhotoAsync(async () => + { + if (e.DataView.Contains(StandardDataFormats.StorageItems) + && (await e.DataView.GetStorageItemsAsync()).OfType().FirstOrDefault() is { } file) + { + await LoadPhotoFromFileAsync(file); + } + else if (e.DataView.Contains(StandardDataFormats.Bitmap)) + { + using var stream = await (await e.DataView.GetBitmapAsync()).OpenReadAsync(); + await LoadPhotoAsync(stream); + } + }); + } + finally + { + deferral.Complete(); + } + } + + private async Task LoadPhotoFromFileAsync(StorageFile file) + { + using var stream = await file.OpenAsync(FileAccessMode.Read); + await LoadPhotoAsync(stream); + } + + private async Task LoadPhotoAsync(IRandomAccessStream stream) + { + GoTo(Page.Photo); + if (AddPane.Visibility != Visibility.Visible) SetPaneVisible(true); + ShowOcrInfo(InfoBarSeverity.Informational, Loc.T("photo.reading")); + + OcrPage page; + try + { + page = await OcrService.RecognizeAsync(stream, _ui.OcrLanguage); + } + catch (Exception ex) + { + ShowOcrInfo(InfoBarSeverity.Error, + Loc.F("photo.read_failed", ex.Message)); + return; + } + + var source = new SoftwareBitmapSource(); + await source.SetBitmapAsync(page.Bitmap); + double width = page.Bitmap.PixelWidth, height = page.Bitmap.PixelHeight; + PhotoImage.Source = source; + PhotoImage.Width = LineCanvas.Width = width; + PhotoImage.Height = LineCanvas.Height = height; + PhotoHint.Visibility = Visibility.Collapsed; + + LineCanvas.Children.Clear(); + var accent = (Color)Application.Current.Resources["SystemAccentColor"]; + var idle = new SolidColorBrush(Color.FromArgb(36, accent.R, accent.G, accent.B)); + var stroke = new SolidColorBrush(accent); + var style = (Style)Root.Resources["PhotoLineButton"]; + foreach (var line in page.Lines) + { + var box = new Button + { + Style = style, + Width = line.Bounds.Width + 8, + Height = line.Bounds.Height + 6, + Background = idle, + BorderBrush = stroke, + Tag = line.Text, + }; + AutomationProperties.SetName(box, line.Text); + ToolTipService.SetToolTip(box, line.Text); + box.Click += OnLineClicked; + Canvas.SetLeft(box, line.Bounds.X - 4); + Canvas.SetTop(box, line.Bounds.Y - 3); + LineCanvas.Children.Add(box); + } + + _startFreshFromPhoto = true; + if (page.Lines.Count == 0) + ShowOcrInfo(InfoBarSeverity.Warning, Loc.T("photo.no_text")); + else if (!page.IsSpanish && !OcrService.SpanishAvailable && !_ui.OcrHintDismissed) + ShowSpanishOcrWarning(page.LanguageName); + else + OcrInfo.IsOpen = false; + + DispatcherQueue.TryEnqueue(DispatcherQueuePriority.Low, FitPhoto); + } + + private void OnFitPhoto(object sender, RoutedEventArgs e) => FitPhoto(); + + private void FitPhoto() + { + if (PhotoImage.Width is not > 0) return; + float zoom = (float)Math.Clamp(PhotoScroller.ViewportWidth / PhotoImage.Width, 0.1, 1.0); + PhotoScroller.ChangeView(0, 0, zoom, true); + } + + /// + /// A click on a line of the photo puts it in the search box: the first click after an album + /// was added starts a new search, later clicks are appended (artist, then album). + /// + private void OnLineClicked(object sender, RoutedEventArgs e) + { + if (sender is not Button { Tag: string raw } box) return; + var (text, year) = OcrService.CleanLine(raw); + box.Opacity = 0.45; + + var current = SearchBox.Text.Trim(); + var next = _startFreshFromPhoto || current.Length == 0 ? text : $"{current} {text}"; + if (year != null && !next.Contains(year.Value.ToString())) next = $"{next} {year}".Trim(); + _startFreshFromPhoto = false; + + SearchBox.Text = next; + SearchBox.SelectionStart = next.Length; + SearchBox.Focus(FocusState.Programmatic); + } + + private void ShowOcrInfo(InfoBarSeverity severity, string message) + { + OcrInfo.ActionButton = null; + OcrInfo.Content = null; + OcrInfo.Severity = severity; + OcrInfo.Message = message; + OcrInfo.IsOpen = true; + } + + /// + /// The Photo page's offer to install Spanish text recognition. It can be dismissed for good; + /// Settings → Text recognition still offers it. + /// + private void ShowSpanishOcrWarning(string? usedLanguage) + { + // Installed earlier in this run: it only needs Queueify to restart, not another install. + if (OcrService.PendingRestartTags.FirstOrDefault(t => t.StartsWith("es", StringComparison.OrdinalIgnoreCase)) is string pending) + { + ShowPhotoOcrOffer(InfoBarSeverity.Informational, + Loc.F("ocr.installed_restart_app", OcrLanguages.NameInSentence(pending)), OcrOffer.Restart | OcrOffer.Dismiss); + return; + } + ShowPhotoOcrOffer(InfoBarSeverity.Warning, + usedLanguage != null ? Loc.F("ocr.no_spanish_as", usedLanguage) : Loc.T("ocr.no_spanish"), + OcrOffer.Retry | OcrOffer.Dismiss); + } + + /// + /// The Photo page's message with the actions that make sense next: install (again), restart, + /// Windows language settings, or "Don't show this again". + /// + private void ShowPhotoOcrOffer(InfoBarSeverity severity, string message, OcrOffer offer) + { + ShowOcrInfo(severity, message); + if (offer.HasFlag(OcrOffer.Retry)) + { + var install = new Button { Content = Loc.T("ocr.install_spanish") }; + install.Click += async (_, _) => + { + install.IsEnabled = false; + install.Content = Loc.T("ocr.installing"); + await InstallOcrLanguageAsync("es-ES", ShowPhotoOcrOffer); + }; + OcrInfo.ActionButton = install; + } + else if (offer.HasFlag(OcrOffer.Restart)) + { + OcrInfo.ActionButton = RestartButton(); + } + + var links = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4 }; + if (offer.HasFlag(OcrOffer.WindowsSettings)) + { + var windows = new HyperlinkButton { Content = Loc.T("settings.ocr.windows") }; + windows.Click += OnOpenWindowsLanguages; + links.Children.Add(windows); + } + if (offer.HasFlag(OcrOffer.Dismiss) && !_ui.OcrHintDismissed) + { + var dismiss = new HyperlinkButton { Content = Loc.T("ocr.dismiss") }; + dismiss.Click += (_, _) => + { + _ui.OcrHintDismissed = true; + _ui.Save(); + OcrInfo.IsOpen = false; + }; + links.Children.Add(dismiss); + } + if (links.Children.Count > 0) OcrInfo.Content = links; + } + + /// + /// Installs a text recognition language and explains every outcome: done, needs a restart, + /// permission declined or not allowed, window closed, Windows Update error, or another install + /// still running. gets what to say and what to offer next. + /// + private async Task InstallOcrLanguageAsync(string tag, Action report) + { + var name = OcrLanguages.NameInSentence(tag); + OcrInstallOutcome outcome; + try + { + var install = OcrService.InstallAsync(tag); + if (_page == Page.Settings) FillOcrSettings(); // shows it as running + outcome = await install; + } + catch (Exception ex) + { + outcome = new OcrInstallOutcome(OcrInstallResult.Failed, ex.Message); + } + + var offer = OcrService.OfferAfter(outcome.Result); + switch (outcome.Result) + { + case OcrInstallResult.Installed: + report(InfoBarSeverity.Success, Loc.F("ocr.installed", name), offer); + break; + case OcrInstallResult.RestartApp: + report(InfoBarSeverity.Success, Loc.F("ocr.installed_restart_app", name), offer); + break; + case OcrInstallResult.RestartWindows: + report(InfoBarSeverity.Warning, Loc.F("ocr.installed_restart_windows", name), offer); + break; + case OcrInstallResult.Cancelled: + report(InfoBarSeverity.Informational, + Loc.T("ocr.cancelled"), offer); + break; + case OcrInstallResult.Interrupted: + report(InfoBarSeverity.Warning, + Loc.T("ocr.interrupted"), offer); + break; + case OcrInstallResult.Busy: + report(InfoBarSeverity.Informational, Loc.T("ocr.busy"), offer); + break; + case OcrInstallResult.Blocked: + report(InfoBarSeverity.Warning, + Loc.F("ocr.blocked", outcome.Error), offer); + break; + default: + var detail = outcome.Error != null ? Loc.F("ocr.windows_said", outcome.Error) : ""; + report(InfoBarSeverity.Error, Loc.F("ocr.failed", name, detail), offer); + break; + } + if (_page == Page.Settings) FillOcrSettings(); + } + + private Button RestartButton() + { + var restart = new Button { Content = Loc.T("app.restart") }; + restart.Click += (_, _) => _ = RestartAppAsync(); + return restart; + } + + private enum Restart { Closed, NotStarted, StarterFailed } + + /// + /// Starts a fresh copy and closes this one (which saves the window and layout as usual). Through the + /// download's starter, this window stays until the starter has unpacked the new copy and its window is + /// open, so there's never a moment without Queueify on screen, nor two of them. + /// + private async Task RestartAppAsync() + { + // A second click while the new copy starts would start another one. + if (_restarting) return Restart.Closed; + _restarting = true; + // Saved first, so the new copy opens where this one was. + SaveWindow(); + System.Diagnostics.Process? started; + var running = QueueifyProcesses(); + try + { + // Through the download's starter when there is one, so the new copy knows it too. + started = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(AppData.StarterExe ?? Environment.ProcessPath!) { UseShellExecute = false }); + } + catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException) + { + ShowToast(Loc.F("app.restart_failed", ex.Message), severity: InfoBarSeverity.Warning); + _restarting = false; + return Restart.NotStarted; + } + using (started) + { + if (started != null && AppData.StarterExe != null) + { + // However long the first unpack takes, or the starter's message waits to be read: until + // it's done, nothing else is running. + await started.WaitForExitAsync(); + if (started.ExitCode != 0) + { + // The starter showed its own message about what went wrong. + _restarting = false; + return Restart.StarterFailed; + } + // The new copy runs; its window takes a moment more. A minute at most, then this one goes anyway. + for (int i = 0; i < 300 && !NewQueueifyWindow(running); i++) + await Task.Delay(200); + } + } + Close(); + return Restart.Closed; + } + private bool _restarting; +} diff --git a/Queueify/MainWindow.Settings.cs b/Queueify/MainWindow.Settings.cs new file mode 100644 index 0000000..2f9536f --- /dev/null +++ b/Queueify/MainWindow.Settings.cs @@ -0,0 +1,427 @@ +using System.Globalization; +using Microsoft.UI.Dispatching; +using Microsoft.UI.Windowing; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Automation; +using Microsoft.UI.Xaml.Automation.Peers; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Input; +using Microsoft.UI.Xaml.Media; +using Microsoft.UI.Xaml.Media.Imaging; +using Queueify.Controls; +using Queueify.Models; +using Queueify.Services; +using Windows.ApplicationModel.DataTransfer; +using Windows.Graphics; +using Windows.Storage; +using Windows.Storage.Pickers; +using Windows.Storage.Streams; +using Windows.System; +using Windows.UI; +using DispatcherQueuePriority = Microsoft.UI.Dispatching.DispatcherQueuePriority; +using DispatcherQueueTimer = Microsoft.UI.Dispatching.DispatcherQueueTimer; + +namespace Queueify; + +public sealed partial class MainWindow +{ + // ───────────────────────── Settings ───────────────────────── + + private void UpdateSetupInfo() => + SetupInfo.IsOpen = !_settings.SpotifyConfigured && !_settings.TidalConfigured; + + private void ApplyPreferredService() => + BacklogItem.Preferred = Enum.TryParse(_settings.PreferredService, out var s) ? s : MusicService.Tidal; + + /// "Open settings" in the Add albums panel. + private void OnSettings(object sender, RoutedEventArgs e) => GoTo(Page.Settings); + + /// + /// The values the Settings page shows. Edits are compared against it (AppSettings.ApplyEdits), + /// so a value a sync brought in while the page was open isn't overwritten by an untouched box. + /// + private AppSettings _settingsShown = new(); + + /// Set while the page fills its controls, so their change events don't save anything. + private bool _fillingSettings; + + /// + /// The last connection test per service failed with this message; KeysRejected tells a wrong key + /// apart from a network problem. Cleared when the keys change (here or from another PC). + /// + private readonly Dictionary _serviceProblem = []; + + /// Services whose keys are being tested right now. + private readonly HashSet _testing = []; + + /// Services whose current keys passed a test search in this session. + private readonly HashSet _verified = []; + + /// The keys changed (saved, removed, or synced from another PC): earlier test results no longer apply. + private void ForgetTestResult(MusicService service) + { + _serviceProblem.Remove(service); + _verified.Remove(service); + (service == MusicService.Tidal ? TidalCard : SpotifyCard).HideResult(); + } + + /// + /// Fills the page from the current settings. After a sync, keys the user is typing (boxes that + /// differ from what was shown) are kept, and so is what they were compared against. + /// + private void FillSettingsPage(bool keepTypedKeys = false) + { + _fillingSettings = true; + try + { + // Shown in standard form ("ar" as Argentina), and compared in that form, so picking + // nothing never counts as a change. + var shown = _settings.ForSettingsPage(); + if (keepTypedKeys && (TidalCard.ClientId != _settingsShown.TidalClientId || TidalCard.ClientSecret != _settingsShown.TidalClientSecret)) + { + shown.TidalClientId = _settingsShown.TidalClientId; + shown.TidalClientSecret = _settingsShown.TidalClientSecret; + } + else + { + TidalCard.ClientId = shown.TidalClientId; + TidalCard.ClientSecret = shown.TidalClientSecret; + } + if (keepTypedKeys && (SpotifyCard.ClientId != _settingsShown.SpotifyClientId || SpotifyCard.ClientSecret != _settingsShown.SpotifyClientSecret)) + { + shown.SpotifyClientId = _settingsShown.SpotifyClientId; + shown.SpotifyClientSecret = _settingsShown.SpotifyClientSecret; + } + else + { + SpotifyCard.ClientId = shown.SpotifyClientId; + SpotifyCard.ClientSecret = shown.SpotifyClientSecret; + } + _settingsShown = shown; + + if (!keepTypedKeys) + { + TidalCard.IsExpanded = !_settings.TidalConfigured; + SpotifyCard.IsExpanded = !_settings.SpotifyConfigured; + } + + PreferredBox.SelectedItem = shown.PreferredService; + var countries = Countries.Options(shown.CountryCode, CultureInfo.CurrentCulture); + CountryBox.ItemsSource = Items(countries); + CountryBox.SelectedItem = countries.FirstOrDefault(c => c.Code == shown.CountryCode); + ThemeBox.SelectedItem = ThemeBox.Items.OfType().FirstOrDefault(i => (string)i.Tag == _ui.Theme) + ?? ThemeBox.Items[0]; + LanguageBox.SelectedItem = LanguageBox.Items.OfType().FirstOrDefault(i => (string)i.Tag == _ui.Language) + ?? LanguageBox.Items[0]; + UpdateLanguageRestart(); + UpdateCheckToggle.IsOn = _ui.CheckForUpdates; + SettingsDataPath.Text = AppData.Folder; + FillOcrSettings(); + UpdateServiceCards(); + } + finally + { + _fillingSettings = false; + } + } + + private void UpdateServiceCards() + { + Show(TidalCard, MusicService.Tidal, _settings.TidalConfigured); + Show(SpotifyCard, MusicService.Spotify, _settings.SpotifyConfigured); + + void Show(ServiceCard card, MusicService service, bool configured) + { + if (!configured) + card.ShowState(false, false, Loc.T("service.not_connected.pill"), Loc.F("service.not_connected", service)); + else if (_testing.Contains(service)) + card.ShowState(false, true, Loc.T("service.testing.pill"), Loc.T("service.testing")); + else if (_serviceProblem.TryGetValue(service, out var problem)) + card.ShowState(false, true, Loc.T(problem.KeysRejected ? "service.check_keys.pill" : "service.unreachable.pill"), problem.Message); + else if (_verified.Contains(service)) + card.ShowState(true, true, Loc.T("service.connected.pill"), Loc.F("service.connected", service)); + else + card.ShowState(true, true, Loc.T("service.saved.pill"), Loc.F("service.saved", service)); + } + } + + /// + /// Applies what changed between and , saves, + /// and lets the rest of the app catch up. Only real changes are stamped as the newest shared + /// settings, so saving unchanged values never pushes older keys to the other PCs. + /// + private void CommitSettingsEdit(AppSettings edited) + { + if (_settings.ApplyEdits(_settingsShown, edited)) + { + _settings.SharedSettingsUpdatedAt = BacklogStore.Now(); + ScheduleSync(); + } + _settingsShown = edited; + AppData.SaveSettings(_settings); + ApplyPreferredService(); + UpdateSetupInfo(); + UpdateServiceCards(); + _resultsQuery = null; + RefreshQueue(); + } + + private async void OnSaveServiceKeys(object? sender, EventArgs e) + { + if (sender is not ServiceCard card) return; + var service = card == TidalCard ? MusicService.Tidal : MusicService.Spotify; + if (card.ClientId.Length == 0 || card.ClientSecret.Length == 0) + { + card.ShowResult(InfoBarSeverity.Warning, Loc.T("service.need_both")); + return; + } + + var edited = _settingsShown.Clone(); + if (service == MusicService.Tidal) + (edited.TidalClientId, edited.TidalClientSecret) = (card.ClientId, card.ClientSecret); + else + (edited.SpotifyClientId, edited.SpotifyClientSecret) = (card.ClientId, card.ClientSecret); + ForgetTestResult(service); + _testing.Add(service); + CommitSettingsEdit(edited); + await TestServiceAsync(card, service); + } + + private string KeysOf(MusicService service) => service == MusicService.Tidal + ? $"{_settings.TidalClientId}:{_settings.TidalClientSecret}" + : $"{_settings.SpotifyClientId}:{_settings.SpotifyClientSecret}"; + + /// + /// A real search with the saved keys: the quickest proof that they work. The result only counts + /// if the keys are still the ones tested (they may be removed or synced meanwhile). + /// + private async Task TestServiceAsync(ServiceCard card, MusicService service) + { + var tested = KeysOf(service); + _testing.Add(service); + card.IsBusy = true; + card.HideResult(); + UpdateServiceCards(); + (string Message, bool KeysRejected)? problem = null; + int found = 0; + try + { + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(25)); + var search = service == MusicService.Tidal + ? _tidal.SearchAsync("Charly Garcia Clics Modernos", cts.Token) + : _spotify.SearchAsync("Charly Garcia Clics Modernos", cts.Token); + found = (await search).Count; + } + catch (CatalogException ex) { problem = (ex.Message, ex.KeysRejected); } + catch (OperationCanceledException) { problem = (Loc.F("service.timeout", service), false); } + catch (HttpRequestException ex) { problem = (Loc.F("service.unreachable", service, ex.Message), false); } + catch (Exception ex) { problem = (Loc.F("service.unexpected", service, ex.Message), false); } + finally + { + _testing.Remove(service); + card.IsBusy = false; + } + + if (KeysOf(service) != tested) + { + UpdateServiceCards(); + return; + } + if (problem is { } p) _serviceProblem[service] = p; + else _verified.Add(service); + UpdateServiceCards(); + if (problem is { } shown) + card.ShowResult(InfoBarSeverity.Error, shown.Message); + else + card.ShowResult(InfoBarSeverity.Success, Loc.F("service.test_ok", QueueText.Albums(found))); + } + + private void OnRemoveServiceKeys(object? sender, EventArgs e) + { + if (sender is not ServiceCard card) return; + var service = card == TidalCard ? MusicService.Tidal : MusicService.Spotify; + var (oldId, oldSecret) = service == MusicService.Tidal + ? (_settings.TidalClientId, _settings.TidalClientSecret) + : (_settings.SpotifyClientId, _settings.SpotifyClientSecret); + + SetKeys(service, "", ""); + ShowToast(Loc.F("service.removed", service), undo: () => + { + // Keys saved here or synced from another PC since then are newer: undo must not replace them. + if (KeysOf(service) != ":") + { + ShowToast(Loc.F("service.undo_refused", service), severity: InfoBarSeverity.Warning); + return; + } + SetKeys(service, oldId, oldSecret); + }, severity: InfoBarSeverity.Informational); + + void SetKeys(MusicService s, string id, string secret) + { + var edited = _settingsShown.Clone(); + if (s == MusicService.Tidal) (edited.TidalClientId, edited.TidalClientSecret) = (id, secret); + else (edited.SpotifyClientId, edited.SpotifyClientSecret) = (id, secret); + ForgetTestResult(s); + var target = s == MusicService.Tidal ? TidalCard : SpotifyCard; + target.ClientId = id; + target.ClientSecret = secret; + target.HideResult(); + CommitSettingsEdit(edited); + } + } + + private void OnPreferredChanged(object sender, SelectionChangedEventArgs e) + { + if (_fillingSettings || PreferredBox.SelectedItem is not string service) return; + var edited = _settingsShown.Clone(); + edited.PreferredService = service; + CommitSettingsEdit(edited); + } + + private void OnCountryChanged(object sender, SelectionChangedEventArgs e) + { + if (_fillingSettings || CountryBox.SelectedItem is not CountryOption country) return; + var edited = _settingsShown.Clone(); + edited.CountryCode = country.Code; + CommitSettingsEdit(edited); + } + + private void OnUpdateCheckToggled(object sender, RoutedEventArgs e) + { + if (_fillingSettings) return; + _ui.CheckForUpdates = UpdateCheckToggle.IsOn; + _ui.Save(); + } + + private void OnThemeChanged(object sender, SelectionChangedEventArgs e) + { + if (_fillingSettings || ThemeBox.SelectedItem is not ComboBoxItem { Tag: string theme }) return; + _ui.Theme = theme; + _ui.Save(); + ApplyTheme(); + } + + /// Text recognition: what Windows has installed, which one reads photos, what can be added. + private void FillOcrSettings() + { + bool wasFilling = _fillingSettings; + _fillingSettings = true; + try + { + var installed = OcrService.InstalledTags; + var choices = new List { new("auto", Loc.T("ocr.auto")) }; + choices.AddRange(installed.Select(t => new OcrLanguageOption(t, OcrLanguages.NameOf(t)))); + OcrLanguageBox.ItemsSource = Items(choices); + OcrLanguageBox.SelectedItem = choices.FirstOrDefault(c => c.Tag.Equals(_ui.OcrLanguage, StringComparison.OrdinalIgnoreCase)) + ?? choices[0]; + + var pending = OcrService.PendingRestartTags; + var names = installed.Select(OcrLanguages.NameOf) + .Concat(pending.Select(t => Loc.F("ocr.after_restart", OcrLanguages.NameOf(t)))).ToList(); + OcrInstalledList.Text = names.Count == 0 + ? Loc.T("ocr.none_installed") + : string.Join(", ", names); + + // The button and progress follow the install actually running, wherever it was started. + var installable = OcrLanguages.Installable(installed, pending); + bool installing = OcrService.InstallingTag != null; + OcrInstallBox.ItemsSource = Items(installable); + OcrInstallBox.SelectedIndex = installable.Count > 0 ? 0 : -1; + OcrInstallBox.IsEnabled = OcrInstallButton.IsEnabled = installable.Count > 0 && !installing; + OcrInstallProgress.Visibility = installing ? Visibility.Visible : Visibility.Collapsed; + OcrInstallBox.PlaceholderText = installable.Count > 0 ? "" : Loc.T("ocr.all_installed"); + } + finally + { + _fillingSettings = wasFilling; + } + } + + private void OnOcrLanguageChanged(object sender, SelectionChangedEventArgs e) + { + if (_fillingSettings || OcrLanguageBox.SelectedItem is not OcrLanguageOption choice) return; + _ui.OcrLanguage = choice.Tag; + _ui.Save(); + } + + private async void OnInstallOcrLanguage(object sender, RoutedEventArgs e) + { + if (OcrInstallBox.SelectedItem is not OcrLanguageOption choice) return; + OcrInstallInfo.IsOpen = false; + try + { + // Retry and Windows settings are already on this page; only a restart needs a button here. + await InstallOcrLanguageAsync(choice.Tag, (severity, message, offer) => + { + OcrInstallInfo.Severity = severity; + OcrInstallInfo.Message = message; + OcrInstallInfo.ActionButton = offer.HasFlag(OcrOffer.Restart) ? RestartButton() : null; + OcrInstallInfo.IsOpen = true; + }); + } + finally + { + FillOcrSettings(); + } + } + + private async void OnOpenWindowsLanguages(object sender, RoutedEventArgs e) => + await Launcher.LaunchUriAsync(new Uri("ms-settings:regionlanguage")); + + private void OnLanguageChanged(object sender, SelectionChangedEventArgs e) + { + if (_fillingSettings || LanguageBox.SelectedItem is not ComboBoxItem { Tag: string language }) return; + _ui.Language = language; + _ui.Save(); + UpdateLanguageRestart(); + } + + /// The window's texts are set when it loads, so a new language shows after a restart. + private void UpdateLanguageRestart() + { + bool pending = Loc.Resolve(_ui.Language, Loc.WindowsLanguage) != Loc.Language; + LanguageRestartInfo.ActionButton = pending ? RestartButton() : null; + LanguageRestartInfo.IsOpen = pending; + LanguageRow.RowSpacing = pending ? 12 : 0; + } + + private void ApplyTheme() + { + Root.RequestedTheme = _ui.Theme switch + { + "light" => ElementTheme.Light, + "dark" => ElementTheme.Dark, + _ => ElementTheme.Default, + }; + UpdateCaptionButtons(); + } + + /// The window's own minimize/maximize/close buttons don't follow the app theme by themselves. + private void UpdateCaptionButtons() + { + bool dark = Root.ActualTheme == ElementTheme.Dark; + var bar = AppWindow.TitleBar; + var text = dark ? Color.FromArgb(255, 255, 255, 255) : Color.FromArgb(255, 0, 0, 0); + bar.ButtonBackgroundColor = bar.ButtonInactiveBackgroundColor = Color.FromArgb(0, 0, 0, 0); + bar.ButtonForegroundColor = bar.ButtonHoverForegroundColor = bar.ButtonPressedForegroundColor = text; + bar.ButtonInactiveForegroundColor = Color.FromArgb(255, 128, 128, 128); + bar.ButtonHoverBackgroundColor = dark ? Color.FromArgb(24, 255, 255, 255) : Color.FromArgb(20, 0, 0, 0); + bar.ButtonPressedBackgroundColor = dark ? Color.FromArgb(40, 255, 255, 255) : Color.FromArgb(36, 0, 0, 0); + } + + private void OnResetLayout(object sender, RoutedEventArgs e) + { + _ui.ResetLayout(); + _ui.Save(); + CoverViewToggle.IsChecked = _ui.CoverView; + CheckSortItem(); + if (AppWindow.Presenter is OverlappedPresenter { State: OverlappedPresenterState.Maximized } presenter) presenter.Restore(); + SizeToScreen(1440, 920); + GoTo(Page.Queue); + ShowToast(Loc.T("settings.layout.done"), + severity: InfoBarSeverity.Informational); + } + + private static TextBlock Paragraph(string text) => + new() { Text = text, TextWrapping = TextWrapping.Wrap, Style = (Style)Application.Current.Resources["CaptionTextBlockStyle"] }; +} diff --git a/Queueify/MainWindow.Sync.cs b/Queueify/MainWindow.Sync.cs new file mode 100644 index 0000000..c8b0b32 --- /dev/null +++ b/Queueify/MainWindow.Sync.cs @@ -0,0 +1,446 @@ +using System.Globalization; +using Microsoft.UI.Dispatching; +using Microsoft.UI.Windowing; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Automation; +using Microsoft.UI.Xaml.Automation.Peers; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Input; +using Microsoft.UI.Xaml.Media; +using Microsoft.UI.Xaml.Media.Imaging; +using Queueify.Controls; +using Queueify.Models; +using Queueify.Services; +using Windows.ApplicationModel.DataTransfer; +using Windows.Graphics; +using Windows.Storage; +using Windows.Storage.Pickers; +using Windows.Storage.Streams; +using Windows.System; +using Windows.UI; +using DispatcherQueuePriority = Microsoft.UI.Dispatching.DispatcherQueuePriority; +using DispatcherQueueTimer = Microsoft.UI.Dispatching.DispatcherQueueTimer; + +namespace Queueify; + +public sealed partial class MainWindow +{ + // ───────────────────────── Sync between PCs ───────────────────────── + + private void ScheduleSync() + { + if (!_settings.SyncConfigured) return; + _syncDebounce.Stop(); + _syncDebounce.Start(); + } + + private Task? _syncTask; + private Task? _followUpSync; + private bool _syncSetupRunning; // the setup dialog is trying a connection: no other sync may run + + /// + /// Downloads other PCs' changes and uploads this PC's. Returns an error message, or null when it + /// worked (or sync isn't set up). If a sync is already running, one more runs right after it and + /// the caller gets that result, so "Sync now" never reports success for a sync that didn't happen. + /// Failures are harmless: pending changes stay and go up next time. + /// + private Task SyncNowAsync() + { + if (!_settings.SyncConfigured || _syncSetupRunning) return Task.FromResult(null); + if (_syncTask is { IsCompleted: false } running) + return _followUpSync ??= AfterAsync(running); + return _syncTask = RunSyncAsync(); + + async Task AfterAsync(Task previous) + { + await previous; + _followUpSync = null; + return await SyncNowAsync(); + } + } + + private async Task RunSyncAsync() + { + _lastSyncAttempt = DateTime.UtcNow; + SyncNav.Content = Loc.T("sync.syncing"); + + // Sync a copy: the UI thread keeps using _settings while the sync runs in the background. + var work = _settings.Clone(); + var provider = Provider(); + var sharedStampBefore = _settings.SharedSettingsUpdatedAt; + string? error = null; + try + { + var result = await Task.Run(() => provider.SyncAsync(_store, work, CancellationToken.None)); + if (_settings.SyncIdentity == work.SyncIdentity) // still connected to the same queue + { + _settings.CloudLastServerTime = work.CloudLastServerTime; + _settings.WebLastServerTime = work.WebLastServerTime; + _settings.WebSettingsSyncedAt = work.WebSettingsSyncedAt; + // Take downloaded keys/preferences unless the user saved Settings while this sync ran. + bool sharedChanged = _settings.SharedSettingsUpdatedAt == sharedStampBefore + && work.SharedSettingsUpdatedAt != sharedStampBefore; + if (sharedChanged) + { + var keysBefore = (KeysOf(MusicService.Tidal), KeysOf(MusicService.Spotify)); + _settings.CopySharedFrom(work); + _settings.Normalize(); + if (KeysOf(MusicService.Tidal) != keysBefore.Item1) ForgetTestResult(MusicService.Tidal); + if (KeysOf(MusicService.Spotify) != keysBefore.Item2) ForgetTestResult(MusicService.Spotify); + } + AppData.SaveSettings(_settings); + + if (result.SettingsChanged && sharedChanged) + { + ApplyPreferredService(); + UpdateSetupInfo(); + _resultsQuery = null; + if (_page == Page.Settings) FillSettingsPage(keepTypedKeys: true); + } + if (result.Downloaded > 0 || result.SettingsChanged) + { + _all = _store.LoadAll(); + RefreshQueue(); + } + _lastSynced = DateTime.Now; + } + } + catch (Exception ex) + { + error = DescribeSyncError(ex); + } + + _syncError = _settings.SyncConfigured ? error : null; + UpdateSyncButton(); + return error; + } + + private static string DescribeSyncError(Exception ex) => ex switch + { + CatalogException or SyncException => ex.Message, + HttpRequestException => Loc.T("sync.err.offline"), + TaskCanceledException => Loc.T("sync.err.timeout"), + IOException or UnauthorizedAccessException => Loc.F("sync.err.disk", ex.Message), + _ => Loc.F("sync.err.other", ex.Message), + }; + + /// The Sync icon in the navigation bar shows the state; its tooltip says why. + private void UpdateSyncButton() + { + string label, glyph, tip; + bool web = _settings.WebConfigured; + if (!_settings.SyncConfigured) + (label, glyph, tip) = (Loc.T("nav.sync"), "", Loc.T("sync.tip.off")); + else if (_syncError != null) + (label, glyph, tip) = (Loc.T("sync.not_synced"), "", Loc.F("sync.tip.error", _syncError)); + else + (label, glyph, tip) = (Loc.T("sync.synced"), "", + _lastSynced is DateTime t ? web ? Loc.F("webSync.tip.at", t) : Loc.F("sync.tip.at", t) + : web ? Loc.T("webSync.tip.ok") : Loc.T("sync.tip.ok")); + + SyncNav.Content = label; + SyncIcon.Glyph = SettingsSyncIcon.Glyph = glyph; + SettingsSyncStatus.Text = tip; + ToolTipService.SetToolTip(SyncNav, tip); + Microsoft.UI.Xaml.Automation.AutomationProperties.SetName(SyncNav, tip); + } + + private async void OnSync(object sender, RoutedEventArgs e) + { + switch (_settings.ActiveSync) + { + case SyncKind.Web: await ShowWebSyncConnectedAsync(); break; + case SyncKind.Cloud: await ShowSyncConnectedAsync(); break; + default: await ShowSyncSetupAsync(); break; + } + } + + /// First-time setup: create the online queue (first PC) or join it with a sync code. + private async Task ShowSyncSetupAsync() + { + var create = new RadioButton { Content = Loc.T("sync.setup.create"), GroupName = "sync", IsChecked = true }; + var join = new RadioButton { Content = Loc.T("sync.setup.join"), GroupName = "sync" }; + var web = new RadioButton { Content = Loc.T("webSync.setup.option"), GroupName = "sync" }; + + var projectBox = new TextBox { Header = Loc.T("sync.project"), PlaceholderText = Loc.T("sync.project.placeholder") }; + var copyRules = new Button { Content = Loc.T("sync.copy_rules") }; + copyRules.Click += (_, _) => + { + CopyToClipboard(CloudSync.SecurityRules); + copyRules.Content = Loc.T("sync.rules_copied"); + }; + var createPanel = new StackPanel { Spacing = 10 }; + createPanel.Children.Add(Paragraph( + Loc.T("sync.setup.steps"))); + createPanel.Children.Add(new HyperlinkButton { Content = Loc.T("sync.console"), NavigateUri = new Uri("https://console.firebase.google.com/") }); + createPanel.Children.Add(copyRules); + createPanel.Children.Add(projectBox); + + var codeBox = new TextBox { Header = Loc.T("sync.code"), PlaceholderText = "queueify:…" }; + var joinPanel = new StackPanel { Spacing = 10, Visibility = Visibility.Collapsed }; + joinPanel.Children.Add(Paragraph( + Loc.T("sync.setup.join_text"))); + joinPanel.Children.Add(codeBox); + + var webBox = new TextBox { Header = Loc.T("webSync.code"), PlaceholderText = Loc.T("webSync.code.placeholder") }; + var webPanel = new StackPanel { Spacing = 10, Visibility = Visibility.Collapsed }; + webPanel.Children.Add(Paragraph(Loc.T("webSync.setup.text"))); + webPanel.Children.Add(webBox); + webPanel.Children.Add(Paragraph(Loc.T("webSync.keys_notice"))); + + void ShowOnly(StackPanel shown) + { + foreach (var p in new[] { createPanel, joinPanel, webPanel }) + p.Visibility = p == shown ? Visibility.Visible : Visibility.Collapsed; + } + create.Checked += (_, _) => ShowOnly(createPanel); + join.Checked += (_, _) => ShowOnly(joinPanel); + web.Checked += (_, _) => ShowOnly(webPanel); + + var progress = new ProgressBar { IsIndeterminate = true, Visibility = Visibility.Collapsed }; + var error = new InfoBar { Severity = InfoBarSeverity.Error, IsClosable = false, IsOpen = false }; + + var panel = new StackPanel { Spacing = 12, Width = 480 }; + panel.Children.Add(Paragraph(Loc.T("sync.setup.intro"))); + panel.Children.Add(create); + panel.Children.Add(join); + panel.Children.Add(web); + panel.Children.Add(createPanel); + panel.Children.Add(joinPanel); + panel.Children.Add(webPanel); + panel.Children.Add(progress); + panel.Children.Add(error); + + var dialog = new ContentDialog + { + Title = Loc.T("sync.title"), + Content = new ScrollViewer { Content = panel, MaxHeight = 600 }, + PrimaryButtonText = Loc.T("sync.connect"), + CloseButtonText = Loc.T("dialog.cancel"), + DefaultButton = ContentDialogButton.Primary, + XamlRoot = Root.XamlRoot, + }; + + bool joined = false, toWeb = false; + dialog.PrimaryButtonClick += async (d, args) => + { + var deferral = args.GetDeferral(); + try + { + string project = "", key = "", webUrl = "", webToken = ""; + toWeb = web.IsChecked == true; + joined = toWeb || join.IsChecked == true; + if (toWeb) + { + if (!SyncConnect.TryParse(webBox.Text, out webUrl, out webToken)) + { + Fail(Loc.T("webSync.bad_code")); + return; + } + } + else if (joined) + { + if (!CloudSync.TryParseSyncCode(codeBox.Text, out project, out key)) + { + Fail(Loc.T("sync.bad_code")); + return; + } + } + else + { + if (CloudSync.NormalizeProjectId(projectBox.Text) is not string id) + { + Fail(Loc.T("sync.no_project")); + return; + } + project = id; + key = CloudSync.NewQueueKey(); + } + + SyncTarget target = toWeb ? SyncTarget.Web(webUrl, webToken) + : joined ? SyncTarget.JoinCloud(project, key) + : SyncTarget.CreateCloud(project, key); + + progress.Visibility = Visibility.Visible; + error.IsOpen = false; + d.IsPrimaryButtonEnabled = false; + string? problem = null; + AppSettings? trial = null; + // A debounced sync of the old queue must not run between "mark everything" and the first sync here. + _syncDebounce.Stop(); + _syncSetupRunning = true; + try + { + trial = await SyncSetup.TryConnectAsync(_store, _settings, target, _cloud, _web, _syncTask, CancellationToken.None); + } + catch (Exception ex) + { + problem = DescribeSyncError(ex); + } + finally + { + _syncSetupRunning = false; + } + progress.Visibility = Visibility.Collapsed; + d.IsPrimaryButtonEnabled = true; + + if (trial == null) + { + Fail(problem!); + return; + } + + _settings = trial; + AppData.SaveSettings(_settings); + ApplyPreferredService(); + UpdateSetupInfo(); + _all = _store.LoadAll(); + RefreshQueue(); + _syncError = null; + _lastSynced = DateTime.Now; + UpdateSyncButton(); + } + catch (Exception ex) + { + Fail(DescribeSyncError(ex)); + } + finally + { + deferral.Complete(); + } + + void Fail(string message) + { + error.Message = message; + error.IsOpen = true; + args.Cancel = true; + } + }; + + if (await ShowDialogAsync(dialog) != ContentDialogResult.Primary || !_settings.SyncConfigured) return; + + if (toWeb) + ShowToast(Loc.F("webSync.joined", QueueText.Albums(_all.Count))); + else if (joined) + ShowToast(Loc.F("sync.joined", QueueText.Albums(_all.Count))); + else + await ShowSyncConnectedAsync(justCreated: true); + } + + /// Shows the sync code for other PCs, plus "Sync now" and "Disconnect". + private async Task ShowSyncConnectedAsync(bool justCreated = false) + { + var code = CloudSync.SyncCode(_settings); + var codeBox = new TextBox { Header = Loc.T("sync.code"), Text = code, IsReadOnly = true, TextWrapping = TextWrapping.Wrap }; + var copy = new Button { Content = Loc.T("sync.copy_code") }; + copy.Click += (_, _) => + { + CopyToClipboard(code); + copy.Content = Loc.T("sync.copied"); + }; + + var status = _syncError ?? (_lastSynced is DateTime t ? Loc.F("sync.last", t) : Loc.T("sync.ok")); + var panel = new StackPanel { Spacing = 12, Width = 480 }; + panel.Children.Add(Paragraph(justCreated + ? Loc.T("sync.done") + : Loc.F("sync.this_pc", _settings.CloudProjectId, status))); + panel.Children.Add(Paragraph( + Loc.T("sync.add_pc"))); + panel.Children.Add(codeBox); + panel.Children.Add(copy); + panel.Children.Add(Paragraph(Loc.T("sync.private"))); + + var dialog = new ContentDialog + { + Title = Loc.T("sync.title"), + Content = new ScrollViewer { Content = panel, MaxHeight = 560 }, + PrimaryButtonText = Loc.T("sync.now"), + SecondaryButtonText = Loc.T("sync.disconnect"), + CloseButtonText = Loc.T("dialog.close"), + DefaultButton = ContentDialogButton.Close, + XamlRoot = Root.XamlRoot, + }; + + switch (await ShowDialogAsync(dialog)) + { + case ContentDialogResult.Primary: + var problem = await SyncNowAsync(); + ShowToast(problem ?? Loc.T("sync.ok"), severity: problem == null ? InfoBarSeverity.Success : InfoBarSeverity.Warning); + break; + case ContentDialogResult.Secondary: + _settings.DisconnectCloud(); + _syncError = null; + AppData.SaveSettings(_settings); + UpdateSyncButton(); + ShowToast(Loc.T("sync.disconnected"), + severity: InfoBarSeverity.Informational); + break; + } + } + + /// Shows which web server this PC syncs with, plus "Sync now" and "Disconnect". + private async Task ShowWebSyncConnectedAsync() + { + // Only the host is shown; the token stays out of the window. + var host = Uri.TryCreate(_settings.WebServerUrl, UriKind.Absolute, out var address) ? address.Authority : "?"; + var status = _syncError ?? (_lastSynced is DateTime t ? Loc.F("sync.last", t) : Loc.T("sync.ok")); + var panel = new StackPanel { Spacing = 12, Width = 480 }; + panel.Children.Add(Paragraph(Loc.F("webSync.this_pc", host, status))); + panel.Children.Add(Paragraph(Loc.T("webSync.private"))); + + var dialog = new ContentDialog + { + Title = Loc.T("sync.title"), + Content = new ScrollViewer { Content = panel, MaxHeight = 560 }, + PrimaryButtonText = Loc.T("sync.now"), + SecondaryButtonText = Loc.T("sync.disconnect"), + CloseButtonText = Loc.T("dialog.close"), + DefaultButton = ContentDialogButton.Close, + XamlRoot = Root.XamlRoot, + }; + + switch (await ShowDialogAsync(dialog)) + { + case ContentDialogResult.Primary: + var problem = await SyncNowAsync(); + ShowToast(problem ?? Loc.T("sync.ok"), severity: problem == null ? InfoBarSeverity.Success : InfoBarSeverity.Warning); + break; + case ContentDialogResult.Secondary: + _settings.DisconnectWeb(); + _syncError = null; + AppData.SaveSettings(_settings); + UpdateSyncButton(); + ShowToast(Loc.T("webSync.disconnected"), severity: InfoBarSeverity.Informational); + break; + } + } + + private bool _dialogOpen; + + /// + /// WinUI allows one ContentDialog at a time and throws on a second; a quick double-click on Sync + /// or Settings would otherwise crash the app. A second request while one is open is ignored. + /// + private async Task ShowDialogAsync(ContentDialog dialog) + { + if (_dialogOpen) return ContentDialogResult.None; + _dialogOpen = true; + // Dialogs live outside the window's element tree, so they don't inherit the chosen theme. + dialog.RequestedTheme = Root.ActualTheme; + try + { + return await dialog.ShowAsync(); + } + finally + { + _dialogOpen = false; + } + } + + private static void CopyToClipboard(string text) + { + var package = new DataPackage(); + package.SetText(text); + Clipboard.SetContent(package); + } +} diff --git a/Queueify/MainWindow.Updates.cs b/Queueify/MainWindow.Updates.cs new file mode 100644 index 0000000..e83393d --- /dev/null +++ b/Queueify/MainWindow.Updates.cs @@ -0,0 +1,317 @@ +using System.Globalization; +using Microsoft.UI.Dispatching; +using Microsoft.UI.Windowing; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Automation; +using Microsoft.UI.Xaml.Automation.Peers; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Input; +using Microsoft.UI.Xaml.Media; +using Microsoft.UI.Xaml.Media.Imaging; +using Queueify.Controls; +using Queueify.Models; +using Queueify.Services; +using Windows.ApplicationModel.DataTransfer; +using Windows.Graphics; +using Windows.Storage; +using Windows.Storage.Pickers; +using Windows.Storage.Streams; +using Windows.System; +using Windows.UI; +using DispatcherQueuePriority = Microsoft.UI.Dispatching.DispatcherQueuePriority; +using DispatcherQueueTimer = Microsoft.UI.Dispatching.DispatcherQueueTimer; + +namespace Queueify; + +public sealed partial class MainWindow +{ + // ───────────────────────── Updates ───────────────────────── + + private bool _checkingUpdates; + /// Asked from About: the running check shows its result there. + private bool _reportCheck; + private CancellationTokenSource? _download; + + private async void OnCheckForUpdates(object sender, RoutedEventArgs e) => await CheckForUpdatesAsync(quiet: false); + + /// + /// Asks GitHub for a newer version and offers it under the page title. Quiet (at start) shows nothing + /// unless there is one; from About, the result shows under the button. + /// + private async Task CheckForUpdatesAsync(bool quiet) + { + // One check at a time. Asked from About while the quiet one at start runs, that one reports there + // when it's done. The button stays enabled, so keyboard focus stays on it. + if (!quiet) + { + _reportCheck = true; + ShowUpdateStatus(Loc.T("update.checking")); + } + if (_checkingUpdates) return; + _checkingUpdates = true; + try + { + var release = await _updater.CheckAsync(AppInfo.Version, CancellationToken.None); + if (release != null && !_updating && Updater.IsWanted(release, _ui.SkippedVersion, asked: _reportCheck)) + { + OfferUpdate(release); + // Found while on another page: a dot on Help and a short note say so; the offer itself waits + // in About. + if (_page != Page.Help) + { + SetUpdateBadge(true); + ShowUpdateToast(Loc.F("update.available", release.Version), InfoBarSeverity.Informational); + } + } + // The offer, right above, already says what's new; the line under the button says the rest. + if (_reportCheck) ShowUpdateStatus(release != null ? "" : Loc.T("update.latest")); + } + catch (Exception ex) + { + // UpdateException carries its own message; anything else is a bug, still not worth a crash. + if (_reportCheck) ShowUpdateStatus(ex is UpdateException ? ex.Message : Loc.F("update.failed", ex.Message)); + } + finally + { + _checkingUpdates = false; + _reportCheck = false; + } + } + + private void ShowUpdateStatus(string text) + { + UpdateStatus.Text = text; + if (text.Length == 0) return; + // At the bottom of Help, maybe below the window's edge; and said aloud for screen readers. + UpdateStatus.StartBringIntoView(); + Announce(UpdateStatus, text); + } + + private void OfferUpdate(AppRelease release) + { + var whatsNew = new HyperlinkButton { Content = Loc.T("update.whats_new"), Padding = new Thickness(0, 2, 0, 2) }; + whatsNew.Click += (_, _) => OpenInBrowser(release.Page); + // Not now, and not at the next starts either; Check for updates in About still finds it. + var skip = new HyperlinkButton { Content = Loc.T("update.skip"), Padding = new Thickness(0, 2, 0, 2) }; + AutomationProperties.SetAutomationId(skip, "SkipUpdateButton"); + skip.Click += (_, _) => + { + _ui.SkippedVersion = release.Version; + _ui.Save(); + UpdateBar.IsOpen = false; + SetUpdateBadge(false); + }; + var links = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 20, Margin = new Thickness(0, 0, 0, 8), Children = { whatsNew, skip } }; + ShowUpdateBar(InfoBarSeverity.Informational, Loc.F("update.available", release.Version), InstallButton(release, "update.install"), links, closable: true); + } + + private Button InstallButton(AppRelease release, string text) + { + var install = new Button { Content = Loc.T(text), Style = (Style)Application.Current.Resources["AccentButtonStyle"] }; + AutomationProperties.SetAutomationId(install, "InstallUpdateButton"); + install.Click += (_, _) => _ = InstallUpdateAsync(release); + return install; + } + + /// Downloads the new exe, checks it, puts it in place of this one and restarts through it. + private async Task InstallUpdateAsync(AppRelease release) + { + if (_updating) return; + if (AppData.StarterExe is not { } exe) + { + // Running from a build folder, not a download: nothing to replace. + ShowUpdateProblem(Loc.T("update.manual"), release, retry: false); + return; + } + _updating = true; + var message = Loc.F("update.downloading", release.Version); + var bar = new ProgressBar { Maximum = 1, Margin = new Thickness(0, 0, 0, 12) }; + AutomationProperties.SetName(bar, message); + // No overall time limit: a slow download that keeps coming is fine, a stalled one gives up, and + // Cancel stops either. + var cancel = new Button { Content = Loc.T("update.cancel") }; + cancel.Click += (_, _) => _download?.Cancel(); + ShowUpdateBar(InfoBarSeverity.Informational, message, cancel, bar, closable: false); + _download = new CancellationTokenSource(); + try + { + var downloaded = await _updater.DownloadAsync(release, exe, new Progress(v => bar.Value = v), _download.Token); + Updater.Replace(exe, downloaded); + } + catch (OperationCanceledException) when (_download.IsCancellationRequested) + { + _updating = false; + OfferUpdate(release); + return; + } + catch (Exception ex) + { + _updating = false; + ShowUpdateProblem(ex is UpdateException ? ex.Message : Loc.F("update.failed", ex.Message), release, retry: true); + return; + } + finally + { + _download.Dispose(); + _download = null; + } + // The new version unpacks before its window opens: this one says so and stays until then. The + // keyboard waits on the progress indicator (named, so it's read out) instead of falling into the page. + var starting = Loc.F("update.restarting", release.Version); + var wait = new ProgressBar { IsIndeterminate = true, IsTabStop = true, Margin = new Thickness(0, 0, 0, 12) }; + AutomationProperties.SetName(wait, starting); + ShowUpdateBar(InfoBarSeverity.Informational, starting, null, wait, closable: false); + switch (await RestartAppAsync()) + { + case Restart.StarterFailed: + { + // The new exe itself didn't start (its starter said why), and it's the user's only Queueify + // exe now. What helps first is a version that works, maybe an older one if this release is + // broken: all of them are on the releases page. The same download again only helps when the + // cause was on this PC (disk space, an antivirus). + _updating = false; + var releases = new Button { Content = Loc.T("update.releases"), Style = (Style)Application.Current.Resources["AccentButtonStyle"] }; + releases.Click += (_, _) => OpenInBrowser(UpdateSource.AllReleases); + var retry = new HyperlinkButton { Content = Loc.T("update.retry"), Padding = new Thickness(0, 2, 0, 2), Margin = new Thickness(0, 0, 0, 8) }; + AutomationProperties.SetAutomationId(retry, "InstallUpdateButton"); + retry.Click += (_, _) => _ = InstallUpdateAsync(release); + // Too important to wait behind a dot: the user mustn't close Queueify without reading it. + GoTo(Page.Help); + ShowUpdateBar(InfoBarSeverity.Error, Loc.F("update.start_failed", release.Version), releases, retry, closable: false); + DispatcherQueue.TryEnqueue(DispatcherQueuePriority.Low, () => UpdateBar.StartBringIntoView()); + break; + } + case Restart.NotStarted: + { + // The new exe is in place; the next start uses it. _updating stays set, so it isn't + // downloaded again. OK closes the bar, and gives the keyboard somewhere to be meanwhile. + var ok = new Button { Content = Loc.T("update.ok") }; + ok.Click += (_, _) => UpdateBar.IsOpen = false; + ShowUpdateBar(InfoBarSeverity.Warning, Loc.F("update.restart_failed", release.Version), ok, null, closable: true); + break; + } + } + } + + private static HashSet QueueifyProcesses() + { + var ids = new HashSet(); + foreach (var p in System.Diagnostics.Process.GetProcessesByName("Queueify")) + using (p) ids.Add(p.Id); + return ids; + } + + /// A Queueify window from a process that wasn't running before (another copy open already doesn't count). + private static bool NewQueueifyWindow(HashSet before) + { + var found = false; + foreach (var p in System.Diagnostics.Process.GetProcessesByName("Queueify")) + using (p) + found |= !before.Contains(p.Id) && p.MainWindowHandle != 0; + return found; + } + + private void ShowUpdateProblem(string message, AppRelease release, bool retry) + { + var page = new HyperlinkButton { Content = Loc.T("update.page"), Padding = new Thickness(0, 2, 0, 2), Margin = new Thickness(0, 0, 0, 8) }; + page.Click += (_, _) => OpenInBrowser(release.Page); + ShowUpdateBar(InfoBarSeverity.Warning, message, retry ? InstallButton(release, "update.retry") : null, page, closable: true); + } + + private void ShowUpdateBar(InfoBarSeverity severity, string message, Microsoft.UI.Xaml.Controls.Primitives.ButtonBase? action, UIElement? content, bool closable) + { + // Keyboard focus in the bar (on the button just pressed) moves to the new button (Cancel, Try again) + // instead of falling into the page when that button goes away. Anywhere else, it stays: someone + // typing in the search box keeps typing there, and a key never presses Try again by surprise. + var focusInBar = IsInside(FocusManager.GetFocusedElement(Root.XamlRoot) as DependencyObject, UpdateBar); + var wasOpen = UpdateBar.IsOpen; + UpdateBar.Severity = severity; + UpdateBar.Message = message; + UpdateBar.ActionButton = action; + UpdateBar.Content = content; + UpdateBar.IsClosable = closable; + UpdateBar.IsOpen = true; + // A problem while the user is on another page: the dot comes back, and a note says what happened. + if (_page != Page.Help && severity is InfoBarSeverity.Warning or InfoBarSeverity.Error) + { + SetUpdateBadge(true, problem: true); + ShowUpdateToast(message, severity); + } + // Opening, the bar announces itself; later states are said here. + if (wasOpen) Announce(UpdateBar, message); + // Only grows while open, so the page below doesn't jump up and down from one state to the next. + if (wasOpen) UpdateBar.MinHeight = Math.Max(UpdateBar.MinHeight, UpdateBar.ActualHeight); + if (focusInBar && ((Control?)action ?? content as Control) is { IsTabStop: true } target) + target.Loaded += (_, _) => target.Focus(FocusState.Keyboard); + } + + private static bool IsInside(DependencyObject? element, DependencyObject container) + { + for (; element != null; element = VisualTreeHelper.GetParent(element)) + if (element == container) return true; + return false; + } + + private static void Announce(UIElement element, string text) => + (FrameworkElementAutomationPeer.FromElement(element) ?? FrameworkElementAutomationPeer.CreatePeerForElement(element)) + ?.RaiseNotificationEvent(AutomationNotificationKind.Other, AutomationNotificationProcessing.ImportantMostRecent, text, "QueueifyUpdate"); + private static void OpenInBrowser(Uri page) => + System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(page.AbsoluteUri) { UseShellExecute = true }); + + private void OnOpenDataFolder(object sender, RoutedEventArgs e) + { + Directory.CreateDirectory(AppData.Folder); + System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(AppData.Folder) { UseShellExecute = true }); + } + + private int _tourStep; + + /// The four stops of the quick tour: what to point at and what to say. + private (FrameworkElement Target, string Title, string Text)[] TourSteps => + [ + (SearchBox, Loc.T("pane.search"), Loc.T("tour.1")), + (QueueNav, Loc.T("tour.2.title"), Loc.T("tour.2")), + (PhotoNav, Loc.T("tour.3.title"), Loc.T("tour.3")), + (SyncNav, Loc.T("tour.4.title"), Loc.T("tour.4")), + ]; + + private void ShowTourStep(int step) + { + var steps = TourSteps; + if (step >= steps.Length) + { + EndTour(); + return; + } + _tourStep = step; + if (step == 0) + { + // Seen as soon as it starts, so however it ends (even closing the app) it won't nag again. + _ui.TourSeen = true; + _ui.Save(); + GoTo(Page.Queue); + if (!_ui.PaneVisible) SetPaneVisible(true); + } + + var (target, title, text) = steps[step]; + Tour.IsOpen = false; + Tour.Target = target; + Tour.Title = Loc.F("tour.counter", title, step + 1, steps.Length); + Tour.Subtitle = text; + Tour.ActionButtonContent = Loc.T(step == steps.Length - 1 ? "tour.done" : "tour.next"); + Tour.IsOpen = true; + } + + private void OnTourNext(TeachingTip sender, object args) => ShowTourStep(_tourStep + 1); + + private void OnTourClosed(TeachingTip sender, object args) => EndTour(); + + private void EndTour() + { + Tour.IsOpen = false; + _ui.TourSeen = true; + _ui.Save(); + } + + private void OnReplayTour(object sender, RoutedEventArgs e) => ShowTourStep(0); +} diff --git a/Queueify/MainWindow.xaml.cs b/Queueify/MainWindow.xaml.cs index c60820f..bc148e4 100644 --- a/Queueify/MainWindow.xaml.cs +++ b/Queueify/MainWindow.xaml.cs @@ -771,801 +771,6 @@ private void ShowToast(string message, Action? undo = null, string? actionText = _toastTimer.Start(); } - // ───────────────────────── Magazine photo (OCR) ───────────────────────── - - private async void OnOpenPhoto(object sender, RoutedEventArgs e) - { - var picker = new FileOpenPicker { SuggestedStartLocation = PickerLocationId.PicturesLibrary }; - foreach (var ext in new[] { ".jpg", ".jpeg", ".png", ".bmp", ".webp", ".heic", ".tif", ".tiff" }) - picker.FileTypeFilter.Add(ext); - WinRT.Interop.InitializeWithWindow.Initialize(picker, WinRT.Interop.WindowNative.GetWindowHandle(this)); - - await GuardPhotoAsync(async () => - { - if (await picker.PickSingleFileAsync() is StorageFile file) - await LoadPhotoFromFileAsync(file); - }); - } - - /// - /// Photo files can be locked, cloud-only or unreadable, and the clipboard can be busy: show the - /// problem on the photo page instead of letting it crash the app. - /// - private async Task GuardPhotoAsync(Func work) - { - try - { - await work(); - } - catch (Exception ex) - { - GoTo(Page.Photo); - ShowOcrInfo(InfoBarSeverity.Error, Loc.F("photo.open_failed", ex.Message)); - } - } - - private void OnPastePhoto(object sender, RoutedEventArgs e) => _ = GuardPhotoAsync(() => PastePhotoAsync(reportEmpty: true)); - - private void OnPasteShortcut(KeyboardAccelerator sender, KeyboardAcceleratorInvokedEventArgs args) - { - // Text boxes keep their normal paste; anywhere else Ctrl+V loads an image. - if (FocusManager.GetFocusedElement(Root.XamlRoot) is TextBox or PasswordBox) return; - args.Handled = true; - _ = GuardPhotoAsync(() => PastePhotoAsync(reportEmpty: false)); - } - - private async Task PastePhotoAsync(bool reportEmpty) - { - var content = Clipboard.GetContent(); - if (content.Contains(StandardDataFormats.Bitmap)) - { - using var stream = await (await content.GetBitmapAsync()).OpenReadAsync(); - await LoadPhotoAsync(stream); - } - else if (content.Contains(StandardDataFormats.StorageItems) - && (await content.GetStorageItemsAsync()).OfType().FirstOrDefault() is { } file) - { - await LoadPhotoFromFileAsync(file); - } - else if (reportEmpty) - { - GoTo(Page.Photo); - ShowOcrInfo(InfoBarSeverity.Informational, Loc.T("photo.clipboard_empty")); - } - } - - private void OnPhotoDragOver(object sender, DragEventArgs e) - { - if (e.DataView.Contains(StandardDataFormats.StorageItems) || e.DataView.Contains(StandardDataFormats.Bitmap)) - { - e.AcceptedOperation = DataPackageOperation.Copy; - e.DragUIOverride.Caption = Loc.T("photo.drop_caption"); - } - } - - private async void OnPhotoDrop(object sender, DragEventArgs e) - { - var deferral = e.GetDeferral(); - try - { - await GuardPhotoAsync(async () => - { - if (e.DataView.Contains(StandardDataFormats.StorageItems) - && (await e.DataView.GetStorageItemsAsync()).OfType().FirstOrDefault() is { } file) - { - await LoadPhotoFromFileAsync(file); - } - else if (e.DataView.Contains(StandardDataFormats.Bitmap)) - { - using var stream = await (await e.DataView.GetBitmapAsync()).OpenReadAsync(); - await LoadPhotoAsync(stream); - } - }); - } - finally - { - deferral.Complete(); - } - } - - private async Task LoadPhotoFromFileAsync(StorageFile file) - { - using var stream = await file.OpenAsync(FileAccessMode.Read); - await LoadPhotoAsync(stream); - } - - private async Task LoadPhotoAsync(IRandomAccessStream stream) - { - GoTo(Page.Photo); - if (AddPane.Visibility != Visibility.Visible) SetPaneVisible(true); - ShowOcrInfo(InfoBarSeverity.Informational, Loc.T("photo.reading")); - - OcrPage page; - try - { - page = await OcrService.RecognizeAsync(stream, _ui.OcrLanguage); - } - catch (Exception ex) - { - ShowOcrInfo(InfoBarSeverity.Error, - Loc.F("photo.read_failed", ex.Message)); - return; - } - - var source = new SoftwareBitmapSource(); - await source.SetBitmapAsync(page.Bitmap); - double width = page.Bitmap.PixelWidth, height = page.Bitmap.PixelHeight; - PhotoImage.Source = source; - PhotoImage.Width = LineCanvas.Width = width; - PhotoImage.Height = LineCanvas.Height = height; - PhotoHint.Visibility = Visibility.Collapsed; - - LineCanvas.Children.Clear(); - var accent = (Color)Application.Current.Resources["SystemAccentColor"]; - var idle = new SolidColorBrush(Color.FromArgb(36, accent.R, accent.G, accent.B)); - var stroke = new SolidColorBrush(accent); - var style = (Style)Root.Resources["PhotoLineButton"]; - foreach (var line in page.Lines) - { - var box = new Button - { - Style = style, - Width = line.Bounds.Width + 8, - Height = line.Bounds.Height + 6, - Background = idle, - BorderBrush = stroke, - Tag = line.Text, - }; - AutomationProperties.SetName(box, line.Text); - ToolTipService.SetToolTip(box, line.Text); - box.Click += OnLineClicked; - Canvas.SetLeft(box, line.Bounds.X - 4); - Canvas.SetTop(box, line.Bounds.Y - 3); - LineCanvas.Children.Add(box); - } - - _startFreshFromPhoto = true; - if (page.Lines.Count == 0) - ShowOcrInfo(InfoBarSeverity.Warning, Loc.T("photo.no_text")); - else if (!page.IsSpanish && !OcrService.SpanishAvailable && !_ui.OcrHintDismissed) - ShowSpanishOcrWarning(page.LanguageName); - else - OcrInfo.IsOpen = false; - - DispatcherQueue.TryEnqueue(DispatcherQueuePriority.Low, FitPhoto); - } - - private void OnFitPhoto(object sender, RoutedEventArgs e) => FitPhoto(); - - private void FitPhoto() - { - if (PhotoImage.Width is not > 0) return; - float zoom = (float)Math.Clamp(PhotoScroller.ViewportWidth / PhotoImage.Width, 0.1, 1.0); - PhotoScroller.ChangeView(0, 0, zoom, true); - } - - /// - /// A click on a line of the photo puts it in the search box: the first click after an album - /// was added starts a new search, later clicks are appended (artist, then album). - /// - private void OnLineClicked(object sender, RoutedEventArgs e) - { - if (sender is not Button { Tag: string raw } box) return; - var (text, year) = OcrService.CleanLine(raw); - box.Opacity = 0.45; - - var current = SearchBox.Text.Trim(); - var next = _startFreshFromPhoto || current.Length == 0 ? text : $"{current} {text}"; - if (year != null && !next.Contains(year.Value.ToString())) next = $"{next} {year}".Trim(); - _startFreshFromPhoto = false; - - SearchBox.Text = next; - SearchBox.SelectionStart = next.Length; - SearchBox.Focus(FocusState.Programmatic); - } - - private void ShowOcrInfo(InfoBarSeverity severity, string message) - { - OcrInfo.ActionButton = null; - OcrInfo.Content = null; - OcrInfo.Severity = severity; - OcrInfo.Message = message; - OcrInfo.IsOpen = true; - } - - /// - /// The Photo page's offer to install Spanish text recognition. It can be dismissed for good; - /// Settings → Text recognition still offers it. - /// - private void ShowSpanishOcrWarning(string? usedLanguage) - { - // Installed earlier in this run: it only needs Queueify to restart, not another install. - if (OcrService.PendingRestartTags.FirstOrDefault(t => t.StartsWith("es", StringComparison.OrdinalIgnoreCase)) is string pending) - { - ShowPhotoOcrOffer(InfoBarSeverity.Informational, - Loc.F("ocr.installed_restart_app", OcrLanguages.NameInSentence(pending)), OcrOffer.Restart | OcrOffer.Dismiss); - return; - } - ShowPhotoOcrOffer(InfoBarSeverity.Warning, - usedLanguage != null ? Loc.F("ocr.no_spanish_as", usedLanguage) : Loc.T("ocr.no_spanish"), - OcrOffer.Retry | OcrOffer.Dismiss); - } - - /// - /// The Photo page's message with the actions that make sense next: install (again), restart, - /// Windows language settings, or "Don't show this again". - /// - private void ShowPhotoOcrOffer(InfoBarSeverity severity, string message, OcrOffer offer) - { - ShowOcrInfo(severity, message); - if (offer.HasFlag(OcrOffer.Retry)) - { - var install = new Button { Content = Loc.T("ocr.install_spanish") }; - install.Click += async (_, _) => - { - install.IsEnabled = false; - install.Content = Loc.T("ocr.installing"); - await InstallOcrLanguageAsync("es-ES", ShowPhotoOcrOffer); - }; - OcrInfo.ActionButton = install; - } - else if (offer.HasFlag(OcrOffer.Restart)) - { - OcrInfo.ActionButton = RestartButton(); - } - - var links = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4 }; - if (offer.HasFlag(OcrOffer.WindowsSettings)) - { - var windows = new HyperlinkButton { Content = Loc.T("settings.ocr.windows") }; - windows.Click += OnOpenWindowsLanguages; - links.Children.Add(windows); - } - if (offer.HasFlag(OcrOffer.Dismiss) && !_ui.OcrHintDismissed) - { - var dismiss = new HyperlinkButton { Content = Loc.T("ocr.dismiss") }; - dismiss.Click += (_, _) => - { - _ui.OcrHintDismissed = true; - _ui.Save(); - OcrInfo.IsOpen = false; - }; - links.Children.Add(dismiss); - } - if (links.Children.Count > 0) OcrInfo.Content = links; - } - - /// - /// Installs a text recognition language and explains every outcome: done, needs a restart, - /// permission declined or not allowed, window closed, Windows Update error, or another install - /// still running. gets what to say and what to offer next. - /// - private async Task InstallOcrLanguageAsync(string tag, Action report) - { - var name = OcrLanguages.NameInSentence(tag); - OcrInstallOutcome outcome; - try - { - var install = OcrService.InstallAsync(tag); - if (_page == Page.Settings) FillOcrSettings(); // shows it as running - outcome = await install; - } - catch (Exception ex) - { - outcome = new OcrInstallOutcome(OcrInstallResult.Failed, ex.Message); - } - - var offer = OcrService.OfferAfter(outcome.Result); - switch (outcome.Result) - { - case OcrInstallResult.Installed: - report(InfoBarSeverity.Success, Loc.F("ocr.installed", name), offer); - break; - case OcrInstallResult.RestartApp: - report(InfoBarSeverity.Success, Loc.F("ocr.installed_restart_app", name), offer); - break; - case OcrInstallResult.RestartWindows: - report(InfoBarSeverity.Warning, Loc.F("ocr.installed_restart_windows", name), offer); - break; - case OcrInstallResult.Cancelled: - report(InfoBarSeverity.Informational, - Loc.T("ocr.cancelled"), offer); - break; - case OcrInstallResult.Interrupted: - report(InfoBarSeverity.Warning, - Loc.T("ocr.interrupted"), offer); - break; - case OcrInstallResult.Busy: - report(InfoBarSeverity.Informational, Loc.T("ocr.busy"), offer); - break; - case OcrInstallResult.Blocked: - report(InfoBarSeverity.Warning, - Loc.F("ocr.blocked", outcome.Error), offer); - break; - default: - var detail = outcome.Error != null ? Loc.F("ocr.windows_said", outcome.Error) : ""; - report(InfoBarSeverity.Error, Loc.F("ocr.failed", name, detail), offer); - break; - } - if (_page == Page.Settings) FillOcrSettings(); - } - - private Button RestartButton() - { - var restart = new Button { Content = Loc.T("app.restart") }; - restart.Click += (_, _) => _ = RestartAppAsync(); - return restart; - } - - private enum Restart { Closed, NotStarted, StarterFailed } - - /// - /// Starts a fresh copy and closes this one (which saves the window and layout as usual). Through the - /// download's starter, this window stays until the starter has unpacked the new copy and its window is - /// open, so there's never a moment without Queueify on screen, nor two of them. - /// - private async Task RestartAppAsync() - { - // A second click while the new copy starts would start another one. - if (_restarting) return Restart.Closed; - _restarting = true; - // Saved first, so the new copy opens where this one was. - SaveWindow(); - System.Diagnostics.Process? started; - var running = QueueifyProcesses(); - try - { - // Through the download's starter when there is one, so the new copy knows it too. - started = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(AppData.StarterExe ?? Environment.ProcessPath!) { UseShellExecute = false }); - } - catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException) - { - ShowToast(Loc.F("app.restart_failed", ex.Message), severity: InfoBarSeverity.Warning); - _restarting = false; - return Restart.NotStarted; - } - using (started) - { - if (started != null && AppData.StarterExe != null) - { - // However long the first unpack takes, or the starter's message waits to be read: until - // it's done, nothing else is running. - await started.WaitForExitAsync(); - if (started.ExitCode != 0) - { - // The starter showed its own message about what went wrong. - _restarting = false; - return Restart.StarterFailed; - } - // The new copy runs; its window takes a moment more. A minute at most, then this one goes anyway. - for (int i = 0; i < 300 && !NewQueueifyWindow(running); i++) - await Task.Delay(200); - } - } - Close(); - return Restart.Closed; - } - private bool _restarting; - - // ───────────────────────── Sync between PCs ───────────────────────── - - private void ScheduleSync() - { - if (!_settings.SyncConfigured) return; - _syncDebounce.Stop(); - _syncDebounce.Start(); - } - - private Task? _syncTask; - private Task? _followUpSync; - private bool _syncSetupRunning; // the setup dialog is trying a connection: no other sync may run - - /// - /// Downloads other PCs' changes and uploads this PC's. Returns an error message, or null when it - /// worked (or sync isn't set up). If a sync is already running, one more runs right after it and - /// the caller gets that result, so "Sync now" never reports success for a sync that didn't happen. - /// Failures are harmless: pending changes stay and go up next time. - /// - private Task SyncNowAsync() - { - if (!_settings.SyncConfigured || _syncSetupRunning) return Task.FromResult(null); - if (_syncTask is { IsCompleted: false } running) - return _followUpSync ??= AfterAsync(running); - return _syncTask = RunSyncAsync(); - - async Task AfterAsync(Task previous) - { - await previous; - _followUpSync = null; - return await SyncNowAsync(); - } - } - - private async Task RunSyncAsync() - { - _lastSyncAttempt = DateTime.UtcNow; - SyncNav.Content = Loc.T("sync.syncing"); - - // Sync a copy: the UI thread keeps using _settings while the sync runs in the background. - var work = _settings.Clone(); - var provider = Provider(); - var sharedStampBefore = _settings.SharedSettingsUpdatedAt; - string? error = null; - try - { - var result = await Task.Run(() => provider.SyncAsync(_store, work, CancellationToken.None)); - if (_settings.SyncIdentity == work.SyncIdentity) // still connected to the same queue - { - _settings.CloudLastServerTime = work.CloudLastServerTime; - _settings.WebLastServerTime = work.WebLastServerTime; - _settings.WebSettingsSyncedAt = work.WebSettingsSyncedAt; - // Take downloaded keys/preferences unless the user saved Settings while this sync ran. - bool sharedChanged = _settings.SharedSettingsUpdatedAt == sharedStampBefore - && work.SharedSettingsUpdatedAt != sharedStampBefore; - if (sharedChanged) - { - var keysBefore = (KeysOf(MusicService.Tidal), KeysOf(MusicService.Spotify)); - _settings.CopySharedFrom(work); - _settings.Normalize(); - if (KeysOf(MusicService.Tidal) != keysBefore.Item1) ForgetTestResult(MusicService.Tidal); - if (KeysOf(MusicService.Spotify) != keysBefore.Item2) ForgetTestResult(MusicService.Spotify); - } - AppData.SaveSettings(_settings); - - if (result.SettingsChanged && sharedChanged) - { - ApplyPreferredService(); - UpdateSetupInfo(); - _resultsQuery = null; - if (_page == Page.Settings) FillSettingsPage(keepTypedKeys: true); - } - if (result.Downloaded > 0 || result.SettingsChanged) - { - _all = _store.LoadAll(); - RefreshQueue(); - } - _lastSynced = DateTime.Now; - } - } - catch (Exception ex) - { - error = DescribeSyncError(ex); - } - - _syncError = _settings.SyncConfigured ? error : null; - UpdateSyncButton(); - return error; - } - - private static string DescribeSyncError(Exception ex) => ex switch - { - CatalogException or SyncException => ex.Message, - HttpRequestException => Loc.T("sync.err.offline"), - TaskCanceledException => Loc.T("sync.err.timeout"), - IOException or UnauthorizedAccessException => Loc.F("sync.err.disk", ex.Message), - _ => Loc.F("sync.err.other", ex.Message), - }; - - /// The Sync icon in the navigation bar shows the state; its tooltip says why. - private void UpdateSyncButton() - { - string label, glyph, tip; - bool web = _settings.WebConfigured; - if (!_settings.SyncConfigured) - (label, glyph, tip) = (Loc.T("nav.sync"), "", Loc.T("sync.tip.off")); - else if (_syncError != null) - (label, glyph, tip) = (Loc.T("sync.not_synced"), "", Loc.F("sync.tip.error", _syncError)); - else - (label, glyph, tip) = (Loc.T("sync.synced"), "", - _lastSynced is DateTime t ? web ? Loc.F("webSync.tip.at", t) : Loc.F("sync.tip.at", t) - : web ? Loc.T("webSync.tip.ok") : Loc.T("sync.tip.ok")); - - SyncNav.Content = label; - SyncIcon.Glyph = SettingsSyncIcon.Glyph = glyph; - SettingsSyncStatus.Text = tip; - ToolTipService.SetToolTip(SyncNav, tip); - Microsoft.UI.Xaml.Automation.AutomationProperties.SetName(SyncNav, tip); - } - - private async void OnSync(object sender, RoutedEventArgs e) - { - switch (_settings.ActiveSync) - { - case SyncKind.Web: await ShowWebSyncConnectedAsync(); break; - case SyncKind.Cloud: await ShowSyncConnectedAsync(); break; - default: await ShowSyncSetupAsync(); break; - } - } - - /// First-time setup: create the online queue (first PC) or join it with a sync code. - private async Task ShowSyncSetupAsync() - { - var create = new RadioButton { Content = Loc.T("sync.setup.create"), GroupName = "sync", IsChecked = true }; - var join = new RadioButton { Content = Loc.T("sync.setup.join"), GroupName = "sync" }; - var web = new RadioButton { Content = Loc.T("webSync.setup.option"), GroupName = "sync" }; - - var projectBox = new TextBox { Header = Loc.T("sync.project"), PlaceholderText = Loc.T("sync.project.placeholder") }; - var copyRules = new Button { Content = Loc.T("sync.copy_rules") }; - copyRules.Click += (_, _) => - { - CopyToClipboard(CloudSync.SecurityRules); - copyRules.Content = Loc.T("sync.rules_copied"); - }; - var createPanel = new StackPanel { Spacing = 10 }; - createPanel.Children.Add(Paragraph( - Loc.T("sync.setup.steps"))); - createPanel.Children.Add(new HyperlinkButton { Content = Loc.T("sync.console"), NavigateUri = new Uri("https://console.firebase.google.com/") }); - createPanel.Children.Add(copyRules); - createPanel.Children.Add(projectBox); - - var codeBox = new TextBox { Header = Loc.T("sync.code"), PlaceholderText = "queueify:…" }; - var joinPanel = new StackPanel { Spacing = 10, Visibility = Visibility.Collapsed }; - joinPanel.Children.Add(Paragraph( - Loc.T("sync.setup.join_text"))); - joinPanel.Children.Add(codeBox); - - var webBox = new TextBox { Header = Loc.T("webSync.code"), PlaceholderText = Loc.T("webSync.code.placeholder") }; - var webPanel = new StackPanel { Spacing = 10, Visibility = Visibility.Collapsed }; - webPanel.Children.Add(Paragraph(Loc.T("webSync.setup.text"))); - webPanel.Children.Add(webBox); - webPanel.Children.Add(Paragraph(Loc.T("webSync.keys_notice"))); - - void ShowOnly(StackPanel shown) - { - foreach (var p in new[] { createPanel, joinPanel, webPanel }) - p.Visibility = p == shown ? Visibility.Visible : Visibility.Collapsed; - } - create.Checked += (_, _) => ShowOnly(createPanel); - join.Checked += (_, _) => ShowOnly(joinPanel); - web.Checked += (_, _) => ShowOnly(webPanel); - - var progress = new ProgressBar { IsIndeterminate = true, Visibility = Visibility.Collapsed }; - var error = new InfoBar { Severity = InfoBarSeverity.Error, IsClosable = false, IsOpen = false }; - - var panel = new StackPanel { Spacing = 12, Width = 480 }; - panel.Children.Add(Paragraph(Loc.T("sync.setup.intro"))); - panel.Children.Add(create); - panel.Children.Add(join); - panel.Children.Add(web); - panel.Children.Add(createPanel); - panel.Children.Add(joinPanel); - panel.Children.Add(webPanel); - panel.Children.Add(progress); - panel.Children.Add(error); - - var dialog = new ContentDialog - { - Title = Loc.T("sync.title"), - Content = new ScrollViewer { Content = panel, MaxHeight = 600 }, - PrimaryButtonText = Loc.T("sync.connect"), - CloseButtonText = Loc.T("dialog.cancel"), - DefaultButton = ContentDialogButton.Primary, - XamlRoot = Root.XamlRoot, - }; - - bool joined = false, toWeb = false; - dialog.PrimaryButtonClick += async (d, args) => - { - var deferral = args.GetDeferral(); - try - { - string project = "", key = "", webUrl = "", webToken = ""; - toWeb = web.IsChecked == true; - joined = toWeb || join.IsChecked == true; - if (toWeb) - { - if (!SyncConnect.TryParse(webBox.Text, out webUrl, out webToken)) - { - Fail(Loc.T("webSync.bad_code")); - return; - } - } - else if (joined) - { - if (!CloudSync.TryParseSyncCode(codeBox.Text, out project, out key)) - { - Fail(Loc.T("sync.bad_code")); - return; - } - } - else - { - if (CloudSync.NormalizeProjectId(projectBox.Text) is not string id) - { - Fail(Loc.T("sync.no_project")); - return; - } - project = id; - key = CloudSync.NewQueueKey(); - } - - SyncTarget target = toWeb ? SyncTarget.Web(webUrl, webToken) - : joined ? SyncTarget.JoinCloud(project, key) - : SyncTarget.CreateCloud(project, key); - - progress.Visibility = Visibility.Visible; - error.IsOpen = false; - d.IsPrimaryButtonEnabled = false; - string? problem = null; - AppSettings? trial = null; - // A debounced sync of the old queue must not run between "mark everything" and the first sync here. - _syncDebounce.Stop(); - _syncSetupRunning = true; - try - { - trial = await SyncSetup.TryConnectAsync(_store, _settings, target, _cloud, _web, _syncTask, CancellationToken.None); - } - catch (Exception ex) - { - problem = DescribeSyncError(ex); - } - finally - { - _syncSetupRunning = false; - } - progress.Visibility = Visibility.Collapsed; - d.IsPrimaryButtonEnabled = true; - - if (trial == null) - { - Fail(problem!); - return; - } - - _settings = trial; - AppData.SaveSettings(_settings); - ApplyPreferredService(); - UpdateSetupInfo(); - _all = _store.LoadAll(); - RefreshQueue(); - _syncError = null; - _lastSynced = DateTime.Now; - UpdateSyncButton(); - } - catch (Exception ex) - { - Fail(DescribeSyncError(ex)); - } - finally - { - deferral.Complete(); - } - - void Fail(string message) - { - error.Message = message; - error.IsOpen = true; - args.Cancel = true; - } - }; - - if (await ShowDialogAsync(dialog) != ContentDialogResult.Primary || !_settings.SyncConfigured) return; - - if (toWeb) - ShowToast(Loc.F("webSync.joined", QueueText.Albums(_all.Count))); - else if (joined) - ShowToast(Loc.F("sync.joined", QueueText.Albums(_all.Count))); - else - await ShowSyncConnectedAsync(justCreated: true); - } - - /// Shows the sync code for other PCs, plus "Sync now" and "Disconnect". - private async Task ShowSyncConnectedAsync(bool justCreated = false) - { - var code = CloudSync.SyncCode(_settings); - var codeBox = new TextBox { Header = Loc.T("sync.code"), Text = code, IsReadOnly = true, TextWrapping = TextWrapping.Wrap }; - var copy = new Button { Content = Loc.T("sync.copy_code") }; - copy.Click += (_, _) => - { - CopyToClipboard(code); - copy.Content = Loc.T("sync.copied"); - }; - - var status = _syncError ?? (_lastSynced is DateTime t ? Loc.F("sync.last", t) : Loc.T("sync.ok")); - var panel = new StackPanel { Spacing = 12, Width = 480 }; - panel.Children.Add(Paragraph(justCreated - ? Loc.T("sync.done") - : Loc.F("sync.this_pc", _settings.CloudProjectId, status))); - panel.Children.Add(Paragraph( - Loc.T("sync.add_pc"))); - panel.Children.Add(codeBox); - panel.Children.Add(copy); - panel.Children.Add(Paragraph(Loc.T("sync.private"))); - - var dialog = new ContentDialog - { - Title = Loc.T("sync.title"), - Content = new ScrollViewer { Content = panel, MaxHeight = 560 }, - PrimaryButtonText = Loc.T("sync.now"), - SecondaryButtonText = Loc.T("sync.disconnect"), - CloseButtonText = Loc.T("dialog.close"), - DefaultButton = ContentDialogButton.Close, - XamlRoot = Root.XamlRoot, - }; - - switch (await ShowDialogAsync(dialog)) - { - case ContentDialogResult.Primary: - var problem = await SyncNowAsync(); - ShowToast(problem ?? Loc.T("sync.ok"), severity: problem == null ? InfoBarSeverity.Success : InfoBarSeverity.Warning); - break; - case ContentDialogResult.Secondary: - _settings.DisconnectCloud(); - _syncError = null; - AppData.SaveSettings(_settings); - UpdateSyncButton(); - ShowToast(Loc.T("sync.disconnected"), - severity: InfoBarSeverity.Informational); - break; - } - } - - /// Shows which web server this PC syncs with, plus "Sync now" and "Disconnect". - private async Task ShowWebSyncConnectedAsync() - { - // Only the host is shown; the token stays out of the window. - var host = Uri.TryCreate(_settings.WebServerUrl, UriKind.Absolute, out var address) ? address.Authority : "?"; - var status = _syncError ?? (_lastSynced is DateTime t ? Loc.F("sync.last", t) : Loc.T("sync.ok")); - var panel = new StackPanel { Spacing = 12, Width = 480 }; - panel.Children.Add(Paragraph(Loc.F("webSync.this_pc", host, status))); - panel.Children.Add(Paragraph(Loc.T("webSync.private"))); - - var dialog = new ContentDialog - { - Title = Loc.T("sync.title"), - Content = new ScrollViewer { Content = panel, MaxHeight = 560 }, - PrimaryButtonText = Loc.T("sync.now"), - SecondaryButtonText = Loc.T("sync.disconnect"), - CloseButtonText = Loc.T("dialog.close"), - DefaultButton = ContentDialogButton.Close, - XamlRoot = Root.XamlRoot, - }; - - switch (await ShowDialogAsync(dialog)) - { - case ContentDialogResult.Primary: - var problem = await SyncNowAsync(); - ShowToast(problem ?? Loc.T("sync.ok"), severity: problem == null ? InfoBarSeverity.Success : InfoBarSeverity.Warning); - break; - case ContentDialogResult.Secondary: - _settings.DisconnectWeb(); - _syncError = null; - AppData.SaveSettings(_settings); - UpdateSyncButton(); - ShowToast(Loc.T("webSync.disconnected"), severity: InfoBarSeverity.Informational); - break; - } - } - - private bool _dialogOpen; - - /// - /// WinUI allows one ContentDialog at a time and throws on a second; a quick double-click on Sync - /// or Settings would otherwise crash the app. A second request while one is open is ignored. - /// - private async Task ShowDialogAsync(ContentDialog dialog) - { - if (_dialogOpen) return ContentDialogResult.None; - _dialogOpen = true; - // Dialogs live outside the window's element tree, so they don't inherit the chosen theme. - dialog.RequestedTheme = Root.ActualTheme; - try - { - return await dialog.ShowAsync(); - } - finally - { - _dialogOpen = false; - } - } - - private static void CopyToClipboard(string text) - { - var package = new DataPackage(); - package.SetText(text); - Clipboard.SetContent(package); - } - // ───────────────────────── Help & quick tour ───────────────────────── private void FillHelp() @@ -1577,693 +782,4 @@ private void FillHelp() AboutDataPath.Text = AppData.Folder; } - // ───────────────────────── Updates ───────────────────────── - - private bool _checkingUpdates; - /// Asked from About: the running check shows its result there. - private bool _reportCheck; - private CancellationTokenSource? _download; - - private async void OnCheckForUpdates(object sender, RoutedEventArgs e) => await CheckForUpdatesAsync(quiet: false); - - /// - /// Asks GitHub for a newer version and offers it under the page title. Quiet (at start) shows nothing - /// unless there is one; from About, the result shows under the button. - /// - private async Task CheckForUpdatesAsync(bool quiet) - { - // One check at a time. Asked from About while the quiet one at start runs, that one reports there - // when it's done. The button stays enabled, so keyboard focus stays on it. - if (!quiet) - { - _reportCheck = true; - ShowUpdateStatus(Loc.T("update.checking")); - } - if (_checkingUpdates) return; - _checkingUpdates = true; - try - { - var release = await _updater.CheckAsync(AppInfo.Version, CancellationToken.None); - if (release != null && !_updating && Updater.IsWanted(release, _ui.SkippedVersion, asked: _reportCheck)) - { - OfferUpdate(release); - // Found while on another page: a dot on Help and a short note say so; the offer itself waits - // in About. - if (_page != Page.Help) - { - SetUpdateBadge(true); - ShowUpdateToast(Loc.F("update.available", release.Version), InfoBarSeverity.Informational); - } - } - // The offer, right above, already says what's new; the line under the button says the rest. - if (_reportCheck) ShowUpdateStatus(release != null ? "" : Loc.T("update.latest")); - } - catch (Exception ex) - { - // UpdateException carries its own message; anything else is a bug, still not worth a crash. - if (_reportCheck) ShowUpdateStatus(ex is UpdateException ? ex.Message : Loc.F("update.failed", ex.Message)); - } - finally - { - _checkingUpdates = false; - _reportCheck = false; - } - } - - private void ShowUpdateStatus(string text) - { - UpdateStatus.Text = text; - if (text.Length == 0) return; - // At the bottom of Help, maybe below the window's edge; and said aloud for screen readers. - UpdateStatus.StartBringIntoView(); - Announce(UpdateStatus, text); - } - - private void OfferUpdate(AppRelease release) - { - var whatsNew = new HyperlinkButton { Content = Loc.T("update.whats_new"), Padding = new Thickness(0, 2, 0, 2) }; - whatsNew.Click += (_, _) => OpenInBrowser(release.Page); - // Not now, and not at the next starts either; Check for updates in About still finds it. - var skip = new HyperlinkButton { Content = Loc.T("update.skip"), Padding = new Thickness(0, 2, 0, 2) }; - AutomationProperties.SetAutomationId(skip, "SkipUpdateButton"); - skip.Click += (_, _) => - { - _ui.SkippedVersion = release.Version; - _ui.Save(); - UpdateBar.IsOpen = false; - SetUpdateBadge(false); - }; - var links = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 20, Margin = new Thickness(0, 0, 0, 8), Children = { whatsNew, skip } }; - ShowUpdateBar(InfoBarSeverity.Informational, Loc.F("update.available", release.Version), InstallButton(release, "update.install"), links, closable: true); - } - - private Button InstallButton(AppRelease release, string text) - { - var install = new Button { Content = Loc.T(text), Style = (Style)Application.Current.Resources["AccentButtonStyle"] }; - AutomationProperties.SetAutomationId(install, "InstallUpdateButton"); - install.Click += (_, _) => _ = InstallUpdateAsync(release); - return install; - } - - /// Downloads the new exe, checks it, puts it in place of this one and restarts through it. - private async Task InstallUpdateAsync(AppRelease release) - { - if (_updating) return; - if (AppData.StarterExe is not { } exe) - { - // Running from a build folder, not a download: nothing to replace. - ShowUpdateProblem(Loc.T("update.manual"), release, retry: false); - return; - } - _updating = true; - var message = Loc.F("update.downloading", release.Version); - var bar = new ProgressBar { Maximum = 1, Margin = new Thickness(0, 0, 0, 12) }; - AutomationProperties.SetName(bar, message); - // No overall time limit: a slow download that keeps coming is fine, a stalled one gives up, and - // Cancel stops either. - var cancel = new Button { Content = Loc.T("update.cancel") }; - cancel.Click += (_, _) => _download?.Cancel(); - ShowUpdateBar(InfoBarSeverity.Informational, message, cancel, bar, closable: false); - _download = new CancellationTokenSource(); - try - { - var downloaded = await _updater.DownloadAsync(release, exe, new Progress(v => bar.Value = v), _download.Token); - Updater.Replace(exe, downloaded); - } - catch (OperationCanceledException) when (_download.IsCancellationRequested) - { - _updating = false; - OfferUpdate(release); - return; - } - catch (Exception ex) - { - _updating = false; - ShowUpdateProblem(ex is UpdateException ? ex.Message : Loc.F("update.failed", ex.Message), release, retry: true); - return; - } - finally - { - _download.Dispose(); - _download = null; - } - // The new version unpacks before its window opens: this one says so and stays until then. The - // keyboard waits on the progress indicator (named, so it's read out) instead of falling into the page. - var starting = Loc.F("update.restarting", release.Version); - var wait = new ProgressBar { IsIndeterminate = true, IsTabStop = true, Margin = new Thickness(0, 0, 0, 12) }; - AutomationProperties.SetName(wait, starting); - ShowUpdateBar(InfoBarSeverity.Informational, starting, null, wait, closable: false); - switch (await RestartAppAsync()) - { - case Restart.StarterFailed: - { - // The new exe itself didn't start (its starter said why), and it's the user's only Queueify - // exe now. What helps first is a version that works, maybe an older one if this release is - // broken: all of them are on the releases page. The same download again only helps when the - // cause was on this PC (disk space, an antivirus). - _updating = false; - var releases = new Button { Content = Loc.T("update.releases"), Style = (Style)Application.Current.Resources["AccentButtonStyle"] }; - releases.Click += (_, _) => OpenInBrowser(UpdateSource.AllReleases); - var retry = new HyperlinkButton { Content = Loc.T("update.retry"), Padding = new Thickness(0, 2, 0, 2), Margin = new Thickness(0, 0, 0, 8) }; - AutomationProperties.SetAutomationId(retry, "InstallUpdateButton"); - retry.Click += (_, _) => _ = InstallUpdateAsync(release); - // Too important to wait behind a dot: the user mustn't close Queueify without reading it. - GoTo(Page.Help); - ShowUpdateBar(InfoBarSeverity.Error, Loc.F("update.start_failed", release.Version), releases, retry, closable: false); - DispatcherQueue.TryEnqueue(DispatcherQueuePriority.Low, () => UpdateBar.StartBringIntoView()); - break; - } - case Restart.NotStarted: - { - // The new exe is in place; the next start uses it. _updating stays set, so it isn't - // downloaded again. OK closes the bar, and gives the keyboard somewhere to be meanwhile. - var ok = new Button { Content = Loc.T("update.ok") }; - ok.Click += (_, _) => UpdateBar.IsOpen = false; - ShowUpdateBar(InfoBarSeverity.Warning, Loc.F("update.restart_failed", release.Version), ok, null, closable: true); - break; - } - } - } - - private static HashSet QueueifyProcesses() - { - var ids = new HashSet(); - foreach (var p in System.Diagnostics.Process.GetProcessesByName("Queueify")) - using (p) ids.Add(p.Id); - return ids; - } - - /// A Queueify window from a process that wasn't running before (another copy open already doesn't count). - private static bool NewQueueifyWindow(HashSet before) - { - var found = false; - foreach (var p in System.Diagnostics.Process.GetProcessesByName("Queueify")) - using (p) - found |= !before.Contains(p.Id) && p.MainWindowHandle != 0; - return found; - } - - private void ShowUpdateProblem(string message, AppRelease release, bool retry) - { - var page = new HyperlinkButton { Content = Loc.T("update.page"), Padding = new Thickness(0, 2, 0, 2), Margin = new Thickness(0, 0, 0, 8) }; - page.Click += (_, _) => OpenInBrowser(release.Page); - ShowUpdateBar(InfoBarSeverity.Warning, message, retry ? InstallButton(release, "update.retry") : null, page, closable: true); - } - - private void ShowUpdateBar(InfoBarSeverity severity, string message, Microsoft.UI.Xaml.Controls.Primitives.ButtonBase? action, UIElement? content, bool closable) - { - // Keyboard focus in the bar (on the button just pressed) moves to the new button (Cancel, Try again) - // instead of falling into the page when that button goes away. Anywhere else, it stays: someone - // typing in the search box keeps typing there, and a key never presses Try again by surprise. - var focusInBar = IsInside(FocusManager.GetFocusedElement(Root.XamlRoot) as DependencyObject, UpdateBar); - var wasOpen = UpdateBar.IsOpen; - UpdateBar.Severity = severity; - UpdateBar.Message = message; - UpdateBar.ActionButton = action; - UpdateBar.Content = content; - UpdateBar.IsClosable = closable; - UpdateBar.IsOpen = true; - // A problem while the user is on another page: the dot comes back, and a note says what happened. - if (_page != Page.Help && severity is InfoBarSeverity.Warning or InfoBarSeverity.Error) - { - SetUpdateBadge(true, problem: true); - ShowUpdateToast(message, severity); - } - // Opening, the bar announces itself; later states are said here. - if (wasOpen) Announce(UpdateBar, message); - // Only grows while open, so the page below doesn't jump up and down from one state to the next. - if (wasOpen) UpdateBar.MinHeight = Math.Max(UpdateBar.MinHeight, UpdateBar.ActualHeight); - if (focusInBar && ((Control?)action ?? content as Control) is { IsTabStop: true } target) - target.Loaded += (_, _) => target.Focus(FocusState.Keyboard); - } - - private static bool IsInside(DependencyObject? element, DependencyObject container) - { - for (; element != null; element = VisualTreeHelper.GetParent(element)) - if (element == container) return true; - return false; - } - - private static void Announce(UIElement element, string text) => - (FrameworkElementAutomationPeer.FromElement(element) ?? FrameworkElementAutomationPeer.CreatePeerForElement(element)) - ?.RaiseNotificationEvent(AutomationNotificationKind.Other, AutomationNotificationProcessing.ImportantMostRecent, text, "QueueifyUpdate"); - private static void OpenInBrowser(Uri page) => - System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(page.AbsoluteUri) { UseShellExecute = true }); - - private void OnOpenDataFolder(object sender, RoutedEventArgs e) - { - Directory.CreateDirectory(AppData.Folder); - System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(AppData.Folder) { UseShellExecute = true }); - } - - private int _tourStep; - - /// The four stops of the quick tour: what to point at and what to say. - private (FrameworkElement Target, string Title, string Text)[] TourSteps => - [ - (SearchBox, Loc.T("pane.search"), Loc.T("tour.1")), - (QueueNav, Loc.T("tour.2.title"), Loc.T("tour.2")), - (PhotoNav, Loc.T("tour.3.title"), Loc.T("tour.3")), - (SyncNav, Loc.T("tour.4.title"), Loc.T("tour.4")), - ]; - - private void ShowTourStep(int step) - { - var steps = TourSteps; - if (step >= steps.Length) - { - EndTour(); - return; - } - _tourStep = step; - if (step == 0) - { - // Seen as soon as it starts, so however it ends (even closing the app) it won't nag again. - _ui.TourSeen = true; - _ui.Save(); - GoTo(Page.Queue); - if (!_ui.PaneVisible) SetPaneVisible(true); - } - - var (target, title, text) = steps[step]; - Tour.IsOpen = false; - Tour.Target = target; - Tour.Title = Loc.F("tour.counter", title, step + 1, steps.Length); - Tour.Subtitle = text; - Tour.ActionButtonContent = Loc.T(step == steps.Length - 1 ? "tour.done" : "tour.next"); - Tour.IsOpen = true; - } - - private void OnTourNext(TeachingTip sender, object args) => ShowTourStep(_tourStep + 1); - - private void OnTourClosed(TeachingTip sender, object args) => EndTour(); - - private void EndTour() - { - Tour.IsOpen = false; - _ui.TourSeen = true; - _ui.Save(); - } - - private void OnReplayTour(object sender, RoutedEventArgs e) => ShowTourStep(0); - - // ───────────────────────── Settings ───────────────────────── - - private void UpdateSetupInfo() => - SetupInfo.IsOpen = !_settings.SpotifyConfigured && !_settings.TidalConfigured; - - private void ApplyPreferredService() => - BacklogItem.Preferred = Enum.TryParse(_settings.PreferredService, out var s) ? s : MusicService.Tidal; - - /// "Open settings" in the Add albums panel. - private void OnSettings(object sender, RoutedEventArgs e) => GoTo(Page.Settings); - - /// - /// The values the Settings page shows. Edits are compared against it (AppSettings.ApplyEdits), - /// so a value a sync brought in while the page was open isn't overwritten by an untouched box. - /// - private AppSettings _settingsShown = new(); - - /// Set while the page fills its controls, so their change events don't save anything. - private bool _fillingSettings; - - /// - /// The last connection test per service failed with this message; KeysRejected tells a wrong key - /// apart from a network problem. Cleared when the keys change (here or from another PC). - /// - private readonly Dictionary _serviceProblem = []; - - /// Services whose keys are being tested right now. - private readonly HashSet _testing = []; - - /// Services whose current keys passed a test search in this session. - private readonly HashSet _verified = []; - - /// The keys changed (saved, removed, or synced from another PC): earlier test results no longer apply. - private void ForgetTestResult(MusicService service) - { - _serviceProblem.Remove(service); - _verified.Remove(service); - (service == MusicService.Tidal ? TidalCard : SpotifyCard).HideResult(); - } - - /// - /// Fills the page from the current settings. After a sync, keys the user is typing (boxes that - /// differ from what was shown) are kept, and so is what they were compared against. - /// - private void FillSettingsPage(bool keepTypedKeys = false) - { - _fillingSettings = true; - try - { - // Shown in standard form ("ar" as Argentina), and compared in that form, so picking - // nothing never counts as a change. - var shown = _settings.ForSettingsPage(); - if (keepTypedKeys && (TidalCard.ClientId != _settingsShown.TidalClientId || TidalCard.ClientSecret != _settingsShown.TidalClientSecret)) - { - shown.TidalClientId = _settingsShown.TidalClientId; - shown.TidalClientSecret = _settingsShown.TidalClientSecret; - } - else - { - TidalCard.ClientId = shown.TidalClientId; - TidalCard.ClientSecret = shown.TidalClientSecret; - } - if (keepTypedKeys && (SpotifyCard.ClientId != _settingsShown.SpotifyClientId || SpotifyCard.ClientSecret != _settingsShown.SpotifyClientSecret)) - { - shown.SpotifyClientId = _settingsShown.SpotifyClientId; - shown.SpotifyClientSecret = _settingsShown.SpotifyClientSecret; - } - else - { - SpotifyCard.ClientId = shown.SpotifyClientId; - SpotifyCard.ClientSecret = shown.SpotifyClientSecret; - } - _settingsShown = shown; - - if (!keepTypedKeys) - { - TidalCard.IsExpanded = !_settings.TidalConfigured; - SpotifyCard.IsExpanded = !_settings.SpotifyConfigured; - } - - PreferredBox.SelectedItem = shown.PreferredService; - var countries = Countries.Options(shown.CountryCode, CultureInfo.CurrentCulture); - CountryBox.ItemsSource = Items(countries); - CountryBox.SelectedItem = countries.FirstOrDefault(c => c.Code == shown.CountryCode); - ThemeBox.SelectedItem = ThemeBox.Items.OfType().FirstOrDefault(i => (string)i.Tag == _ui.Theme) - ?? ThemeBox.Items[0]; - LanguageBox.SelectedItem = LanguageBox.Items.OfType().FirstOrDefault(i => (string)i.Tag == _ui.Language) - ?? LanguageBox.Items[0]; - UpdateLanguageRestart(); - UpdateCheckToggle.IsOn = _ui.CheckForUpdates; - SettingsDataPath.Text = AppData.Folder; - FillOcrSettings(); - UpdateServiceCards(); - } - finally - { - _fillingSettings = false; - } - } - - private void UpdateServiceCards() - { - Show(TidalCard, MusicService.Tidal, _settings.TidalConfigured); - Show(SpotifyCard, MusicService.Spotify, _settings.SpotifyConfigured); - - void Show(ServiceCard card, MusicService service, bool configured) - { - if (!configured) - card.ShowState(false, false, Loc.T("service.not_connected.pill"), Loc.F("service.not_connected", service)); - else if (_testing.Contains(service)) - card.ShowState(false, true, Loc.T("service.testing.pill"), Loc.T("service.testing")); - else if (_serviceProblem.TryGetValue(service, out var problem)) - card.ShowState(false, true, Loc.T(problem.KeysRejected ? "service.check_keys.pill" : "service.unreachable.pill"), problem.Message); - else if (_verified.Contains(service)) - card.ShowState(true, true, Loc.T("service.connected.pill"), Loc.F("service.connected", service)); - else - card.ShowState(true, true, Loc.T("service.saved.pill"), Loc.F("service.saved", service)); - } - } - - /// - /// Applies what changed between and , saves, - /// and lets the rest of the app catch up. Only real changes are stamped as the newest shared - /// settings, so saving unchanged values never pushes older keys to the other PCs. - /// - private void CommitSettingsEdit(AppSettings edited) - { - if (_settings.ApplyEdits(_settingsShown, edited)) - { - _settings.SharedSettingsUpdatedAt = BacklogStore.Now(); - ScheduleSync(); - } - _settingsShown = edited; - AppData.SaveSettings(_settings); - ApplyPreferredService(); - UpdateSetupInfo(); - UpdateServiceCards(); - _resultsQuery = null; - RefreshQueue(); - } - - private async void OnSaveServiceKeys(object? sender, EventArgs e) - { - if (sender is not ServiceCard card) return; - var service = card == TidalCard ? MusicService.Tidal : MusicService.Spotify; - if (card.ClientId.Length == 0 || card.ClientSecret.Length == 0) - { - card.ShowResult(InfoBarSeverity.Warning, Loc.T("service.need_both")); - return; - } - - var edited = _settingsShown.Clone(); - if (service == MusicService.Tidal) - (edited.TidalClientId, edited.TidalClientSecret) = (card.ClientId, card.ClientSecret); - else - (edited.SpotifyClientId, edited.SpotifyClientSecret) = (card.ClientId, card.ClientSecret); - ForgetTestResult(service); - _testing.Add(service); - CommitSettingsEdit(edited); - await TestServiceAsync(card, service); - } - - private string KeysOf(MusicService service) => service == MusicService.Tidal - ? $"{_settings.TidalClientId}:{_settings.TidalClientSecret}" - : $"{_settings.SpotifyClientId}:{_settings.SpotifyClientSecret}"; - - /// - /// A real search with the saved keys: the quickest proof that they work. The result only counts - /// if the keys are still the ones tested (they may be removed or synced meanwhile). - /// - private async Task TestServiceAsync(ServiceCard card, MusicService service) - { - var tested = KeysOf(service); - _testing.Add(service); - card.IsBusy = true; - card.HideResult(); - UpdateServiceCards(); - (string Message, bool KeysRejected)? problem = null; - int found = 0; - try - { - using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(25)); - var search = service == MusicService.Tidal - ? _tidal.SearchAsync("Charly Garcia Clics Modernos", cts.Token) - : _spotify.SearchAsync("Charly Garcia Clics Modernos", cts.Token); - found = (await search).Count; - } - catch (CatalogException ex) { problem = (ex.Message, ex.KeysRejected); } - catch (OperationCanceledException) { problem = (Loc.F("service.timeout", service), false); } - catch (HttpRequestException ex) { problem = (Loc.F("service.unreachable", service, ex.Message), false); } - catch (Exception ex) { problem = (Loc.F("service.unexpected", service, ex.Message), false); } - finally - { - _testing.Remove(service); - card.IsBusy = false; - } - - if (KeysOf(service) != tested) - { - UpdateServiceCards(); - return; - } - if (problem is { } p) _serviceProblem[service] = p; - else _verified.Add(service); - UpdateServiceCards(); - if (problem is { } shown) - card.ShowResult(InfoBarSeverity.Error, shown.Message); - else - card.ShowResult(InfoBarSeverity.Success, Loc.F("service.test_ok", QueueText.Albums(found))); - } - - private void OnRemoveServiceKeys(object? sender, EventArgs e) - { - if (sender is not ServiceCard card) return; - var service = card == TidalCard ? MusicService.Tidal : MusicService.Spotify; - var (oldId, oldSecret) = service == MusicService.Tidal - ? (_settings.TidalClientId, _settings.TidalClientSecret) - : (_settings.SpotifyClientId, _settings.SpotifyClientSecret); - - SetKeys(service, "", ""); - ShowToast(Loc.F("service.removed", service), undo: () => - { - // Keys saved here or synced from another PC since then are newer: undo must not replace them. - if (KeysOf(service) != ":") - { - ShowToast(Loc.F("service.undo_refused", service), severity: InfoBarSeverity.Warning); - return; - } - SetKeys(service, oldId, oldSecret); - }, severity: InfoBarSeverity.Informational); - - void SetKeys(MusicService s, string id, string secret) - { - var edited = _settingsShown.Clone(); - if (s == MusicService.Tidal) (edited.TidalClientId, edited.TidalClientSecret) = (id, secret); - else (edited.SpotifyClientId, edited.SpotifyClientSecret) = (id, secret); - ForgetTestResult(s); - var target = s == MusicService.Tidal ? TidalCard : SpotifyCard; - target.ClientId = id; - target.ClientSecret = secret; - target.HideResult(); - CommitSettingsEdit(edited); - } - } - - private void OnPreferredChanged(object sender, SelectionChangedEventArgs e) - { - if (_fillingSettings || PreferredBox.SelectedItem is not string service) return; - var edited = _settingsShown.Clone(); - edited.PreferredService = service; - CommitSettingsEdit(edited); - } - - private void OnCountryChanged(object sender, SelectionChangedEventArgs e) - { - if (_fillingSettings || CountryBox.SelectedItem is not CountryOption country) return; - var edited = _settingsShown.Clone(); - edited.CountryCode = country.Code; - CommitSettingsEdit(edited); - } - - private void OnUpdateCheckToggled(object sender, RoutedEventArgs e) - { - if (_fillingSettings) return; - _ui.CheckForUpdates = UpdateCheckToggle.IsOn; - _ui.Save(); - } - - private void OnThemeChanged(object sender, SelectionChangedEventArgs e) - { - if (_fillingSettings || ThemeBox.SelectedItem is not ComboBoxItem { Tag: string theme }) return; - _ui.Theme = theme; - _ui.Save(); - ApplyTheme(); - } - - /// Text recognition: what Windows has installed, which one reads photos, what can be added. - private void FillOcrSettings() - { - bool wasFilling = _fillingSettings; - _fillingSettings = true; - try - { - var installed = OcrService.InstalledTags; - var choices = new List { new("auto", Loc.T("ocr.auto")) }; - choices.AddRange(installed.Select(t => new OcrLanguageOption(t, OcrLanguages.NameOf(t)))); - OcrLanguageBox.ItemsSource = Items(choices); - OcrLanguageBox.SelectedItem = choices.FirstOrDefault(c => c.Tag.Equals(_ui.OcrLanguage, StringComparison.OrdinalIgnoreCase)) - ?? choices[0]; - - var pending = OcrService.PendingRestartTags; - var names = installed.Select(OcrLanguages.NameOf) - .Concat(pending.Select(t => Loc.F("ocr.after_restart", OcrLanguages.NameOf(t)))).ToList(); - OcrInstalledList.Text = names.Count == 0 - ? Loc.T("ocr.none_installed") - : string.Join(", ", names); - - // The button and progress follow the install actually running, wherever it was started. - var installable = OcrLanguages.Installable(installed, pending); - bool installing = OcrService.InstallingTag != null; - OcrInstallBox.ItemsSource = Items(installable); - OcrInstallBox.SelectedIndex = installable.Count > 0 ? 0 : -1; - OcrInstallBox.IsEnabled = OcrInstallButton.IsEnabled = installable.Count > 0 && !installing; - OcrInstallProgress.Visibility = installing ? Visibility.Visible : Visibility.Collapsed; - OcrInstallBox.PlaceholderText = installable.Count > 0 ? "" : Loc.T("ocr.all_installed"); - } - finally - { - _fillingSettings = wasFilling; - } - } - - private void OnOcrLanguageChanged(object sender, SelectionChangedEventArgs e) - { - if (_fillingSettings || OcrLanguageBox.SelectedItem is not OcrLanguageOption choice) return; - _ui.OcrLanguage = choice.Tag; - _ui.Save(); - } - - private async void OnInstallOcrLanguage(object sender, RoutedEventArgs e) - { - if (OcrInstallBox.SelectedItem is not OcrLanguageOption choice) return; - OcrInstallInfo.IsOpen = false; - try - { - // Retry and Windows settings are already on this page; only a restart needs a button here. - await InstallOcrLanguageAsync(choice.Tag, (severity, message, offer) => - { - OcrInstallInfo.Severity = severity; - OcrInstallInfo.Message = message; - OcrInstallInfo.ActionButton = offer.HasFlag(OcrOffer.Restart) ? RestartButton() : null; - OcrInstallInfo.IsOpen = true; - }); - } - finally - { - FillOcrSettings(); - } - } - - private async void OnOpenWindowsLanguages(object sender, RoutedEventArgs e) => - await Launcher.LaunchUriAsync(new Uri("ms-settings:regionlanguage")); - - private void OnLanguageChanged(object sender, SelectionChangedEventArgs e) - { - if (_fillingSettings || LanguageBox.SelectedItem is not ComboBoxItem { Tag: string language }) return; - _ui.Language = language; - _ui.Save(); - UpdateLanguageRestart(); - } - - /// The window's texts are set when it loads, so a new language shows after a restart. - private void UpdateLanguageRestart() - { - bool pending = Loc.Resolve(_ui.Language, Loc.WindowsLanguage) != Loc.Language; - LanguageRestartInfo.ActionButton = pending ? RestartButton() : null; - LanguageRestartInfo.IsOpen = pending; - LanguageRow.RowSpacing = pending ? 12 : 0; - } - - private void ApplyTheme() - { - Root.RequestedTheme = _ui.Theme switch - { - "light" => ElementTheme.Light, - "dark" => ElementTheme.Dark, - _ => ElementTheme.Default, - }; - UpdateCaptionButtons(); - } - - /// The window's own minimize/maximize/close buttons don't follow the app theme by themselves. - private void UpdateCaptionButtons() - { - bool dark = Root.ActualTheme == ElementTheme.Dark; - var bar = AppWindow.TitleBar; - var text = dark ? Color.FromArgb(255, 255, 255, 255) : Color.FromArgb(255, 0, 0, 0); - bar.ButtonBackgroundColor = bar.ButtonInactiveBackgroundColor = Color.FromArgb(0, 0, 0, 0); - bar.ButtonForegroundColor = bar.ButtonHoverForegroundColor = bar.ButtonPressedForegroundColor = text; - bar.ButtonInactiveForegroundColor = Color.FromArgb(255, 128, 128, 128); - bar.ButtonHoverBackgroundColor = dark ? Color.FromArgb(24, 255, 255, 255) : Color.FromArgb(20, 0, 0, 0); - bar.ButtonPressedBackgroundColor = dark ? Color.FromArgb(40, 255, 255, 255) : Color.FromArgb(36, 0, 0, 0); - } - - private void OnResetLayout(object sender, RoutedEventArgs e) - { - _ui.ResetLayout(); - _ui.Save(); - CoverViewToggle.IsChecked = _ui.CoverView; - CheckSortItem(); - if (AppWindow.Presenter is OverlappedPresenter { State: OverlappedPresenterState.Maximized } presenter) presenter.Restore(); - SizeToScreen(1440, 920); - GoTo(Page.Queue); - ShowToast(Loc.T("settings.layout.done"), - severity: InfoBarSeverity.Informational); - } - - private static TextBlock Paragraph(string text) => - new() { Text = text, TextWrapping = TextWrapping.Wrap, Style = (Style)Application.Current.Resources["CaptionTextBlockStyle"] }; } From 7c06ae5fd5ad5c5555ff38bb1334bfd47be5e5ff Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:59:50 -0300 Subject: [PATCH 50/66] docs: name the MainWindow partial classes Co-Authored-By: Claude Sonnet 5.5 --- docs/ARCHITECTURE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 317919d..30e60d7 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -32,7 +32,7 @@ flowchart LR | Project | What | | --- | --- | -| `Queueify\` | The window: navigation, pages (To listen, Listened, Magazine photo, Help, Settings), dialogs, quick tour, theme, assets. `Tr.cs` is the `{l:Tr Key=…}` markup extension. | +| `Queueify\` | The window (`MainWindow`, split by area into `MainWindow.Photo/Sync/Updates/Settings.cs` partial classes): navigation, pages (To listen, Listened, Magazine photo, Help, Settings), dialogs, quick tour, theme, assets. `Tr.cs` is the `{l:Tr Key=…}` markup extension. | | `Queueify.Core\` | Everything that isn't UI. No WinUI references, so it's tested directly. | | `Queueify.Launcher\` | The download's starter: `Bundle` (append, read and unpack the app, with `X86Filter` and the LZMA SDK in `Lzma\`) and `Program` (unpack, start the app with `QUEUEIFY_EXE`, remove older versions), with `LoadingScreen` (plain Win32) covering the wait. No WinUI. | | `Queueify.Tests\` | xUnit v3 tests for Core and the starter's `Bundle` and `X86Filter`, on Microsoft Testing Platform. | From 754891e3debd308047cc6ac5aaff09629ef5f972 Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:00:58 -0300 Subject: [PATCH 51/66] ci: build and test the web projects, cache NuGet, time limits Both workflows run Queueify.Web.Tests, publish Queueify.Web as a smoke step, cap each job and upload test reports when a step fails. The NuGet cache is keyed on the project and props files. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/ci.yml | 36 ++++++++++++++++++++++++++++++++--- .github/workflows/release.yml | 24 ++++++++++++++++++++++- 2 files changed, 56 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e749cb8..e6bb1e3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,5 +1,5 @@ -# Unit tests (with the Firestore emulator), the release-tool tests and the portable build, on every -# push to main and every pull request. The exe is attached to the run as an artifact. +# Unit tests (with the Firestore emulator), the web tests, the release-tool tests and the portable build, on +# every push to main and every pull request. The exe is attached to the run as an artifact. name: CI on: @@ -17,6 +17,7 @@ concurrency: jobs: build: runs-on: windows-latest + timeout-minutes: 45 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -24,6 +25,13 @@ jobs: with: global-json-file: global.json + # Keyed on what decides the package set, so a changed version restores fresh. + - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ~/.nuget/packages + key: nuget-${{ runner.os }}-${{ hashFiles('**/*.csproj', '**/Directory.Packages.props', '**/Directory.Build.props', 'global.json') }} + restore-keys: nuget-${{ runner.os }}- + # Java runs the Firestore emulator, so the sync tests run here too instead of being skipped. - uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1 with: @@ -32,13 +40,26 @@ jobs: - name: Start the Firestore emulator shell: pwsh + timeout-minutes: 5 run: tools/firestore-emulator.ps1 -Background - name: Unit tests shell: pwsh + timeout-minutes: 15 env: QUEUEIFY_FIRESTORE_EMULATOR: 127.0.0.1:8080 - run: dotnet test --project Queueify.Tests + run: dotnet test --project Queueify.Tests --report-xunit-trx --results-directory TestResults/unit + + - name: Web tests + shell: pwsh + timeout-minutes: 15 + run: dotnet test --project Queueify.Web.Tests --report-xunit-trx --results-directory TestResults/web + + # The shipped web app must publish (it is what the Docker image builds); the tests do not catch a broken publish. + - name: Publish the web app + shell: pwsh + timeout-minutes: 10 + run: dotnet publish Queueify.Web -c Release -o "$env:RUNNER_TEMP/web-publish" - name: Release tool tests shell: powershell @@ -46,6 +67,7 @@ jobs: - name: Build the portable app shell: pwsh + timeout-minutes: 20 run: tools/package.ps1 - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 @@ -53,3 +75,11 @@ jobs: name: Queueify-portable path: dist/*.exe if-no-files-found: error + + # What failed, in a form to open: the test reports. + - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + if: failure() + with: + name: test-results + path: TestResults/ + if-no-files-found: ignore diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e2fc2ab..42b9664 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -12,6 +12,7 @@ permissions: jobs: build: runs-on: windows-latest + timeout-minutes: 60 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -19,6 +20,12 @@ jobs: with: global-json-file: global.json + - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ~/.nuget/packages + key: nuget-${{ runner.os }}-${{ hashFiles('**/*.csproj', '**/Directory.Packages.props', '**/Directory.Build.props', 'global.json') }} + restore-keys: nuget-${{ runner.os }}- + - uses: actions/setup-java@de7274f081f381c8f8158605e0321c36c376e2e6 # v6.0.1 with: distribution: temurin @@ -49,7 +56,15 @@ jobs: shell: pwsh env: QUEUEIFY_FIRESTORE_EMULATOR: 127.0.0.1:8080 - run: dotnet test --project Queueify.Tests + run: dotnet test --project Queueify.Tests --report-xunit-trx --results-directory TestResults/unit + + - name: Web tests + shell: pwsh + run: dotnet test --project Queueify.Web.Tests --report-xunit-trx --results-directory TestResults/web + + - name: Publish the web app + shell: pwsh + run: dotnet publish Queueify.Web -c Release -o "$env:RUNNER_TEMP/web-publish" - name: Build the portable app shell: pwsh @@ -63,6 +78,13 @@ jobs: notes/release-notes.md if-no-files-found: error + - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + if: failure() + with: + name: test-results + path: TestResults/ + if-no-files-found: ignore + publish: needs: build runs-on: ubuntu-latest From 0137622621847607c61922708600baedf9ad78d5 Mon Sep 17 00:00:00 2001 From: Patricio <12850986+PAumedes@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:03:44 -0300 Subject: [PATCH 52/66] fix(web): tighten the CSP, allow blob previews, public connect address connect-src is now only the site itself; blob: images are allowed so the photo preview renders (checked in a real browser: the circuit connects and the preview loads). The inline import map, which script-src blocked anyway, is gone. Queueify:PublicBaseUrl feeds the connect text instead of Host. Co-Authored-By: Claude Sonnet 5.5 --- Queueify.Web.Tests/PublicUrlTests.cs | 73 +++++++++++++++++++ Queueify.Web.Tests/Sync/ConnectPcTests.cs | 17 ++++- Queueify.Web.Tests/WebAppTests.cs | 10 +++ Queueify.Web/Components/App.razor | 1 - Queueify.Web/Components/Pages/ConnectPc.razor | 4 +- Queueify.Web/Services/PublicUrl.cs | 17 +++++ Queueify.Web/Services/QueueifyUi.cs | 19 +++-- SECURITY.md | 3 +- 8 files changed, 133 insertions(+), 11 deletions(-) create mode 100644 Queueify.Web.Tests/PublicUrlTests.cs create mode 100644 Queueify.Web/Services/PublicUrl.cs diff --git a/Queueify.Web.Tests/PublicUrlTests.cs b/Queueify.Web.Tests/PublicUrlTests.cs new file mode 100644 index 0000000..61fa1cd --- /dev/null +++ b/Queueify.Web.Tests/PublicUrlTests.cs @@ -0,0 +1,73 @@ +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.Configuration; +using Queueify.Web.Services; + +namespace Queueify.Web.Tests; + +public sealed class PublicUrlTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "qw-url-" + Guid.NewGuid().ToString("N")); + + public void Dispose() + { + Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); + try { Directory.Delete(_root, true); } catch (IOException) { } + } + + private static IConfiguration Config(string? url) => + new ConfigurationBuilder().AddInMemoryCollection(url is null ? [] : new Dictionary { ["Queueify:PublicBaseUrl"] = url }).Build(); + + [Theory] + [InlineData("https://queue.example.org", "https://queue.example.org")] + [InlineData("https://queue.example.org/", "https://queue.example.org")] + [InlineData("https://queue.example.org:8443/some/path?x=1", "https://queue.example.org:8443")] + [InlineData("http://localhost:5147", "http://localhost:5147")] + public void A_configured_public_address_is_reduced_to_its_origin(string configured, string expected) => + Assert.Equal(expected, PublicUrl.Of(Config(configured))); + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("queue.example.org")] + [InlineData("http://queue.example.org")] // a token would travel in the clear + [InlineData("ftp://queue.example.org")] + [InlineData("https://user:pass@queue.example.org")] + public void Anything_else_is_not_a_public_address(string? configured) => Assert.Null(PublicUrl.Of(Config(configured))); + + private async Task CspAsync(string? publicUrl) + { + Directory.CreateDirectory(_root); + await using var factory = new WebApplicationFactory().WithWebHostBuilder(b => + { + b.UseSetting("Queueify:DataDir", Path.Combine(_root, "data")); + if (publicUrl is not null) b.UseSetting("Queueify:PublicBaseUrl", publicUrl); + }); + using var response = await factory.CreateClient().GetAsync("/Account/Login", TestContext.Current.CancellationToken); + return response.Headers.GetValues("Content-Security-Policy").Single(); + } + + private static string Directive(string csp, string name) => + csp.Split(';').Select(d => d.Trim()).Single(d => d.StartsWith(name + " ", StringComparison.Ordinal)); + + [Fact] + public async Task The_circuit_may_only_talk_to_this_site() + { + var csp = await CspAsync(null); + Assert.Equal("connect-src 'self'", Directive(csp, "connect-src")); + } + + [Fact] + public async Task A_configured_public_address_is_added_as_its_websocket_for_older_browsers() + { + var csp = await CspAsync("https://queue.example.org"); + Assert.Equal("connect-src 'self' wss://queue.example.org", Directive(csp, "connect-src")); + } + + [Fact] + public async Task Pictures_made_in_the_browser_can_be_shown_but_scripts_still_only_come_from_the_site() + { + var csp = await CspAsync(null); + Assert.Contains("blob:", Directive(csp, "img-src").Split(' ')); + Assert.Equal("script-src 'self'", Directive(csp, "script-src")); + } +} diff --git a/Queueify.Web.Tests/Sync/ConnectPcTests.cs b/Queueify.Web.Tests/Sync/ConnectPcTests.cs index 9f9605c..cb92238 100644 --- a/Queueify.Web.Tests/Sync/ConnectPcTests.cs +++ b/Queueify.Web.Tests/Sync/ConnectPcTests.cs @@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Components.Authorization; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Queueify.Services; using Queueify.Web.Components.Pages; @@ -25,15 +26,16 @@ public override Task GetAuthenticationStateAsync() => private readonly SqliteConnection _db = new("DataSource=:memory:"); - private IRenderedComponent Open(string userId) + private IRenderedComponent Open(string userId, string? publicUrl = null) { _db.Open(); Services.AddDbContext(o => o.UseSqlite(_db)); Services.AddSingleton(TimeProvider.System); + Services.AddSingleton(new Microsoft.Extensions.Configuration.ConfigurationBuilder().AddInMemoryCollection(publicUrl is null ? [] : new Dictionary { ["Queueify:PublicBaseUrl"] = publicUrl }).Build()); Services.AddScoped(); Services.AddScoped(); Services.AddLogging(); - Services.AddIdentityCore().AddEntityFrameworkStores(); + Services.AddIdentityCore(o => o.Stores.SchemaVersion = Microsoft.AspNetCore.Identity.IdentitySchemaVersions.Version3).AddEntityFrameworkStores(); // same model as the app: the model is cached per process Services.AddSingleton(new SignedIn(userId)); using (var scope = Services.BuildServiceProvider().CreateScope()) { @@ -105,6 +107,17 @@ public void Wrong_passwords_here_count_towards_the_accounts_lockout() Assert.Empty(page.FindAll("#connect-text")); } + [Fact] + public void The_connect_text_uses_the_configured_public_address_not_the_one_the_request_claims() + { + var page = Open("user-5", publicUrl: "https://queue.example.org"); + page.Find("#token-name").Input("PC"); + page.Find("#token-password").Input(Password); + page.Find("form").Submit(); + + Assert.StartsWith("queueify-web|https://queue.example.org|qw_", page.Find("#connect-text").GetAttribute("value")!); + } + [Fact] public void Every_text_on_the_page_exists_in_both_languages() { diff --git a/Queueify.Web.Tests/WebAppTests.cs b/Queueify.Web.Tests/WebAppTests.cs index 3766bf6..e96e258 100644 --- a/Queueify.Web.Tests/WebAppTests.cs +++ b/Queueify.Web.Tests/WebAppTests.cs @@ -233,6 +233,16 @@ public async Task The_language_and_theme_cookies_are_secure_in_production_too() Assert.All(set, c => Assert.Contains("secure", c, StringComparison.OrdinalIgnoreCase)); } + [Fact] + public async Task Pages_carry_no_inline_script_because_the_policy_would_block_it() + { + using var factory = Factory(); + var html = await Client(factory).GetStringAsync("/Account/Login", TestContext.Current.CancellationToken); + + // An inline
- +@Loc.T("web.nav.skip") -
-
- About + + +
+ +
+
@Body
+
- -
- @Body -
-
-