diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..489b83a --- /dev/null +++ b/.dockerignore @@ -0,0 +1,8 @@ +**/bin/ +**/obj/ +.git/ +.claude/ +.cache/ +dist/ +*.db +Queueify.Web/App_Data/ diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e749cb8..620331c 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 "$env:GITHUB_WORKSPACE/TestResults/unit" + + - name: Web tests + shell: pwsh + timeout-minutes: 15 + run: dotnet test --project Queueify.Web.Tests --report-xunit-trx --results-directory "$env:GITHUB_WORKSPACE/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..6e8052b 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 "$env:GITHUB_WORKSPACE/TestResults/unit" + + - name: Web tests + shell: pwsh + run: dotnet test --project Queueify.Web.Tests --report-xunit-trx --results-directory "$env:GITHUB_WORKSPACE/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 diff --git a/.gitignore b/.gitignore index 3707cef..987c35f 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,11 @@ publish/ .vs/ .cache/ dist/ +Queueify.Web/App_Data/ +.scratch/ +TestResults/ + +# Databases hold accounts and queues: never commit them +*.db +*.db-shm +*.db-wal diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..d930f16 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,16 @@ + + + + enable + enable + + + + + $(WarningsAsErrors);NU1901;NU1902;NU1903;NU1904 + + + $(WarningsAsErrors);nullable + + diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 0000000..cd873de --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,35 @@ + + + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..17605e4 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,28 @@ +# Queueify.Web: build from the repository root, `docker build -t queueify-web .` +FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build +WORKDIR /src +# The bracket globs copy the shared build files when the repository has them. +COPY global.json Queueify.slnx Directory.Build.prop[s] Directory.Packages.prop[s] ./ +COPY Queueify.Core/ Queueify.Core/ +COPY Queueify.Web/ Queueify.Web/ +RUN dotnet publish Queueify.Web/Queueify.Web.csproj -c Release -o /out + +FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS run +# tesseract reads the photos; curl is only for the health check. +RUN apt-get update \ + && apt-get install -y --no-install-recommends tesseract-ocr tesseract-ocr-eng tesseract-ocr-spa curl \ + && rm -rf /var/lib/apt/lists/* \ + && mkdir /data && chown 1654:1654 /data +WORKDIR /app +COPY --from=build /out . + +# Everything the server keeps (accounts, queues, keys, models) lives in /data: mount a volume there and back it up whole. +ENV Queueify__DataDir=/data \ + Ocr__TessdataPath=/usr/share/tesseract-ocr/5/tessdata \ + ASPNETCORE_HTTP_PORTS=8080 +VOLUME /data +EXPOSE 8080 +# The image's built-in non-root user (uid 1654). +USER app +HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 CMD curl -fsS http://localhost:8080/healthz || exit 1 +ENTRYPOINT ["dotnet", "Queueify.Web.dll"] 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/Queueify.Core.csproj b/Queueify.Core/Queueify.Core.csproj index a5adc3b..8b6f468 100644 --- a/Queueify.Core/Queueify.Core.csproj +++ b/Queueify.Core/Queueify.Core.csproj @@ -1,20 +1,23 @@ - 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 1.4.0 - + true - true + true embedded + + + + - + 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 af62bfb..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,64 @@ 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(); + } + + /// + /// Brings in albums from a backup in one transaction, keeping each album's own UpdatedAt (so "newest + /// wins" still means the album's last edit, not the day of the import). A new album is added; one already here + /// is overwritten only when the backup's copy is newer. An album deleted here is not brought back. + /// Returns how many were added and how many were already here. + /// + public (int Added, int AlreadyHere) MergeBackup(IEnumerable items) + { + int added = 0, here = 0; + using var db = Open(); + // 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"); + item.Dirty = true; // queued for the server's sync stamp, so connected PCs receive the imported albums + item.Deleted = false; + + using var find = db.CreateCommand(); + find.Transaction = tx; + find.CommandText = "SELECT deleted, updated_at FROM items WHERE uid = $uid"; + find.Parameters.AddWithValue("$uid", item.Uid); + using (var r = find.ExecuteReader()) + { + if (r.Read()) + { + here++; + if (r.GetInt64(0) != 0 || ParseDate(r.GetString(1)).ToUniversalTime() >= AsUtc(item.UpdatedAt)) continue; + using var update = db.CreateCommand(); + update.Transaction = tx; + update.CommandText = """ + UPDATE items SET artist = $artist, album = $album, year = $year, source = $source, cover_url = $cover, + spotify_id = $spotify, tidal_id = $tidal, added_at = $added, listened_at = $listened, rating = $rating, + updated_at = $updated, dirty = $dirty, deleted = 0 + WHERE uid = $uid + """; + Bind(update, item); + update.ExecuteNonQuery(); + continue; + } + } + + using var insert = db.CreateCommand(); + insert.Transaction = tx; + insert.CommandText = $""" + INSERT INTO items ({Columns[4..]}) + VALUES ($uid, $artist, $album, $year, $source, $cover, $spotify, $tidal, $added, $listened, $rating, $updated, $dirty, $deleted) + """; + Bind(insert, item); + insert.ExecuteNonQuery(); + added++; + } + tx.Commit(); + return (added, here); } /// @@ -152,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(); } @@ -243,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); } @@ -254,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/CloudSync.cs b/Queueify.Core/Services/CloudSync.cs index e885147..81aff02 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(); @@ -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/ExternalLinks.cs b/Queueify.Core/Services/ExternalLinks.cs index 4e3510a..276fe65 100644 --- a/Queueify.Core/Services/ExternalLinks.cs +++ b/Queueify.Core/Services/ExternalLinks.cs @@ -3,17 +3,16 @@ 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(new Uri($"spotify:album:{id}"), new Uri($"https://open.spotify.com/album/{id}")); - - public static Task OpenTidalAsync(string id) => - OpenAsync(new Uri($"tidal://album/{id}"), new Uri($"https://tidal.com/album/{id}")); - - private static async Task OpenAsync(Uri app, Uri web) + public static async Task OpenAsync(PlayLink link) { + var app = new Uri(link.App); try { var support = await Launcher.QueryUriSupportAsync(app, LaunchQuerySupportType.Uri); @@ -24,6 +23,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/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/ISyncProvider.cs b/Queueify.Core/Services/ISyncProvider.cs new file mode 100644 index 0000000..189646e --- /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, ISyncProvider cloud, ISyncProvider web) => kind switch + { + SyncKind.Web => web, + SyncKind.Cloud => cloud, + _ => throw new InvalidOperationException("Sync isn't set up."), + }; +} diff --git a/Queueify.Core/Services/Matcher.cs b/Queueify.Core/Services/Matcher.cs index 36bf500..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)); @@ -118,7 +119,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/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/PlayLinks.cs b/Queueify.Core/Services/PlayLinks.cs new file mode 100644 index 0000000..496df9e --- /dev/null +++ b/Queueify.Core/Services/PlayLinks.cs @@ -0,0 +1,38 @@ +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) + if (Only(item, service) is { } link) return link; + return null; + } + + /// The link on exactly this service, or null when the album isn't there or its id is not a plain token. + public static PlayLink? Only(BacklogItem item, MusicService service) + { + var id = service == MusicService.Spotify ? item.SpotifyId : item.TidalId; + return IsPlainId(id) ? For(service, id!) : null; + } + + public 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.Core/Services/ServerSync.cs b/Queueify.Core/Services/ServerSync.cs new file mode 100644 index 0000000..417be65 --- /dev/null +++ b/Queueify.Core/Services/ServerSync.cs @@ -0,0 +1,250 @@ +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; + + /// Re-ask a few seconds before the last answer, in case the server committed two changes at nearly the same moment. + public static readonly TimeSpan Overlap = TimeSpan.FromSeconds(5); + + /// Largest answer read (about 50,000 albums); a bigger one is not a Queueify server. + public const long MaxAnswerBytes = 16L * 1024 * 1024; + + // 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, PooledConnectionLifetime = TimeSpan.FromMinutes(5) }) { Timeout = TimeSpan.FromSeconds(30) }; + http.DefaultRequestHeaders.UserAgent.ParseAdd("Queueify/" + AppInfo.Version); + return http; + } + + 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 now = BacklogStore.Now(); + var dirty = store.LoadDirty(); + // Only the first ask overlaps; later rounds start exactly at the last answer, so they can end. + var since = s.WebLastServerTime is DateTime last && last > DateTime.UnixEpoch + Overlap ? last - Overlap : (DateTime?)null; + 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); + + // A missing or absurd time would be stored as the next position and break every later sync. + if (answer.ServerTime <= DateTime.UnixEpoch || answer.ServerTime > now + FutureTolerance) + throw new SyncException(Loc.T("webSync.err.bad_reply")); + + // 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; + } + + // 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; + remotes.Add(ToItem(wire, now)); + } + int applied = store.ApplyRemoteBatch(remotes); + downloaded += applied; + + if (answer.Settings is { } shared) + { + serverHadSettings = true; + if (Past(shared.UpdatedAt, now) > (s.SharedSettingsUpdatedAt ?? DateTime.MinValue)) + { + TakeSettings(s, shared, now); + settingsChanged = true; + } + } + + // 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 || fullPage; + 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 bytes = await ReadBoundedAsync(res, timeout.Token); + return JsonSerializer.Deserialize(bytes.Span, SyncJson.Default.SyncResponse) is { Albums: not null } answer + && !answer.Albums.Contains(null!) + ? answer + : throw new SyncException(Loc.T("webSync.err.bad_reply")); + } + catch (OperationCanceledException) when (!ct.IsCancellationRequested) + { + throw new SyncException(Loc.T("webSync.err.timeout")); + } + catch (Exception ex) when (ex is HttpRequestException or IOException) + { + // 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 buffer.GetBuffer().AsMemory(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, DateTime now) + { + s.SpotifyClientId = Cut(shared.SpotifyClientId) ?? ""; + s.SpotifyClientSecret = Cut(shared.SpotifyClientSecret) ?? ""; + s.TidalClientId = Cut(shared.TidalClientId) ?? ""; + s.TidalClientSecret = Cut(shared.TidalClientSecret) ?? ""; + if (!string.IsNullOrWhiteSpace(shared.PreferredService)) s.PreferredService = Cut(shared.PreferredService)!; + if (!string.IsNullOrWhiteSpace(shared.CountryCode)) s.CountryCode = Cut(shared.CountryCode)!; + s.SharedSettingsUpdatedAt = s.WebSettingsSyncedAt = Past(shared.UpdatedAt, now); + } + + 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, DateTime now) => new() + { + Uid = a.Uid, + Artist = Cut(a.Artist) ?? "", + Album = Cut(a.Album) ?? "", + Year = AlbumYear.OrNull(a.Year), + Source = Cut(a.Source), + CoverUrl = Cut(a.CoverUrl), + 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), + UpdatedAt = Past(a.UpdatedAt, now), + Deleted = a.Deleted, + }; + + /// + /// A change time more than a few minutes ahead is taken as now: a server (or a wrong clock) must not + /// be able to make a row win every later comparison. + /// + 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 == 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) => + t.Kind == DateTimeKind.Unspecified ? DateTime.SpecifyKind(t, DateTimeKind.Utc) : t.ToUniversalTime(); +} 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 62e0819..7c3d8bc 100644 --- a/Queueify.Core/Services/Strings.En.cs +++ b/Queueify.Core/Services/Strings.En.cs @@ -1,4 +1,4 @@ -namespace Queueify.Services; +namespace Queueify.Services; public static partial class Loc { @@ -173,7 +173,7 @@ public static partial class Loc ["sync.err.timeout"] = "Firebase didn't answer in time. Your changes will sync later.", ["sync.err.disk"] = "Couldn't save on this PC ({0}). Your changes will sync later.", ["sync.err.other"] = "Sync failed ({0}). Your changes are kept and will sync later.", - ["sync.setup.intro"] = "Keep one queue on all your PCs. It's stored in your own Google Firebase account, on the free plan (no credit card).", + ["sync.setup.intro"] = "Keep one queue on all your PCs: in your own Google Firebase account (free plan, no credit card) or on a Queueify web server you run.", ["sync.setup.create"] = "This is my first PC: create the online queue", ["sync.setup.join"] = "I already set it up on another PC", ["sync.setup.steps"] = "1. Open the Firebase console and sign in with your Google account.\n2. Create a project with any name (e.g. Queueify). Google Analytics isn't needed.\n3. In the menu, open Build → Firestore Database → Create database. If asked, choose the Standard edition, keep the database ID \"(default)\", pick a location near you (e.g. southamerica-east1) and start in production mode.\n4. Open the Rules tab, replace everything with Queueify's rules (button below) and click Publish.\n5. Copy the project ID (it's in the address bar after /project/, or in Project settings) and paste it here.", @@ -353,5 +353,382 @@ 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.", + + // ── Web app: shell, queue and add pages ── + ["web.nav.skip"] = "Skip to content", + ["web.nav.main"] = "Main navigation", + ["web.nav.more"] = "More", + ["web.nav.add"] = "Add", + ["web.nav.add.tip"] = "Add an album to your queue (Ctrl+K)", + ["web.nav.connect"] = "Connect a PC", + ["web.nav.connect.tip"] = "Connect a PC: sync the desktop app with this queue", + ["web.nav.signout"] = "Sign out", + ["web.pref.title"] = "Language and theme", + ["web.pref.language"] = "Language", + ["web.pref.theme"] = "Theme", + ["web.pref.system"] = "Auto", + ["web.error.unhandled"] = "Something went wrong.", + ["web.error.reload"] = "Reload", + ["web.toast.dismiss"] = "Dismiss", + ["web.reconnect.first"] = "Reconnecting to the server…", + ["web.reconnect.repeat"] = "Still trying. Next attempt in (seconds):", + ["web.reconnect.failed"] = "Couldn't reconnect. Retry, or reload the page.", + ["web.reconnect.retry"] = "Retry", + ["web.reconnect.paused"] = "The session was paused by the server.", + ["web.reconnect.resume"] = "Resume", + ["web.queue.stars"] = "{0} stars", + ["web.add.summary"] = "Someone recommended an album? Type it as you heard it.", + ["web.add.keys_link"] = "Open Settings", + ["web.add.quick"] = "Add by hand", + ["web.add.artist"] = "Artist", + ["web.add.album"] = "Album", + ["web.add.year"] = "Year", + + // ── Web app: accounts ── + ["web.auth.nav.profile"] = "Profile", + ["web.auth.nav.email"] = "Email", + ["web.auth.nav.password"] = "Password", + ["web.auth.nav.external"] = "External logins", + ["web.auth.nav.2fa"] = "Two-factor authentication", + ["web.auth.nav.passkeys"] = "Passkeys", + ["web.auth.nav.data"] = "Personal data", + ["web.auth.manage.title"] = "Your account", + ["web.auth.manage.sub"] = "Sign-in options for this queue.", + ["web.auth.register"] = "Create your account", + ["web.auth.register.sub"] = "Your queue is private to your account.", + ["web.auth.first_user"] = "You are the first one here, so this account owns the server. Choose a good password or add a passkey afterwards.", + ["web.auth.closed"] = "Registration is closed on this server. Ask its owner for an account.", + ["web.auth.login"] = "Sign in", + ["web.auth.login.sub"] = "Your albums wait for you.", + ["web.auth.email"] = "Email", + ["web.auth.password"] = "Password", + ["web.auth.confirm"] = "Confirm password", + ["web.auth.or"] = "or", + ["web.auth.have_account"] = "I already have an account", + ["web.auth.remember"] = "Keep me signed in", + ["web.auth.passkey"] = "Sign in with a passkey", + ["web.auth.register_link"] = "Create an account", + ["web.auth.invalid"] = "That email and password don't match.", + ["web.auth.external_using"] = "Sign in with your {0} account", + + ["web.queue.star.one"] = "1 star", + ["web.add.throttled"] = "Too many searches in a minute. Wait a moment and try again.", + ["web.add.not_on"] = "not found there", + + ["web.error.save"] = "Couldn't save that. Try again in a moment.", + + // -- Web app: account pages -- + ["web.acct.denied.title"] = "Access denied", + ["web.acct.denied.text"] = "You do not have access to this resource.", + ["web.acct.confirm.title"] = "Confirm email", + ["web.acct.confirm.change.title"] = "Confirm email change", + ["web.acct.forgot.title"] = "Forgot your password?", + ["web.acct.forgot.enter"] = "Enter your email.", + ["web.acct.forgot.reset"] = "Reset password", + ["web.acct.forgot.conf.title"] = "Forgot password confirmation", + ["web.acct.forgot.conf.text"] = "Please check your email to reset your password.", + ["web.acct.invalid.reset.title"] = "Invalid password reset", + ["web.acct.invalid.reset.text"] = "The password reset link is invalid.", + ["web.acct.invalid.user"] = "Invalid user", + ["web.acct.lockout.title"] = "Locked out", + ["web.acct.lockout.text"] = "This account has been locked out, please try again later.", + ["web.acct.twofa.title"] = "Two-factor authentication", + ["web.acct.twofa.intro"] = "Your login is protected with an authenticator app. Enter your authenticator code below.", + ["web.acct.twofa.code"] = "Authenticator code", + ["web.acct.twofa.remember"] = "Remember this machine", + ["web.acct.twofa.nodevice"] = "Don't have access to your authenticator device? You can", + ["web.acct.twofa.use_recovery"] = "log in with a recovery code", + ["web.acct.recovery.title"] = "Recovery code verification", + ["web.acct.recovery.intro"] = "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.", + ["web.acct.recovery.code"] = "Recovery Code", + ["web.acct.regconf.title"] = "Register confirmation", + ["web.acct.regconf.nosender"] = "This app does not currently have a real email sender registered, see", + ["web.acct.regconf.docs"] = "these docs", + ["web.acct.regconf.configure"] = "for how to configure a real email sender.", + ["web.acct.regconf.normally"] = "Normally this would be emailed:", + ["web.acct.regconf.click"] = "Click here to confirm your account", + ["web.acct.regconf.check"] = "Please check your email to confirm your account.", + ["web.acct.resend.title"] = "Resend email confirmation", + ["web.acct.resend.btn"] = "Resend", + ["web.acct.reset.your"] = "Reset your password.", + ["web.acct.reset.btn"] = "Reset", + ["web.acct.reset.conf.title"] = "Reset password confirmation", + ["web.acct.reset.conf.text1"] = "Your password has been reset. Please", + ["web.acct.reset.conf.link"] = "click here to log in", + ["web.acct.newpass"] = "New password", + ["web.acct.oldpass"] = "Old password", + ["web.acct.confirmpass"] = "Confirm password", + ["web.acct.enterpass"] = "Please enter your password.", + ["web.acct.confirmpass.ph"] = "Please confirm your password.", + ["web.acct.oldpass.ph"] = "Enter the old password", + ["web.acct.newpass.ph"] = "Enter the new password", + ["web.acct.password"] = "Password", + ["web.acct.email"] = "Email", + ["web.acct.chpass.title"] = "Change password", + ["web.acct.chpass.btn"] = "Update password", + ["web.acct.delete.title"] = "Delete Personal Data", + ["web.acct.delete.warn"] = "Deleting this data will permanently remove your account, and this cannot be recovered.", + ["web.acct.delete.btn"] = "Delete data and close my account", + ["web.acct.disable.title"] = "Disable two-factor authentication (2FA)", + ["web.acct.disable.only"] = "This action only disables 2FA.", + ["web.acct.disable.keys"] = "Disabling 2FA does not change the keys used in authenticator apps. If you wish to change the key used in an authenticator app you should", + ["web.acct.disable.reset"] = "reset your authenticator keys.", + ["web.acct.disable.btn"] = "Disable 2FA", + ["web.acct.email.manage"] = "Manage email", + ["web.acct.email.enter"] = "Enter your email", + ["web.acct.email.send_ver"] = "Send verification email", + ["web.acct.email.new"] = "New email", + ["web.acct.email.new.ph"] = "Enter a new email", + ["web.acct.email.change"] = "Change email", + ["web.acct.auth.config"] = "Configure authenticator app", + ["web.acct.auth.steps"] = "To use an authenticator app go through the following steps:", + ["web.acct.auth.step1"] = "Download a two-factor authenticator app like Microsoft Authenticator for", + ["web.acct.auth.step1b"] = "or Google Authenticator for", + ["web.acct.auth.step2a"] = "Scan the QR Code or enter this key", + ["web.acct.auth.step2b"] = "into your two factor authenticator app. Spaces and casing do not matter.", + ["web.acct.auth.qr"] = "Learn how to", + ["web.acct.auth.qr_link"] = "enable QR code generation", + ["web.acct.auth.step3"] = "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.", + ["web.acct.auth.code.ph"] = "Enter the code", + ["web.acct.auth.code"] = "Verification Code", + ["web.acct.auth.verify"] = "Verify", + ["web.acct.ext.registered"] = "Registered Logins", + ["web.acct.ext.remove"] = "Remove", + ["web.acct.ext.add"] = "Add another service to log in.", + ["web.acct.recov.codes"] = "Recovery codes", + ["web.acct.recov.safe"] = "Put these codes in a safe place.", + ["web.acct.recov.lose"] = "If you lose your device and don't have the recovery codes you will lose access to your account.", + ["web.acct.recov.gen.title"] = "Generate two-factor authentication (2FA) recovery codes", + ["web.acct.recov.gen.keys"] = "Generating new recovery codes does not change the keys used in authenticator apps. If you wish to change the key used in an authenticator app you should", + ["web.acct.recov.gen.btn"] = "Generate Recovery Codes", + ["web.acct.profile.title"] = "Profile", + ["web.acct.profile.username"] = "Username", + ["web.acct.profile.phone"] = "Phone number", + ["web.acct.profile.phone.ph"] = "Enter your phone number", + ["web.acct.profile.save"] = "Save", + ["web.acct.pk.title"] = "Manage your passkeys", + ["web.acct.pk.rename"] = "Rename", + ["web.acct.pk.delete"] = "Delete", + ["web.acct.pk.none"] = "No passkeys are registered.", + ["web.acct.pk.max"] = "You have reached the maximum number of allowed passkeys. Please delete one before adding a new one.", + ["web.acct.pk.add"] = "Add a new passkey", + ["web.acct.pk.rename.title"] = "Enter a name for your passkey", + ["web.acct.pk.rename.name"] = "Passkey name", + ["web.acct.pk.continue"] = "Continue", + ["web.acct.pd.title"] = "Personal Data", + ["web.acct.pd.text"] = "Your account contains personal data that you have given us. This page allows you to download or delete that data.", + ["web.acct.pd.download"] = "Download", + ["web.acct.resetauth.title"] = "Reset authenticator key", + ["web.acct.resetauth.warn"] = "If you reset your authenticator key your authenticator app will not work until you reconfigure it.", + ["web.acct.resetauth.text"] = "This process disables 2FA until you verify your authenticator app. If you do not complete your authenticator app configuration you may lose access to your account.", + ["web.acct.setpass.title"] = "Set your password", + ["web.acct.setpass.text"] = "You do not have a local username/password for this site. Add a local account so you can log in without an external login.", + ["web.acct.setpass.btn"] = "Set password", + ["web.acct.tf.title"] = "Two-factor authentication (2FA)", + ["web.acct.tf.none_left"] = "You have no recovery codes left.", + ["web.acct.tf.none_left2"] = "You must", + ["web.acct.tf.gen_new"] = "generate a new set of recovery codes", + ["web.acct.tf.none_left3"] = "before you can log in with a recovery code.", + ["web.acct.tf.one_left"] = "You have 1 recovery code left.", + ["web.acct.tf.can"] = "You can", + ["web.acct.tf.few"] = "You should", + ["web.acct.tf.forget"] = "Forget this browser", + ["web.acct.tf.reset_codes"] = "Reset recovery codes", + ["web.acct.tf.app"] = "Authenticator app", + ["web.acct.tf.add_app"] = "Add authenticator app", + ["web.acct.tf.setup_app"] = "Set up authenticator app", + ["web.acct.tf.reset_app"] = "Reset authenticator app", + ["web.acct.tf.privacy"] = "Privacy and cookie policy have not been accepted.", + ["web.acct.tf.privacy2"] = "You must accept the policy before you can enable two factor authentication.", + ["web.acct.m.confirm.ok"] = "Thank you for confirming your email.", + ["web.acct.m.confirm.err"] = "Error confirming your email.", + ["web.acct.m.change.ok"] = "Thank you for confirming your email change.", + ["web.acct.m.change.err"] = "Error changing email.", + ["web.acct.m.invalid2fa"] = "Invalid authenticator code.", + ["web.acct.m.invalid_recovery"] = "Invalid recovery code entered.", + ["web.acct.m.pw_changed"] = "Your password has been changed", + ["web.acct.m.bad_pw"] = "Incorrect password.", + ["web.acct.m.email_same"] = "Your email is unchanged.", + ["web.acct.m.email_link"] = "Confirmation link to change email sent. Please check your email.", + ["web.acct.m.ver_sent"] = "Verification email sent. Please check your email.", + ["web.acct.m.code_invalid"] = "Verification code is invalid.", + ["web.acct.m.auth_ok"] = "Your authenticator app has been verified.", + ["web.acct.m.ext_not_removed"] = "The external login was not removed.", + ["web.acct.m.ext_removed"] = "The external login was removed.", + ["web.acct.m.ext_added"] = "The external login was added.", + ["web.acct.m.codes_new"] = "You have generated new recovery codes.", + ["web.acct.m.phone_fail"] = "Failed to set phone number.", + ["web.acct.m.profile_ok"] = "Your profile has been updated", + ["web.acct.m.pk_none"] = "The browser did not provide a passkey.", + ["web.acct.m.pk_max"] = "You have reached the maximum number of allowed passkeys.", + ["web.acct.m.pk_add_fail"] = "The passkey could not be added to your account.", + ["web.acct.m.pk_del_fail"] = "The passkey could not be deleted.", + ["web.acct.m.pk_deleted"] = "Passkey deleted successfully.", + ["web.acct.m.pk_bad_id"] = "The specified passkey ID had an invalid format.", + ["web.acct.m.pk_notfound"] = "The specified passkey could not be found.", + ["web.acct.m.pk_upd_fail"] = "The passkey could not be updated.", + ["web.acct.m.pk_updated"] = "Passkey updated successfully.", + ["web.acct.m.setpw_ok"] = "Your password has been set.", + + ["web.val.required"] = "This field is required.", + ["web.val.email"] = "Enter a valid email address.", + ["web.val.length"] = "Use between {0} and {1} characters.", + ["web.val.match"] = "The two passwords don't match.", + ["web.idn.default"] = "Something went wrong. Try again.", + ["web.idn.short"] = "The password needs at least {0} characters.", + ["web.idn.symbol"] = "The password needs at least one symbol (like ! or #).", + ["web.idn.digit"] = "The password needs at least one digit.", + ["web.idn.lower"] = "The password needs at least one lowercase letter.", + ["web.idn.upper"] = "The password needs at least one uppercase letter.", + ["web.idn.unique"] = "The password needs at least {0} different characters.", + ["web.idn.mismatch"] = "That password is wrong.", + ["web.idn.taken"] = "{0} is already registered.", + ["web.idn.email"] = "Enter a valid email address.", + ["web.idn.linked"] = "That login is already linked to an account.", + ["web.acct.pk.rename_named"] = "Enter a new name for your \"{0}\" passkey", + ["web.acct.tf.left_n"] = "You have {0} recovery codes left.", + ["web.acct.ext.remove_tip"] = "Remove this {0} login from your account", + ["web.acct.ext.login_tip"] = "Log in using your {0} account", + + ["web.acct.assoc"] = "Link your {0} account.", + + ["web.acct.m.ext_load"] = "Couldn't load the external login information.", + ["web.acct.pk.unnamed"] = "Unnamed passkey", + // ── Web app: Settings, Help, Photo, data ── + ["webSettings.title"] = "Settings", + ["webSettings.summary"] = "Music services, country, theme, language, text recognition and your data. The music section has a Save button; the rest saves as soon as you change it.", + ["webSettings.keys.note"] = "Keys are write-only: once saved they are never shown again. Leave a field empty to keep the saved one.", + ["webSettings.steps"] = "How to get the keys", + ["webSettings.keys.on"] = "Configured", + ["webSettings.keys.off"] = "Not configured", + ["webSettings.client_id"] = "Client ID", + ["webSettings.client_secret"] = "Client secret", + ["webSettings.secret.saved"] = "Saved. Type to replace it", + ["webSettings.secret.empty"] = "Paste it here", + ["webSettings.remove"] = "Remove {0} keys", + ["webSettings.save"] = "Save", + ["webSettings.saved"] = "Saved.", + ["webSettings.unchanged"] = "Nothing changed.", + ["webSettings.test"] = "Test saved {0} keys", + ["webSettings.removed"] = "{0} keys removed.", + ["webSettings.testing"] = "Testing…", + ["webSettings.test.ok"] = "{0} answered: the keys work.", + ["webSettings.test.missing"] = "Save the {0} Client ID and secret first.", + ["webSettings.test.unexpected"] = "Couldn't test {0} right now. Try again in a moment.", + ["webSettings.theme.text"] = "Light or dark; by default the same as your device", + ["webSettings.theme.system"] = "Use my device setting", + ["webSettings.language.text"] = "English or Spanish; by default the same as your browser", + ["webSettings.language.system"] = "Use my browser language", + ["webSettings.ocr.text"] = "The language used to read the text on a magazine photo", + ["webSettings.ocr.auto"] = "Automatic (Spanish and English)", + ["webSettings.ocr.es"] = "Spanish", + ["webSettings.ocr.en"] = "English", + ["webSettings.connect.title"] = "Windows app", + ["webSettings.connect.text"] = "Link the Queueify app on a PC to this queue with a personal token.", + ["webSettings.connect.open"] = "Connect a PC", + ["webSettings.signout.title"] = "Sessions on other devices", + ["webSettings.signout.text"] = "Signing out here doesn't end your sessions on other devices. Changing your password in Account signs every other device out.", + ["webSettings.signout.open"] = "Open account", + ["webSettings.delete.title"] = "Delete my data", + ["webSettings.delete.text"] = "Removes your whole queue, saved keys and preferences from this server. Your sign-in stays; delete it under Account. This can't be undone, so download a backup first.", + ["webSettings.delete.sure"] = "I understand this can't be undone", + ["webSettings.delete.button"] = "Delete my data", + ["webSettings.delete.done"] = "Your data was deleted.", + ["webSettings.failed"] = "Couldn't save that ({0}). Try again.", + ["webData.title"] = "Your data", + ["webData.text"] = "Download your queue, or bring in the queue from the Windows app. Albums keep their identity, so importing twice never duplicates them.", + ["webData.export.json"] = "Download JSON", + ["webData.export.csv"] = "Download CSV", + ["webData.import.title"] = "Import", + ["webData.import.text"] = "Choose the queueify.db of the Windows app (in %LOCALAPPDATA%\\Queueify) or a JSON file downloaded here.", + ["webData.import.choose"] = "Choose a file", + ["webData.import.button"] = "Import", + ["webData.import.working"] = "Importing…", + ["webData.import.done"] = "Imported: {0} new, {1} already here, {2} skipped.", + ["webData.import.too_big"] = "That file is too big ({0} MB at most).", + ["webData.import.invalid"] = "That isn't a Queueify queue: choose queueify.db from the Windows app or a JSON file downloaded here.", + ["webData.import.failed"] = "Couldn't import that file. Try again, or download a fresh copy of it.", + ["webHelp.title"] = "Help", + ["webHelp.summary"] = "How everything works, and the keyboard shortcuts", + ["webHelp.guide.5"] = "5. Lazy mode: photograph a page in Magazine photo, then tap the artist and the album on it instead of typing.", + ["webHelp.touch"] = "On a phone: tap an album to see its options; add Queueify to your home screen from the browser menu.", + ["webHelp.sync"] = "To keep the Windows app and this queue together, open Settings → Connect a PC and paste the text it gives you into the app's Sync dialog.", + ["webHelp.trouble.1"] = "• “Spotify rejected the Client ID”: open Settings and paste the keys again from developer.spotify.com/dashboard, then press Test keys. The account that owns the app needs Premium.", + ["webHelp.trouble.2"] = "• An album isn't found: use fewer words (artist + main title), check the spelling, or add it without a link.", + ["webHelp.trouble.3"] = "• Text on a photo is read wrong: use good light and shoot the page straight on. Photos are read in Spanish and English; change it in Settings.", + ["webHelp.tour.title"] = "Quick tour", + ["webHelp.tour.1.title"] = "Add an album", + ["webHelp.tour.1"] = "Type what the magazine says, like “Charly García Clics Modernos”. Press Enter to search Spotify and Tidal, and Enter again to add the best match.", + ["webHelp.tour.2.title"] = "Your queue", + ["webHelp.tour.2"] = "Everything you add waits here. Press Play to open it in Tidal or Spotify. Tick the circle when you've heard it; it moves to Listened, where you can rate it.", + ["webHelp.tour.3.title"] = "Too lazy to type?", + ["webHelp.tour.3"] = "Take a photo of a magazine page, then tap the artist and the album on it.", + ["webHelp.tour.4.title"] = "Settings", + ["webHelp.tour.4"] = "Paste your Spotify or Tidal keys here once. You can also connect the Windows app and download your queue.", + ["webPhoto.title"] = "Magazine photo", + ["webPhoto.summary"] = "Take or choose a photo of a page, then tap the artist and the album on it.", + ["webPhoto.choose"] = "Choose a photo", + ["webPhoto.take"] = "Take a photo", + ["webPhoto.drop"] = "Drop a photo here, paste one with Ctrl+V, or use the buttons.", + ["webPhoto.language"] = "Read the photo in", + ["webPhoto.reading"] = "Reading the page…", + ["webPhoto.privacy"] = "The photo is read and then discarded; the server keeps nothing.", + ["webPhoto.tap"] = "Tap the artist and the album, in that order, then search.", + ["webPhoto.search"] = "Search for “{0}”", + ["webPhoto.clear"] = "Clear selection", + ["webPhoto.no_text"] = "No text found. Try a sharper, well-lit photo taken straight on.", + ["webPhoto.preview"] = "Your photo, with the text lines that were found", + ["webPhoto.err.tooLarge"] = "That photo is too big (up to {0} MB). Try a smaller one.", + ["webPhoto.err.tooManyPixels"] = "That photo has too many pixels. Try a smaller one.", + ["webPhoto.err.notAnImage"] = "That file isn't a JPG, PNG or WebP photo. iPhone HEIC photos: share them as JPG, or set the camera to Most Compatible.", + ["webPhoto.err.corrupt"] = "That photo looks damaged and couldn't be opened. Try taking it again.", + ["webPhoto.err.busy"] = "A photo is already being read. Wait a moment and try again.", + ["webPhoto.err.timeout"] = "Reading the photo took too long. Try a smaller or clearer one.", + ["webPhoto.err.engineMissing"] = "Reading photos isn't available right now. Ask whoever runs this server to check the text reader.", + ["webPhoto.err.unauthorized"] = "Your session ended. Sign in again.", + ["webPhoto.err.network"] = "Couldn't send the photo. Check the connection and try again.", + ["webPhoto.err.language"] = "That language isn't offered.", + ["webPhoto.err.unknown"] = "Something went wrong reading the photo. Try again in a moment.", + ["webPhoto.found"] = "{0} lines found. Tap the artist and the album, in that order, then search.", + ["webHelp.col.keys"] = "Keys", + ["webHelp.col.does"] = "What it does", + // ── 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.", + + ["web.keys.ctrl_k"] = "Go to Add and its search box", + ["webSync.setup.option"] = "Connect to a Queueify web server", + ["webSync.setup.text"] = "In the menu of your Queueify web app (not this 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 has three parts separated by |: \"queueify-web\", an https address and the token.", + ["webSync.keys_notice"] = "Your Spotify and Tidal keys are shared with this server: if it has none yet, this PC's keys are sent to it; otherwise this PC takes the server's. Only connect to a server you run or trust.", + ["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. The token keeps working until you revoke it in the web app.", + ["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 (if this PC is connected, open Sync and choose Disconnect this PC first).", + ["webSync.err.unauthorized"] = "The web server didn't accept this PC's token. It may have been revoked: make a new token in the web app and connect again with the new connect text (if this PC is connected, open Sync and choose Disconnect this PC first).", + ["webSync.err.redirect"] = "The web server sent this PC somewhere else, so nothing was sent. Connect again with the right address (if this PC is connected, open Sync and choose Disconnect this PC first).", + ["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 the server answers.", + ["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..a6977d0 100644 --- a/Queueify.Core/Services/Strings.Es.cs +++ b/Queueify.Core/Services/Strings.Es.cs @@ -1,4 +1,4 @@ -namespace Queueify.Services; +namespace Queueify.Services; // Español rioplatense (vos), para quien lee las revistas. public static partial class Loc @@ -174,7 +174,7 @@ public static partial class Loc ["sync.err.timeout"] = "Firebase no respondió a tiempo. Tus cambios se sincronizan más tarde.", ["sync.err.disk"] = "No se pudo guardar en esta PC ({0}). Tus cambios se sincronizan más tarde.", ["sync.err.other"] = "Falló la sincronización ({0}). Tus cambios quedan guardados y se sincronizan más tarde.", - ["sync.setup.intro"] = "Tené una sola lista en todas tus PC. Se guarda en tu propia cuenta de Google Firebase, en el plan gratuito (sin tarjeta de crédito).", + ["sync.setup.intro"] = "Tené una sola lista en todas tus PC. Se guarda en tu propia cuenta de Google Firebase (plan gratuito, sin tarjeta de crédito) o en un servidor web de Queueify que manejes vos.", ["sync.setup.create"] = "Es mi primera PC: crear la lista en línea", ["sync.setup.join"] = "Ya lo configuré en otra PC", ["sync.setup.steps"] = "1. Abrí la consola de Firebase e iniciá sesión con tu cuenta de Google.\n2. Creá un proyecto con cualquier nombre (p. ej. Queueify). No hace falta Google Analytics.\n3. En el menú, abrí Compilación (Build) → Firestore Database → Crear base de datos. Si te pregunta, elegí la edición Standard, dejá el ID de base de datos \"(default)\", elegí una ubicación cercana (p. ej. southamerica-east1) y empezá en modo de producción.\n4. Abrí la pestaña Reglas (Rules), reemplazá todo por las reglas de Queueify (botón de abajo) y hacé clic en Publicar (Publish).\n5. Copiá el ID del proyecto (está en la barra de direcciones después de /project/, o en Configuración del proyecto) y pegalo acá.", @@ -354,5 +354,382 @@ 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.", + + // ── Web: estructura, lista y agregar ── + ["web.nav.skip"] = "Saltar al contenido", + ["web.nav.main"] = "Navegación principal", + ["web.nav.more"] = "Más", + ["web.nav.add"] = "Agregar", + ["web.nav.add.tip"] = "Agregar un álbum a tu lista (Ctrl+K)", + ["web.nav.connect"] = "Conectar una PC", + ["web.nav.connect.tip"] = "Conectar una PC: sincronizar la app de escritorio con esta lista", + ["web.nav.signout"] = "Salir", + ["web.pref.title"] = "Idioma y tema", + ["web.pref.language"] = "Idioma", + ["web.pref.theme"] = "Tema", + ["web.pref.system"] = "Automático", + ["web.error.unhandled"] = "Algo salió mal.", + ["web.error.reload"] = "Recargar", + ["web.toast.dismiss"] = "Cerrar", + ["web.reconnect.first"] = "Reconectando con el servidor…", + ["web.reconnect.repeat"] = "Seguimos intentando. Próximo intento en segundos:", + ["web.reconnect.failed"] = "No se pudo reconectar. Probá de nuevo o recargá la página.", + ["web.reconnect.retry"] = "Reintentar", + ["web.reconnect.paused"] = "El servidor pausó la sesión.", + ["web.reconnect.resume"] = "Reanudar", + ["web.queue.stars"] = "{0} estrellas", + ["web.add.summary"] = "¿Te recomendaron un álbum? Escribilo como lo oíste.", + ["web.add.keys_link"] = "Abrir Configuración", + ["web.add.quick"] = "Agregar a mano", + ["web.add.artist"] = "Artista", + ["web.add.album"] = "Álbum", + ["web.add.year"] = "Año", + + // ── Web: cuentas ── + ["web.auth.nav.profile"] = "Perfil", + ["web.auth.nav.email"] = "Correo", + ["web.auth.nav.password"] = "Contraseña", + ["web.auth.nav.external"] = "Cuentas externas", + ["web.auth.nav.2fa"] = "Verificación en dos pasos", + ["web.auth.nav.passkeys"] = "Claves de acceso", + ["web.auth.nav.data"] = "Datos personales", + ["web.auth.manage.title"] = "Tu cuenta", + ["web.auth.manage.sub"] = "Formas de entrar a esta lista.", + ["web.auth.register"] = "Creá tu cuenta", + ["web.auth.register.sub"] = "Tu lista es privada, solo de tu cuenta.", + ["web.auth.first_user"] = "Sos la primera persona acá, así que esta cuenta es la dueña del servidor. Elegí una buena contraseña o agregá una clave de acceso después.", + ["web.auth.closed"] = "El registro está cerrado en este servidor. Pedile una cuenta a quien lo administra.", + ["web.auth.login"] = "Entrar", + ["web.auth.login.sub"] = "Tus álbumes te están esperando.", + ["web.auth.email"] = "Correo", + ["web.auth.password"] = "Contraseña", + ["web.auth.confirm"] = "Repetí la contraseña", + ["web.auth.or"] = "o", + ["web.auth.have_account"] = "Ya tengo una cuenta", + ["web.auth.remember"] = "Mantenerme conectado", + ["web.auth.passkey"] = "Entrar con una clave de acceso", + ["web.auth.register_link"] = "Crear una cuenta", + ["web.auth.invalid"] = "Ese correo y esa contraseña no coinciden.", + ["web.auth.external_using"] = "Entrar con tu cuenta de {0}", + + ["web.queue.star.one"] = "1 estrella", + ["web.add.throttled"] = "Demasiadas búsquedas en un minuto. Esperá un momento y probá de nuevo.", + ["web.add.not_on"] = "no está ahí", + + ["web.error.save"] = "No se pudo guardar. Probá de nuevo en un momento.", + + // -- Web: paginas de la cuenta -- + ["web.acct.denied.title"] = "Acceso denegado", + ["web.acct.denied.text"] = "No tenés acceso a este recurso.", + ["web.acct.confirm.title"] = "Confirmar el correo", + ["web.acct.confirm.change.title"] = "Confirmar el cambio de correo", + ["web.acct.forgot.title"] = "¿Olvidaste tu contraseña?", + ["web.acct.forgot.enter"] = "Ingresá tu correo.", + ["web.acct.forgot.reset"] = "Restablecer la contraseña", + ["web.acct.forgot.conf.title"] = "Confirmación de contraseña olvidada", + ["web.acct.forgot.conf.text"] = "Revisá tu correo para restablecer la contraseña.", + ["web.acct.invalid.reset.title"] = "Restablecimiento no válido", + ["web.acct.invalid.reset.text"] = "El enlace para restablecer la contraseña no es válido.", + ["web.acct.invalid.user"] = "Usuario no válido", + ["web.acct.lockout.title"] = "Cuenta bloqueada", + ["web.acct.lockout.text"] = "Esta cuenta está bloqueada por un rato; probá de nuevo más tarde.", + ["web.acct.twofa.title"] = "Verificación en dos pasos", + ["web.acct.twofa.intro"] = "Tu cuenta está protegida con una app autenticadora. Ingresá abajo el código que te da.", + ["web.acct.twofa.code"] = "Código del autenticador", + ["web.acct.twofa.remember"] = "Recordar este equipo", + ["web.acct.twofa.nodevice"] = "¿No tenés a mano tu dispositivo autenticador? Podés", + ["web.acct.twofa.use_recovery"] = "entrar con un código de recuperación", + ["web.acct.recovery.title"] = "Verificación con código de recuperación", + ["web.acct.recovery.intro"] = "Pediste entrar con un código de recuperación. Esta sesión no se va a recordar hasta que uses un código de la app autenticadora o desactives la verificación en dos pasos y vuelvas a entrar.", + ["web.acct.recovery.code"] = "Código de recuperación", + ["web.acct.regconf.title"] = "Confirmación de registro", + ["web.acct.regconf.nosender"] = "Esta app no tiene configurado un envío de correo real; mirá", + ["web.acct.regconf.docs"] = "esta documentación", + ["web.acct.regconf.configure"] = "para saber cómo configurarlo.", + ["web.acct.regconf.normally"] = "Normalmente esto llegaría por correo:", + ["web.acct.regconf.click"] = "Hacé clic acá para confirmar tu cuenta", + ["web.acct.regconf.check"] = "Revisá tu correo para confirmar tu cuenta.", + ["web.acct.resend.title"] = "Reenviar la confirmación por correo", + ["web.acct.resend.btn"] = "Reenviar", + ["web.acct.reset.your"] = "Restablecé tu contraseña.", + ["web.acct.reset.btn"] = "Restablecer", + ["web.acct.reset.conf.title"] = "Contraseña restablecida", + ["web.acct.reset.conf.text1"] = "Tu contraseña se restableció. Ahora podés", + ["web.acct.reset.conf.link"] = "entrar acá", + ["web.acct.newpass"] = "Contraseña nueva", + ["web.acct.oldpass"] = "Contraseña actual", + ["web.acct.confirmpass"] = "Repetí la contraseña", + ["web.acct.enterpass"] = "Ingresá tu contraseña.", + ["web.acct.confirmpass.ph"] = "Repetí tu contraseña.", + ["web.acct.oldpass.ph"] = "Ingresá la contraseña actual", + ["web.acct.newpass.ph"] = "Ingresá la contraseña nueva", + ["web.acct.password"] = "Contraseña", + ["web.acct.email"] = "Correo", + ["web.acct.chpass.title"] = "Cambiar la contraseña", + ["web.acct.chpass.btn"] = "Actualizar la contraseña", + ["web.acct.delete.title"] = "Borrar los datos personales", + ["web.acct.delete.warn"] = "Borrar estos datos elimina tu cuenta para siempre y no se puede deshacer.", + ["web.acct.delete.btn"] = "Borrar mis datos y cerrar mi cuenta", + ["web.acct.disable.title"] = "Desactivar la verificación en dos pasos", + ["web.acct.disable.only"] = "Esto solo desactiva la verificación en dos pasos.", + ["web.acct.disable.keys"] = "Desactivarla no cambia las claves de las apps autenticadoras. Si querés cambiar la clave de una app autenticadora, tenés que", + ["web.acct.disable.reset"] = "restablecer tus claves del autenticador.", + ["web.acct.disable.btn"] = "Desactivar", + ["web.acct.email.manage"] = "Administrar el correo", + ["web.acct.email.enter"] = "Ingresá tu correo", + ["web.acct.email.send_ver"] = "Enviar correo de verificación", + ["web.acct.email.new"] = "Correo nuevo", + ["web.acct.email.new.ph"] = "Ingresá un correo nuevo", + ["web.acct.email.change"] = "Cambiar el correo", + ["web.acct.auth.config"] = "Configurar la app autenticadora", + ["web.acct.auth.steps"] = "Para usar una app autenticadora, seguí estos pasos:", + ["web.acct.auth.step1"] = "Descargá una app autenticadora como Microsoft Authenticator para", + ["web.acct.auth.step1b"] = "o Google Authenticator para", + ["web.acct.auth.step2a"] = "Escaneá el código QR o ingresá esta clave", + ["web.acct.auth.step2b"] = "en tu app autenticadora. Los espacios y las mayúsculas no importan.", + ["web.acct.auth.qr"] = "Aprendé cómo", + ["web.acct.auth.qr_link"] = "habilitar la generación de códigos QR", + ["web.acct.auth.step3"] = "Cuando escanees el código QR o ingreses la clave, tu app te va a dar un código único. Ingresalo en el cuadro de abajo.", + ["web.acct.auth.code.ph"] = "Ingresá el código", + ["web.acct.auth.code"] = "Código de verificación", + ["web.acct.auth.verify"] = "Verificar", + ["web.acct.ext.registered"] = "Cuentas vinculadas", + ["web.acct.ext.remove"] = "Quitar", + ["web.acct.ext.add"] = "Agregar otro servicio para entrar.", + ["web.acct.recov.codes"] = "Códigos de recuperación", + ["web.acct.recov.safe"] = "Guardá estos códigos en un lugar seguro.", + ["web.acct.recov.lose"] = "Si perdés tu dispositivo y no tenés los códigos de recuperación, perdés el acceso a tu cuenta.", + ["web.acct.recov.gen.title"] = "Generar códigos de recuperación de la verificación en dos pasos", + ["web.acct.recov.gen.keys"] = "Generar códigos nuevos no cambia las claves de las apps autenticadoras. Si querés cambiar la clave de una app autenticadora, tenés que", + ["web.acct.recov.gen.btn"] = "Generar códigos de recuperación", + ["web.acct.profile.title"] = "Perfil", + ["web.acct.profile.username"] = "Usuario", + ["web.acct.profile.phone"] = "Teléfono", + ["web.acct.profile.phone.ph"] = "Ingresá tu teléfono", + ["web.acct.profile.save"] = "Guardar", + ["web.acct.pk.title"] = "Tus claves de acceso", + ["web.acct.pk.rename"] = "Renombrar", + ["web.acct.pk.delete"] = "Borrar", + ["web.acct.pk.none"] = "No hay claves de acceso registradas.", + ["web.acct.pk.max"] = "Llegaste al máximo de claves de acceso. Borrá una antes de agregar otra.", + ["web.acct.pk.add"] = "Agregar una clave de acceso", + ["web.acct.pk.rename.title"] = "Poné un nombre a tu clave de acceso", + ["web.acct.pk.rename.name"] = "Nombre de la clave", + ["web.acct.pk.continue"] = "Continuar", + ["web.acct.pd.title"] = "Datos personales", + ["web.acct.pd.text"] = "Tu cuenta tiene los datos personales que nos diste. Desde acá podés descargarlos o borrarlos.", + ["web.acct.pd.download"] = "Descargar", + ["web.acct.resetauth.title"] = "Restablecer la clave del autenticador", + ["web.acct.resetauth.warn"] = "Si restablecés la clave, tu app autenticadora no va a funcionar hasta que la configures de nuevo.", + ["web.acct.resetauth.text"] = "Esto desactiva la verificación en dos pasos hasta que verifiques la app. Si no terminás la configuración, podrías perder el acceso a tu cuenta.", + ["web.acct.setpass.title"] = "Poné tu contraseña", + ["web.acct.setpass.text"] = "No tenés usuario y contraseña propios en este sitio. Agregalos para poder entrar sin una cuenta externa.", + ["web.acct.setpass.btn"] = "Guardar la contraseña", + ["web.acct.tf.title"] = "Verificación en dos pasos", + ["web.acct.tf.none_left"] = "No te quedan códigos de recuperación.", + ["web.acct.tf.none_left2"] = "Tenés que", + ["web.acct.tf.gen_new"] = "generar un juego nuevo de códigos de recuperación", + ["web.acct.tf.none_left3"] = "antes de poder entrar con uno.", + ["web.acct.tf.one_left"] = "Te queda 1 código de recuperación.", + ["web.acct.tf.can"] = "Podés", + ["web.acct.tf.few"] = "Te conviene", + ["web.acct.tf.forget"] = "Olvidar este navegador", + ["web.acct.tf.reset_codes"] = "Restablecer los códigos de recuperación", + ["web.acct.tf.app"] = "App autenticadora", + ["web.acct.tf.add_app"] = "Agregar una app autenticadora", + ["web.acct.tf.setup_app"] = "Configurar la app autenticadora", + ["web.acct.tf.reset_app"] = "Restablecer la app autenticadora", + ["web.acct.tf.privacy"] = "No se aceptó la política de privacidad y cookies.", + ["web.acct.tf.privacy2"] = "Tenés que aceptarla antes de activar la verificación en dos pasos.", + ["web.acct.m.confirm.ok"] = "Gracias por confirmar tu correo.", + ["web.acct.m.confirm.err"] = "No se pudo confirmar tu correo.", + ["web.acct.m.change.ok"] = "Gracias por confirmar el cambio de correo.", + ["web.acct.m.change.err"] = "No se pudo cambiar el correo.", + ["web.acct.m.invalid2fa"] = "Código del autenticador no válido.", + ["web.acct.m.invalid_recovery"] = "Código de recuperación no válido.", + ["web.acct.m.pw_changed"] = "Tu contraseña se cambió", + ["web.acct.m.bad_pw"] = "Contraseña incorrecta.", + ["web.acct.m.email_same"] = "Tu correo no cambió.", + ["web.acct.m.email_link"] = "Enviamos el enlace para confirmar el cambio. Revisá tu correo.", + ["web.acct.m.ver_sent"] = "Enviamos el correo de verificación. Revisalo.", + ["web.acct.m.code_invalid"] = "El código de verificación no es válido.", + ["web.acct.m.auth_ok"] = "Tu app autenticadora quedó verificada.", + ["web.acct.m.ext_not_removed"] = "No se quitó la cuenta externa.", + ["web.acct.m.ext_removed"] = "Se quitó la cuenta externa.", + ["web.acct.m.ext_added"] = "Se agregó la cuenta externa.", + ["web.acct.m.codes_new"] = "Generaste códigos de recuperación nuevos.", + ["web.acct.m.phone_fail"] = "No se pudo guardar el teléfono.", + ["web.acct.m.profile_ok"] = "Se actualizó tu perfil", + ["web.acct.m.pk_none"] = "El navegador no entregó una clave de acceso.", + ["web.acct.m.pk_max"] = "Llegaste al máximo de claves de acceso.", + ["web.acct.m.pk_add_fail"] = "No se pudo agregar la clave de acceso a tu cuenta.", + ["web.acct.m.pk_del_fail"] = "No se pudo borrar la clave de acceso.", + ["web.acct.m.pk_deleted"] = "Se borró la clave de acceso.", + ["web.acct.m.pk_bad_id"] = "El identificador de la clave de acceso no es válido.", + ["web.acct.m.pk_notfound"] = "No se encontró esa clave de acceso.", + ["web.acct.m.pk_upd_fail"] = "No se pudo actualizar la clave de acceso.", + ["web.acct.m.pk_updated"] = "Se actualizó la clave de acceso.", + ["web.acct.m.setpw_ok"] = "Se guardó tu contraseña.", + + ["web.val.required"] = "Este campo es obligatorio.", + ["web.val.email"] = "Ingresá un correo válido.", + ["web.val.length"] = "Usá entre {0} y {1} caracteres.", + ["web.val.match"] = "Las dos contraseñas no coinciden.", + ["web.idn.default"] = "Algo salió mal. Probá de nuevo.", + ["web.idn.short"] = "La contraseña necesita al menos {0} caracteres.", + ["web.idn.symbol"] = "La contraseña necesita al menos un símbolo (como ! o #).", + ["web.idn.digit"] = "La contraseña necesita al menos un dígito.", + ["web.idn.lower"] = "La contraseña necesita al menos una letra minúscula.", + ["web.idn.upper"] = "La contraseña necesita al menos una letra mayúscula.", + ["web.idn.unique"] = "La contraseña necesita al menos {0} caracteres distintos.", + ["web.idn.mismatch"] = "Esa contraseña es incorrecta.", + ["web.idn.taken"] = "{0} ya está registrado.", + ["web.idn.email"] = "Ingresá un correo válido.", + ["web.idn.linked"] = "Esa cuenta ya está vinculada a otro usuario.", + ["web.acct.pk.rename_named"] = "Poné un nombre nuevo a tu clave de acceso \"{0}\"", + ["web.acct.tf.left_n"] = "Te quedan {0} códigos de recuperación.", + ["web.acct.ext.remove_tip"] = "Quitar esta cuenta de {0} de tu usuario", + ["web.acct.ext.login_tip"] = "Entrar con tu cuenta de {0}", + + ["web.acct.assoc"] = "Vinculá tu cuenta de {0}.", + + ["web.acct.m.ext_load"] = "No se pudo cargar la información de la cuenta externa.", + ["web.acct.pk.unnamed"] = "Clave sin nombre", + // ── App web: Configuración, Ayuda, Foto, datos ── + ["webSettings.title"] = "Configuración", + ["webSettings.summary"] = "Servicios de música, país, tema, idioma, reconocimiento de texto y tus datos. La sección de música tiene su botón Guardar; lo demás se guarda apenas lo cambiás.", + ["webSettings.keys.note"] = "Las claves son de solo escritura: una vez guardadas no se vuelven a mostrar. Dejá un campo vacío para conservar la guardada.", + ["webSettings.steps"] = "Cómo conseguir las claves", + ["webSettings.keys.on"] = "Configurada", + ["webSettings.keys.off"] = "Sin configurar", + ["webSettings.client_id"] = "Client ID", + ["webSettings.client_secret"] = "Client secret", + ["webSettings.secret.saved"] = "Guardada. Escribí para reemplazarla", + ["webSettings.secret.empty"] = "Pegala acá", + ["webSettings.remove"] = "Quitar las claves de {0}", + ["webSettings.save"] = "Guardar", + ["webSettings.saved"] = "Guardado.", + ["webSettings.unchanged"] = "No cambió nada.", + ["webSettings.test"] = "Probar las claves guardadas de {0}", + ["webSettings.removed"] = "Se quitaron las claves de {0}.", + ["webSettings.testing"] = "Probando…", + ["webSettings.test.ok"] = "{0} respondió: las claves funcionan.", + ["webSettings.test.missing"] = "Primero guardá el Client ID y el secret de {0}.", + ["webSettings.test.unexpected"] = "No se pudo probar {0} ahora. Probá de nuevo en un rato.", + ["webSettings.theme.text"] = "Claro u oscuro; por defecto, el de tu dispositivo", + ["webSettings.theme.system"] = "Usar el de mi dispositivo", + ["webSettings.language.text"] = "Inglés o español; por defecto, el de tu navegador", + ["webSettings.language.system"] = "Usar el idioma de mi navegador", + ["webSettings.ocr.text"] = "El idioma con el que se lee el texto de una foto de revista", + ["webSettings.ocr.auto"] = "Automático (español e inglés)", + ["webSettings.ocr.es"] = "Español", + ["webSettings.ocr.en"] = "Inglés", + ["webSettings.connect.title"] = "App de Windows", + ["webSettings.connect.text"] = "Vinculá Queueify de una PC con esta lista usando un token personal.", + ["webSettings.connect.open"] = "Conectar una PC", + ["webSettings.signout.title"] = "Sesiones en otros dispositivos", + ["webSettings.signout.text"] = "Cerrar sesión acá no termina tus sesiones en otros dispositivos. Cambiar la contraseña en Cuenta cierra la sesión en todos los demás.", + ["webSettings.signout.open"] = "Abrir cuenta", + ["webSettings.delete.title"] = "Borrar mis datos", + ["webSettings.delete.text"] = "Elimina toda tu lista, las claves guardadas y tus preferencias de este servidor. Tu usuario sigue; borralo en Cuenta. No se puede deshacer, así que antes descargá una copia.", + ["webSettings.delete.sure"] = "Entiendo que no se puede deshacer", + ["webSettings.delete.button"] = "Borrar mis datos", + ["webSettings.delete.done"] = "Se borraron tus datos.", + ["webSettings.failed"] = "No se pudo guardar ({0}). Probá de nuevo.", + ["webData.title"] = "Tus datos", + ["webData.text"] = "Descargá tu lista o traé la de la app de Windows. Los álbumes conservan su identidad, así que importar dos veces nunca los duplica.", + ["webData.export.json"] = "Descargar JSON", + ["webData.export.csv"] = "Descargar CSV", + ["webData.import.title"] = "Importar", + ["webData.import.text"] = "Elegí el queueify.db de la app de Windows (en %LOCALAPPDATA%\\Queueify) o un JSON descargado desde acá.", + ["webData.import.choose"] = "Elegir un archivo", + ["webData.import.button"] = "Importar", + ["webData.import.working"] = "Importando…", + ["webData.import.done"] = "Importado: {0} nuevos, {1} que ya estaban, {2} salteados.", + ["webData.import.too_big"] = "Ese archivo es demasiado grande (máximo {0} MB).", + ["webData.import.invalid"] = "Eso no es una lista de Queueify: elegí el queueify.db de la app de Windows o un JSON descargado desde acá.", + ["webData.import.failed"] = "No se pudo importar ese archivo. Probá de nuevo, o descargá una copia nueva.", + ["webHelp.title"] = "Ayuda", + ["webHelp.summary"] = "Cómo funciona todo, y los atajos de teclado", + ["webHelp.guide.5"] = "5. Modo fiaca: sacale una foto a la página en Foto de revista y tocá el artista y el álbum en lugar de escribir.", + ["webHelp.touch"] = "En el celular: tocá un álbum para ver sus opciones; agregá Queueify a la pantalla de inicio desde el menú del navegador.", + ["webHelp.sync"] = "Para tener juntas la app de Windows y esta lista, abrí Configuración → Conectar una PC y pegá el texto que te da en el diálogo Sincronizar de la app.", + ["webHelp.trouble.1"] = "• “Spotify rechazó el Client ID”: abrí Configuración y pegá de nuevo las claves de developer.spotify.com/dashboard, y apretá Probar las claves. La cuenta dueña de la app necesita Premium.", + ["webHelp.trouble.2"] = "• No se encuentra un álbum: usá menos palabras (artista + título principal), revisá la ortografía o agregalo sin enlace.", + ["webHelp.trouble.3"] = "• El texto de una foto se lee mal: usá buena luz y sacá la página de frente. Las fotos se leen en español e inglés; cambialo en Configuración.", + ["webHelp.tour.title"] = "Recorrido rápido", + ["webHelp.tour.1.title"] = "Agregá un álbum", + ["webHelp.tour.1"] = "Escribí lo que dice la revista, como “Charly García Clics Modernos”. Apretá Enter para buscar en Spotify y Tidal, y Enter otra vez para agregar la mejor coincidencia.", + ["webHelp.tour.2.title"] = "Tu lista", + ["webHelp.tour.2"] = "Todo lo que agregás espera acá. Apretá Escuchar para abrirlo en Tidal o Spotify. Marcá el círculo cuando lo hayas oído; pasa a Escuchados, donde le podés poner puntaje.", + ["webHelp.tour.3.title"] = "¿Fiaca de escribir?", + ["webHelp.tour.3"] = "Sacale una foto a una página de revista y tocá el artista y el álbum.", + ["webHelp.tour.4.title"] = "Configuración", + ["webHelp.tour.4"] = "Pegá acá una vez tus claves de Spotify o Tidal. También podés conectar la app de Windows y descargar tu lista.", + ["webPhoto.title"] = "Foto de revista", + ["webPhoto.summary"] = "Sacá o elegí una foto de una página y tocá el artista y el álbum.", + ["webPhoto.choose"] = "Elegir una foto", + ["webPhoto.take"] = "Sacar una foto", + ["webPhoto.drop"] = "Soltá una foto acá, pegá una con Ctrl+V o usá los botones.", + ["webPhoto.language"] = "Leer la foto en", + ["webPhoto.reading"] = "Leyendo la página…", + ["webPhoto.privacy"] = "La foto se lee y se descarta; el servidor no guarda nada.", + ["webPhoto.tap"] = "Tocá el artista y el álbum, en ese orden, y buscá.", + ["webPhoto.search"] = "Buscar “{0}”", + ["webPhoto.clear"] = "Borrar la selección", + ["webPhoto.no_text"] = "No se encontró texto. Probá con una foto más nítida, bien iluminada y de frente.", + ["webPhoto.preview"] = "Tu foto, con las líneas de texto que se encontraron", + ["webPhoto.err.tooLarge"] = "Esa foto es demasiado grande (hasta {0} MB). Probá con una más chica.", + ["webPhoto.err.tooManyPixels"] = "Esa foto tiene demasiados píxeles. Probá con una más chica.", + ["webPhoto.err.notAnImage"] = "Ese archivo no es una foto JPG, PNG o WebP. Fotos HEIC del iPhone: compartilas como JPG, o poné la cámara en Más compatible.", + ["webPhoto.err.corrupt"] = "Esa foto parece dañada y no se pudo abrir. Probá sacarla de nuevo.", + ["webPhoto.err.busy"] = "Ya se está leyendo una foto. Esperá un momento y probá de nuevo.", + ["webPhoto.err.timeout"] = "Leer la foto tardó demasiado. Probá con una más chica o más clara.", + ["webPhoto.err.engineMissing"] = "Leer fotos no está disponible ahora. Pedile a quien administra este servidor que revise el lector de texto.", + ["webPhoto.err.unauthorized"] = "Se terminó tu sesión. Volvé a ingresar.", + ["webPhoto.err.network"] = "No se pudo enviar la foto. Revisá la conexión y probá de nuevo.", + ["webPhoto.err.language"] = "Ese idioma no está disponible.", + ["webPhoto.err.unknown"] = "Algo salió mal al leer la foto. Probá de nuevo en un rato.", + ["webPhoto.found"] = "Se encontraron {0} líneas. Tocá el artista y el álbum, en ese orden, y buscá.", + ["webHelp.col.keys"] = "Teclas", + ["webHelp.col.does"] = "Qué hace", + // ── 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.", + + ["web.keys.ctrl_k"] = "Ir a Agregar y a su cuadro de búsqueda", + ["webSync.setup.option"] = "Conectarme a un servidor web de Queueify", + ["webSync.setup.text"] = "En el menú de tu app web de Queueify (no en esta app), 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. Tiene tres partes separadas por |: \"queueify-web\", una dirección https y el token.", + ["webSync.keys_notice"] = "Tus claves de Spotify y Tidal se comparten con este servidor: si todavía no tiene, se le envían las de esta PC; si tiene, esta PC toma las del servidor. Conectate solo a un servidor tuyo o de confianza.", + ["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 el menú de 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. El token sigue funcionando hasta que lo revoques en la app web.", + ["webSync.tip.at"] = "Sincronizado con el servidor web ({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 (si esta PC está conectada, abrí Sincronizar y elegí Desconectar esta PC primero).", + ["webSync.err.unauthorized"] = "El servidor web no aceptó el token de esta PC. Puede que lo hayan revocado: creá un token nuevo en la app web y conectate de nuevo con el texto de conexión nuevo (si esta PC está conectada, abrí Sincronizar y elegí Desconectar esta PC primero).", + ["webSync.err.redirect"] = "El servidor web redirigió esta PC a otra dirección, así que no se envió nada. Conectate de nuevo con la dirección correcta (si esta PC está conectada, abrí Sincronizar y elegí Desconectar esta PC primero).", + ["webSync.err.server"] = "El servidor web tuvo un problema (error {0}). Tus cambios quedan guardados 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 quedan guardados; 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 quedan guardados y se sincronizan cuando el servidor responda.", + ["webSync.help"] = "En lugar de Firebase podés sincronizar con un servidor web de Queueify (el tuyo): en el menú de 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/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.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.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.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.Launcher/Queueify.Launcher.csproj b/Queueify.Launcher/Queueify.Launcher.csproj index af1b5a1..3407a03 100644 --- a/Queueify.Launcher/Queueify.Launcher.csproj +++ b/Queueify.Launcher/Queueify.Launcher.csproj @@ -7,8 +7,6 @@ win-x64 Queueify.Launcher Queueify.Launcher - enable - enable ..\Queueify\Assets\Queueify.ico app.manifest 1.4.0 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/BacklogStoreMergeTests.cs b/Queueify.Tests/BacklogStoreMergeTests.cs new file mode 100644 index 0000000..090eab6 --- /dev/null +++ b/Queueify.Tests/BacklogStoreMergeTests.cs @@ -0,0 +1,55 @@ +using Queueify.Models; +using Queueify.Services; + +namespace Queueify.Tests; + +public sealed class BacklogStoreMergeTests : IDisposable +{ + private readonly string _dir = Path.Combine(Path.GetTempPath(), "qm-" + Guid.NewGuid().ToString("N")); + private BacklogStore Store() => new(Path.Combine(_dir, "queueify.db")); + public void Dispose() { try { Directory.Delete(_dir, true); } catch (IOException) { } } + + private static BacklogItem Item(string uid, string album, DateTime updated) => + new() { Uid = uid, Artist = "A", Album = album, AddedAt = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc), UpdatedAt = updated }; + + 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); + + [Fact] + public void MergeBackup_AddsNewAlbumsKeepingTheirUidAndEditTime() + { + var store = Store(); + + Assert.Equal((1, 0), store.MergeBackup([Item("u1", "One", Old)])); + + var stored = store.FindByUid("u1")!; + Assert.Equal(Old, stored.UpdatedAt); + Assert.True(stored.Dirty); // still to be handed to the sync, which stamps it for the other PCs + } + + [Fact] + public void MergeBackup_NewerCopyWinsAndOlderOrEqualDoesNot() + { + var store = Store(); + store.MergeBackup([Item("u1", "Old title", Old)]); + + store.MergeBackup([Item("u1", "Same time", Old)]); + Assert.Equal("Old title", store.FindByUid("u1")!.Album); + + Assert.Equal((0, 1), store.MergeBackup([Item("u1", "New title", New)])); + Assert.Equal("New title", store.FindByUid("u1")!.Album); + } + + [Fact] + public void MergeBackup_DoesNotBringBackAnAlbumDeletedHere() + { + var store = Store(); + var item = Item("u1", "One", Old); + store.Insert(item); + store.Delete(item); + + store.MergeBackup([Item("u1", "One", DateTime.UtcNow.AddDays(1))]); + + Assert.Empty(store.LoadAll()); + } +} diff --git a/Queueify.Tests/BacklogStoreSafetyTests.cs b/Queueify.Tests/BacklogStoreSafetyTests.cs new file mode 100644 index 0000000..fe77547 --- /dev/null +++ b/Queueify.Tests/BacklogStoreSafetyTests.cs @@ -0,0 +1,239 @@ +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); + } + + + // ───────────── 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/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/LocTests.cs b/Queueify.Tests/LocTests.cs index 82f788d..d335f1c 100644 --- a/Queueify.Tests/LocTests.cs +++ b/Queueify.Tests/LocTests.cs @@ -36,8 +36,8 @@ public void EveryKeyTheAppUses_Exists() var root = RepoRoot(); var used = new HashSet(); foreach (var file in Directory.EnumerateFiles(root, "*.*", SearchOption.AllDirectories) - .Where(f => (f.EndsWith(".cs") || f.EndsWith(".xaml")) && !f.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}") - && !f.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}") && !f.Contains("Queueify.Tests"))) + .Where(f => (f.EndsWith(".cs") || f.EndsWith(".xaml") || f.EndsWith(".razor")) && !f.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}") + && !f.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}") && !f.Contains("Queueify.Tests") && !f.Contains("Queueify.Web.Tests"))) { var text = File.ReadAllText(file); foreach (Match m in CodeKey().Matches(text)) used.Add(m.Groups[1].Value); @@ -143,7 +143,7 @@ private static IEnumerable SourceFiles(string extension) => Directory.EnumerateFiles(RepoRoot(), "*" + extension, SearchOption.AllDirectories) .Where(f => !f.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}") && !f.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}") - && !f.Contains("Queueify.Tests") && !f.EndsWith("Strings.En.cs") && !f.EndsWith("Strings.Es.cs")); + && !f.Contains("Queueify.Tests") && !f.Contains("Queueify.Web.Tests") && !f.EndsWith("Strings.En.cs") && !f.EndsWith("Strings.Es.cs")); [Fact] public void T_UsesTheCurrentLanguage_AndFallsBackToTheKey() @@ -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/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/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.Tests/Queueify.Tests.csproj b/Queueify.Tests/Queueify.Tests.csproj index 1a03aaa..85cc5ad 100644 --- a/Queueify.Tests/Queueify.Tests.csproj +++ b/Queueify.Tests/Queueify.Tests.csproj @@ -7,15 +7,13 @@ net10.0-windows10.0.26100.0 Exe - enable - enable false false - + diff --git a/Queueify.Tests/ServerSyncPagingTests.cs b/Queueify.Tests/ServerSyncPagingTests.cs new file mode 100644 index 0000000..cbc8cff --- /dev/null +++ b/Queueify.Tests/ServerSyncPagingTests.cs @@ -0,0 +1,233 @@ +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); + } +} + +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.Tests/ServerSyncTests.cs b/Queueify.Tests/ServerSyncTests.cs new file mode 100644 index 0000000..f7bec26 --- /dev/null +++ b/Queueify.Tests/ServerSyncTests.cs @@ -0,0 +1,733 @@ +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, 1, 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); + + // A small overlap, in case the server commits two changes at nearly the same moment; applying a row twice is harmless. + Assert.Equal(first - ServerSync.Overlap, server.Requests[^1].Since); + Assert.Equal(2, server.Requests.Count); // the overlap doesn't make an idle sync loop + } + + [Fact] + public async Task Later_rounds_of_one_sync_ask_from_the_exact_server_time_without_overlap() + { + var server = new FakeServer(); + var store = NewStore(); + var settings = Connected(); + settings.WebLastServerTime = server.Clock; + for (int i = 0; i < 3; i++) store.Insert(Item("Album " + i)); + + await new ServerSync(new HttpClient(server), maxBatch: 2).SyncAsync(store, settings, CancellationToken.None); + + var firstStart = new DateTime(2026, 10, 1, 12, 0, 0, DateTimeKind.Utc); + Assert.Equal(firstStart - ServerSync.Overlap, server.Requests[0].Since); + Assert.Equal(firstStart.AddSeconds(1), server.Requests[1].Since); // the first answer's serverTime, exactly + } + + // ───────────── what a server may send ───────────── + + private static HttpResponseMessage Answer(SyncResponse r) => + new(HttpStatusCode.OK) { Content = new StringContent(JsonSerializer.Serialize(r, SyncJson.Default.SyncResponse), Encoding.UTF8, "application/json") }; + + [Fact] + public async Task Downloaded_text_is_cut_the_uid_checked_and_the_year_bounded() + { + var t = BacklogStore.Now(); + var long1 = new string('x', 5000); + var server = new FakeServer + { + Override = _ => Answer(new SyncResponse(t, + [ + new SyncAlbum("ok1", long1, long1, 99999, long1, long1, long1, long1, t, null, 9, t, false), + new SyncAlbum(new string('u', 65), "A", "B", 2000, null, null, null, null, t, null, -1, t, false), + new SyncAlbum("", "A", "B", 2000, null, null, null, null, t, null, -1, t, false), + ], null)), + }; + var store = NewStore(); + + await Client(server).SyncAsync(store, Connected(), CancellationToken.None); + + var got = Assert.Single(store.LoadAll()); + Assert.Equal("ok1", got.Uid); + 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); + } + + [Fact] + public async Task A_far_future_change_time_is_pulled_back_so_it_cannot_win_forever() + { + var future = new DateTime(9999, 1, 1, 0, 0, 0, DateTimeKind.Utc); + var server = new FakeServer + { + Override = _ => Answer(new SyncResponse(BacklogStore.Now(), + [Wire("f1", "Future", future)], + new SyncSettings("a", "b", "", "", "Tidal", "AR", future))), + }; + var store = NewStore(); + var settings = Connected(); + + await Client(server).SyncAsync(store, settings, CancellationToken.None); + + Assert.True(store.FindByUid("f1")!.UpdatedAt < BacklogStore.Now().AddMinutes(10)); + Assert.True(settings.SharedSettingsUpdatedAt < BacklogStore.Now().AddMinutes(10)); + } + + [Fact] + public async Task Shared_settings_from_the_server_are_cut_to_500_characters() + { + var big = new string('k', 4000); + var server = new FakeServer + { + Override = _ => Answer(new SyncResponse(BacklogStore.Now(), [], new SyncSettings(big, big, big, big, big, big, BacklogStore.Now()))), + }; + var settings = Connected(); + + await Client(server).SyncAsync(NewStore(), settings, CancellationToken.None); + + Assert.Equal(500, settings.SpotifyClientSecret.Length); + Assert.Equal(500, settings.TidalClientId.Length); + } + + [Fact] + public async Task A_null_album_in_the_answer_is_a_bad_reply_not_a_crash() + { + var server = new FakeServer + { + Override = _ => new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent("""{"serverTime":"2026-10-14T12:00:00Z","albums":[null],"settings":null}""", Encoding.UTF8, "application/json"), + }, + }; + + var ex = await Assert.ThrowsAsync(() => Client(server).SyncAsync(NewStore(), Connected(), CancellationToken.None)); + + Assert.Equal(Loc.T("webSync.err.bad_reply"), ex.Message); + } + + [Theory] + [InlineData("""{"albums":[]}""")] // no serverTime + [InlineData("""{"serverTime":"9999-01-01T00:00:00Z","albums":[]}""")] // absurd serverTime + public async Task A_reply_without_a_usable_server_time_is_a_bad_reply_and_changes_nothing(string json) + { + var server = new FakeServer + { + Override = _ => new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") }, + }; + var settings = Connected(); + + var ex = await Assert.ThrowsAsync(() => Client(server).SyncAsync(NewStore(), settings, CancellationToken.None)); + + Assert.Equal(Loc.T("webSync.err.bad_reply"), ex.Message); + Assert.Null(settings.WebLastServerTime); + } + + [Fact] + public async Task A_stored_sync_position_at_the_very_start_of_time_does_not_crash_the_next_sync() + { + var server = new FakeServer(); + var settings = Connected(); + settings.WebLastServerTime = DateTime.MinValue; + + await Client(server).SyncAsync(NewStore(), settings, CancellationToken.None); + + Assert.Null(server.Requests[0].Since); + } + + private sealed class CutContent : HttpContent + { + protected override Task SerializeToStreamAsync(Stream stream, System.Net.TransportContext? context) => throw new IOException("connection reset"); + protected override bool TryComputeLength(out long length) { length = 0; return false; } + protected override Task CreateContentReadStreamAsync() => throw new IOException("connection reset"); + } + + [Fact] + public async Task A_connection_cut_while_the_answer_arrives_is_the_offline_message() + { + var server = new FakeServer { Override = _ => new HttpResponseMessage(HttpStatusCode.OK) { Content = new CutContent() } }; + + var ex = await Assert.ThrowsAsync(() => Client(server).SyncAsync(NewStore(), Connected(), CancellationToken.None)); + + Assert.Equal(Loc.T("webSync.err.offline"), ex.Message); + } + + [Fact] + public async Task An_oversized_answer_is_refused_without_reading_it() + { + var server = new FakeServer + { + Override = _ => + { + var content = new StringContent("{}"); + content.Headers.ContentLength = ServerSync.MaxAnswerBytes + 1; + return new HttpResponseMessage(HttpStatusCode.OK) { Content = content }; + }, + }; + + var ex = await Assert.ThrowsAsync(() => Client(server).SyncAsync(NewStore(), Connected(), CancellationToken.None)); + + Assert.Equal(Loc.T("webSync.err.bad_reply"), ex.Message); + } + + [Fact] + public async Task The_apps_own_client_does_not_follow_a_redirect_to_another_server() + { + using var first = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0); + using var second = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0); + first.Start(); + second.Start(); + int secondPort = ((IPEndPoint)second.LocalEndpoint).Port; + int firstPort = ((IPEndPoint)first.LocalEndpoint).Port; + var serving = Task.Run(async () => + { + using var c = await first.AcceptTcpClientAsync(); + var buffer = new byte[4096]; + await c.GetStream().ReadAsync(buffer); + var reply = Encoding.ASCII.GetBytes($"HTTP/1.1 307 Temporary Redirect\r\nLocation: http://127.0.0.1:{secondPort}/api/sync\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); + await c.GetStream().WriteAsync(reply); + }); + using var http = ServerSync.CreateClient(); + var settings = new AppSettings { WebServerUrl = $"http://127.0.0.1:{firstPort}", WebToken = Token }; + + var ex = await Assert.ThrowsAsync(() => new ServerSync(http).SyncAsync(NewStore(), settings, CancellationToken.None)); + await serving; + + Assert.Equal(Loc.T("webSync.err.redirect"), ex.Message); + Assert.False(second.Pending()); + } + + [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 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, 1, 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, 1, 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, 1, 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, 1, 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, 1, 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, 1, 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, 1, 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.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.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.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.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/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/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/AlbumSearchTests.cs b/Queueify.Web.Tests/AlbumSearchTests.cs new file mode 100644 index 0000000..abfd093 --- /dev/null +++ b/Queueify.Web.Tests/AlbumSearchTests.cs @@ -0,0 +1,136 @@ +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); + Assert.NotNull(outcome); + + 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.NotNull(outcome); + + 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.NotNull(outcome); + + 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.NotNull(outcome); + + 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.NotNull(outcome); + 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.NotNull(outcome); + + 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.NotNull(outcome); + 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/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/ComponentTests.cs b/Queueify.Web.Tests/ComponentTests.cs new file mode 100644 index 0000000..cee5e59 --- /dev/null +++ b/Queueify.Web.Tests/ComponentTests.cs @@ -0,0 +1,631 @@ +using Bunit; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.AspNetCore.Components.Forms; +using Microsoft.FluentUI.AspNetCore.Components; +using Queueify.Models; +using Queueify.Services; +using Queueify.Web.Components.Layout; +using Queueify.Web.Components.Pages; +using Queueify.Web.Components.Shared; +using Queueify.Web.Services; +using Queueify.Web.Storage; + +namespace Queueify.Web.Tests; + +/// Shared setup: a scratch data folder, a signed-in user, fake catalogs. +public abstract class WebComponentTests : BunitContext +{ + protected readonly string Root = Path.Combine(Path.GetTempPath(), "qw-" + Guid.NewGuid().ToString("N")); + protected readonly FakeCatalogs Catalogs = new(); + protected UserStores Stores => new(Root); + + protected WebComponentTests() + { + JSInterop.Mode = JSRuntimeMode.Loose; + Services.AddFluentUIComponents(); + Services.AddSingleton(new UserStores(Root)); + Services.AddSingleton(new FixedUser("alice")); + Services.AddSingleton(Catalogs); + Services.AddScoped(); + Services.AddScoped(); + Services.AddScoped(); + Services.AddScoped(); + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + try { Directory.Delete(Root, true); } catch (IOException) { } + } + + protected UserQueue Queue => Services.GetRequiredService(); + protected Toasts Toasts => Services.GetRequiredService(); + + protected BacklogItem Seed(string artist, string album, int? year = null, string? source = null, string? tidal = null, string? spotify = null, int daysAgo = 0) + { + var q = new UserQueue(Stores, new FixedUser("alice")); + q.LoadAsync().GetAwaiter().GetResult(); + var item = q.Add(new BacklogItem { Artist = artist, Album = album, Year = year, TidalId = tidal, SpotifyId = spotify }, source ?? ""); + if (daysAgo != 0) + { + item.AddedAt = DateTime.Now.AddDays(-daysAgo); + Stores.QueueOf("alice").Update(item); + } + return item; + } + + protected void SaveKeys(bool spotify = true, bool tidal = true) => + Stores.SaveSettings("alice", new AppSettings + { + SpotifyClientId = spotify ? "id" : "", SpotifyClientSecret = spotify ? "s" : "", + TidalClientId = tidal ? "id" : "", TidalClientSecret = tidal ? "s" : "", + }); + + protected static string[] Titles(IRenderedComponent cut) => + cut.FindAll(".q-title").Select(e => e.TextContent.Trim()).ToArray(); + + protected sealed class FixedUser(string id) : IUserContext + { + public Task UserIdAsync() => Task.FromResult(id); + } + + private sealed class NoAntiforgery : AntiforgeryStateProvider + { + public override AntiforgeryRequestToken? GetAntiforgeryToken() => null; + } + + public sealed class FakeCatalogs : ICatalogs + { + public List Spotify { get; set; } = []; + public List Tidal { get; set; } = []; + public List Queries { get; } = []; + + /// When set, searches wait here until the test lets them go. + public TaskCompletionSource? Gate { get; set; } + + public async Task> SearchAsync(MusicService service, string query, string userId, AppSettings settings, CancellationToken ct) + { + Queries.Add(query); + if (Gate != null) await Gate.Task; + return service == MusicService.Spotify ? Spotify : Tidal; + } + } +} + +public sealed class QueuePageTests : WebComponentTests +{ + private IRenderedComponent Open(bool listened = false) => + Render(p => p.Add(c => c.Listened, listened)); + + [Fact] + public void The_queue_lists_waiting_albums_oldest_first() + { + Seed("Soda Stereo", "Signos", 1986, daysAgo: 1); + Seed("Charly García", "Clics Modernos", 1983, daysAgo: 5); + + Assert.Equal(["Clics Modernos", "Signos"], Titles(Open())); + } + + [Fact] + public void The_filter_narrows_the_list_and_says_so_when_nothing_matches() + { + Seed("Soda Stereo", "Signos"); + Seed("Charly García", "Clics Modernos"); + var cut = Open(); + + cut.Find("#q-filter").Input("garcia"); + cut.WaitForAssertion(() => Assert.Equal(["Clics Modernos"], Titles(cut))); + + cut.Find("#q-filter").Input("zzz"); + cut.WaitForAssertion(() => Assert.Empty(Titles(cut))); + Assert.Contains(Loc.T("empty.filter.title"), cut.Markup); + } + + [Fact] + public void The_filter_waits_for_a_pause_in_typing_and_only_the_last_text_counts() + { + Seed("Soda Stereo", "Signos"); + Seed("Charly García", "Clics Modernos"); + var cut = Open(); + + cut.Find("#q-filter").Input("s"); + cut.Find("#q-filter").Input("so"); + cut.Find("#q-filter").Input("soda"); + + Assert.Equal(2, Titles(cut).Length); // nothing was recomputed per keystroke + Assert.Equal("soda", cut.Find("#q-filter").GetAttribute("value")); // and the box keeps what was typed + cut.WaitForAssertion(() => Assert.Equal(["Signos"], Titles(cut))); + } + + [Fact] + public void Escape_clears_the_filter() + { + Seed("Soda Stereo", "Signos"); + Seed("Charly García", "Clics Modernos"); + var cut = Open(); + cut.Find("#q-filter").Input("soda"); + cut.WaitForAssertion(() => Assert.Single(Titles(cut))); + + cut.Find("#q-filter").KeyDown(new Microsoft.AspNetCore.Components.Web.KeyboardEventArgs { Key = "Escape" }); + + cut.WaitForAssertion(() => Assert.Equal(2, Titles(cut).Length), TimeSpan.FromSeconds(2)); + + Assert.Equal("", cut.Find("#q-filter").GetAttribute("value")); + } + + [Fact] + public void A_long_queue_draws_one_page_and_more_on_request() + { + var store = Stores.QueueOf("alice"); + for (var i = 0; i < 250; i++) store.Insert(new BacklogItem { Artist = "Artist " + i, Album = "Album " + i, AddedAt = DateTime.Now.AddMinutes(-1000 + i) }); + var cut = Open(); + + Assert.Equal(100, cut.FindAll("li.q-row").Count); + Assert.Contains("250", cut.Find(".q-sub").TextContent); // the summary still counts every album + + cut.Find("button.q-showmore").Click(); + Assert.Equal(200, cut.FindAll("li.q-row").Count); + cut.Find("button.q-showmore").Click(); + Assert.Equal(250, cut.FindAll("li.q-row").Count); + Assert.Empty(cut.FindAll("button.q-showmore")); + } + + [Fact] + public void A_new_filter_starts_again_from_the_first_page() + { + var store = Stores.QueueOf("alice"); + for (var i = 0; i < 250; i++) store.Insert(new BacklogItem { Artist = "Artist", Album = "Album " + i, AddedAt = DateTime.Now.AddMinutes(-1000 + i) }); + var cut = Open(); + cut.Find("button.q-showmore").Click(); + Assert.Equal(200, cut.FindAll("li.q-row").Count); + + cut.Find("#q-filter").Input("album"); + cut.WaitForAssertion(() => Assert.Equal(100, cut.FindAll("li.q-row").Count)); + } + + [Fact] + public void The_remembered_sort_and_covers_choice_come_back_in_one_browser_call() + { + Seed("Soda Stereo", "Signos", 1986, daysAgo: 1); + Seed("Charly García", "Clics Modernos", 1983, daysAgo: 5); + JSInterop.Setup("queueify.getMany", _ => true).SetResult(["year", "1"]); + + var cut = Open(); + + cut.WaitForAssertion(() => Assert.Equal(["Clics Modernos", "Signos"], Titles(cut))); + Assert.NotEmpty(cut.FindAll("ul.q-grid")); + Assert.Single(JSInterop.Invocations.Where(i => i.Identifier is "queueify.getMany")); + Assert.Empty(JSInterop.Invocations.Where(i => i.Identifier is "queueify.get")); + } + + [Fact] + public void Sorting_changes_the_order() + { + Seed("Soda Stereo", "Signos", 1986, daysAgo: 1); + Seed("Charly García", "Clics Modernos", 1983, daysAgo: 5); + Seed("Spinetta", "Artaud", 1973, daysAgo: 3); + var cut = Open(); + + cut.Find("#q-sort").Change("year"); + Assert.Equal(["Artaud", "Clics Modernos", "Signos"], Titles(cut)); + + cut.Find("#q-sort").Change("newest"); + Assert.Equal(["Signos", "Artaud", "Clics Modernos"], Titles(cut)); + + cut.Find("#q-sort").Change("artist"); + Assert.Equal(["Clics Modernos", "Signos", "Artaud"], Titles(cut)); + } + + [Fact] + public void Marking_listened_moves_the_album_and_undo_brings_it_back() + { + Seed("Soda Stereo", "Signos"); + var cut = Open(); + + cut.Find(".q-check").Click(); + + Assert.Empty(Titles(cut)); + var toast = Toasts.Current!; + Assert.Contains("Signos", toast.Message); + Assert.NotNull(toast.Rate); // the stars to rate it right away + + toast.Action!(); + cut.WaitForAssertion(() => Assert.Equal(["Signos"], Titles(cut))); + } + + [Fact] + public void Rating_right_after_listening_is_saved_and_shown_on_the_listened_page() + { + Seed("Soda Stereo", "Signos"); + var cut = Open(); + cut.Find(".q-check").Click(); + + Toasts.Current!.Rate!(4); + + var listened = Open(listened: true); + Assert.Equal(["Signos"], Titles(listened)); + Assert.Equal(4, listened.FindAll(".q-star.on").Count); + } + + [Fact] + public void Rating_on_the_listened_page_works_with_the_stars() + { + var item = Seed("Soda Stereo", "Signos"); + Queue.LoadAsync().GetAwaiter().GetResult(); + Queue.SetListened(Queue.All.Single(), true); + var cut = Open(listened: true); + + cut.FindAll(".q-star")[2].Click(); // three stars + + Queue.LoadAsync().GetAwaiter().GetResult(); + Assert.Equal(3, Queue.All.Single().Rating); + Assert.Equal(item.Uid, Queue.All.Single().Uid); + } + + [Fact] + public void Deleting_removes_the_album_and_undo_restores_it() + { + Seed("Soda Stereo", "Signos"); + var cut = Open(); + + cut.FindAll(".q-menu-list button").Single(b => b.TextContent.Contains(Loc.T("menu.delete"))).Click(); + Assert.Empty(Titles(cut)); + + Toasts.Current!.Action!(); + cut.WaitForAssertion(() => Assert.Equal(["Signos"], Titles(cut))); + } + + [Fact] + public void Play_opens_the_preferred_service_with_an_app_link_and_a_web_fallback() + { + Stores.SaveSettings("alice", new AppSettings { PreferredService = "Spotify" }); + Seed("Soda Stereo", "Signos", tidal: "111", spotify: "4aawyAB9vmqN3uQ7FjRGTy"); + var cut = Open(); + + var play = cut.Find("a.q-btn.primary"); + Assert.Equal("https://open.spotify.com/album/4aawyAB9vmqN3uQ7FjRGTy", play.GetAttribute("href")); + Assert.Equal("spotify:album:4aawyAB9vmqN3uQ7FjRGTy", play.GetAttribute("data-app")); + Assert.Contains("noopener", play.GetAttribute("rel")); + } + + [Fact] + public void An_album_without_links_has_no_play_button() + { + Seed("Soda Stereo", "Signos"); + var cut = Open(); + Assert.Empty(cut.FindAll("a.q-btn.primary")); + Assert.Contains(Loc.T("item.no_link"), cut.Markup); + } + + [Fact] + public void Surprise_me_picks_a_waiting_album_and_an_empty_queue_says_so() + { + var empty = Open(); + empty.Find("button[title='" + Loc.T("queue.surprise.tip") + "']").Click(); + Assert.Equal(Loc.T("toast.surprise_empty"), Toasts.Current!.Message); + + Seed("Soda Stereo", "Signos"); + var cut = Open(); + cut.Find("button[title='" + Loc.T("queue.surprise.tip") + "']").Click(); + + Assert.Contains("Signos", Toasts.Current!.Message); + Assert.Single(cut.FindAll(".q-row.picked")); + } + + [Fact] + public void The_cover_grid_shows_the_same_albums_as_tiles() + { + Seed("Soda Stereo", "Signos"); + var cut = Open(); + + cut.Find("fluent-switch").Change(true); + + cut.WaitForAssertion(() => Assert.Single(cut.FindAll("li.q-tile"))); + } + + [Fact] + public void Texts_follow_the_users_language() + { + using var _ = Loc.Override("es"); + var cut = Open(); + Assert.Contains("Para escuchar", cut.Markup); + Assert.Equal(Loc.T("queue.summary.empty"), cut.Find(".q-sub").TextContent.Trim()); + Assert.NotEqual(Loc.English["queue.summary.empty"], Loc.T("queue.summary.empty")); + } + + [Fact] + public void One_star_is_not_called_stars() + { + Assert.Equal("1 star", Stars.Label(1)); + Assert.Equal("3 stars", Stars.Label(3)); + } + + [Fact] + public void Nobody_elses_albums_are_listed() + { + var bobs = new UserQueue(Stores, new FixedUser("bob")); + bobs.LoadAsync().GetAwaiter().GetResult(); + bobs.Add(new BacklogItem { Album = "Bobs album" }, ""); + + Assert.DoesNotContain("Bobs album", Open().Markup); + } +} + +public sealed class NavMenuTests : WebComponentTests +{ + [Fact] + public void Every_page_is_in_the_navigation() + { + var cut = Render(); + var hrefs = cut.FindAll(".q-rail a").Select(a => a.GetAttribute("href")).ToList(); + + foreach (var expected in new[] { "", "add", "listened", "photo", "help", "settings", "connect" }) + Assert.Contains(expected, hrefs); + Assert.Single(cut.FindAll(".q-rail form[action='Account/Logout']")); + } + + [Fact] + public void Round_badges_show_how_many_are_waiting_and_listened() + { + Seed("A", "One"); + Seed("B", "Two"); + var third = Seed("C", "Three"); + var q = new UserQueue(Stores, new FixedUser("alice")); + q.LoadAsync().GetAwaiter().GetResult(); + q.SetListened(q.All.Single(i => i.Uid == third.Uid), true); + + var cut = Render(); + + Assert.Equal(["2", "1"], cut.FindAll(".q-rail .q-badge").Select(b => b.TextContent.Trim()).ToArray()); + Assert.Contains(cut.FindAll(".q-rail a").Select(a => a.GetAttribute("aria-label")), l => l!.Contains("2")); + } + + [Fact] + public void Badges_follow_changes_without_reloading() + { + Seed("A", "One"); + var cut = Render(); + Assert.Equal("1", cut.Find(".q-rail .q-badge").TextContent.Trim()); + + Queue.Add(new BacklogItem { Album = "Two" }, ""); + + cut.WaitForAssertion(() => Assert.Equal("2", cut.Find(".q-rail .q-badge").TextContent.Trim())); + } + + [Fact] + public void An_empty_queue_has_no_badges() => + Assert.Empty(Render().FindAll(".q-badge")); +} + +public sealed class AddPageTests : WebComponentTests +{ + 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 }; + + private IRenderedComponent Open() => Render(); + + [Fact] + public void Without_keys_an_info_bar_points_to_settings_and_adding_by_hand_stays_possible() + { + var cut = Open(); + + var link = cut.Find(".q-alert a"); + Assert.Equal("settings", link.GetAttribute("href")); + Assert.NotNull(cut.Find("details.q-quick")); + } + + [Fact] + public void With_keys_there_is_no_info_bar() + { + SaveKeys(); + Assert.Empty(Open().FindAll(".q-alert")); + } + + [Fact] + public void Searching_shows_merged_results_with_service_pills_and_the_score() + { + SaveKeys(); + Catalogs.Spotify = [Match(MusicService.Spotify, "sp1", "Clics Modernos", "Charly García", 1983)]; + Catalogs.Tidal = [Match(MusicService.Tidal, "td1", "Clics Modernos", "Charly García", 1983)]; + var cut = Open(); + + cut.Find("#q-search").Input("charly garcia clics modernos 1983"); + cut.Find("#q-search").KeyDown("Enter"); + + cut.WaitForAssertion(() => Assert.Single(cut.FindAll("li.q-result"))); + Assert.Empty(cut.FindAll(".q-pill.off")); + Assert.Contains(Loc.T("result.best"), cut.Markup); + Assert.Contains(Loc.T("search.press_enter"), cut.Markup); + } + + [Fact] + public void A_service_found_on_one_side_only_greys_the_other_pill() + { + SaveKeys(); + Catalogs.Tidal = [Match(MusicService.Tidal, "td1", "Signos", "Soda Stereo", 1986)]; + var cut = Open(); + + cut.Find("#q-search").Input("soda stereo signos"); + cut.Find("#q-search").KeyDown("Enter"); + + cut.WaitForAssertion(() => Assert.StartsWith("Spotify", cut.Find(".q-pill.off").TextContent.Trim())); + } + + [Fact] + public void Adding_a_result_saves_it_with_both_links_and_remembers_the_magazine() + { + SaveKeys(); + Catalogs.Spotify = [Match(MusicService.Spotify, "sp1", "Signos", "Soda Stereo", 1986)]; + Catalogs.Tidal = [Match(MusicService.Tidal, "td1", "Signos", "Soda Stereo", 1986)]; + var cut = Open(); + + cut.Find("#q-magazine").Input("Pelo"); + cut.Find("#q-search").Input("soda stereo signos"); + cut.Find("#q-search").KeyDown("Enter"); + cut.WaitForAssertion(() => Assert.Single(cut.FindAll("li.q-result"))); + cut.Find("li.q-result button.q-btn.primary").Click(); + + var saved = Stores.QueueOf("alice").LoadAll().Single(); + Assert.Equal(("Soda Stereo", "Signos", 1986, "Pelo", "sp1", "td1"), (saved.Artist, saved.Album, saved.Year, saved.Source, saved.SpotifyId, saved.TidalId)); + Assert.Equal("Pelo", Stores.LoadSettings("alice").LastSource); + Assert.Empty(cut.FindAll("li.q-result")); + Assert.Contains("Signos", Toasts.Current!.Message); + } + + [Fact] + public void Enter_on_a_confident_result_adds_it_and_undo_removes_it() + { + SaveKeys(tidal: false); + Catalogs.Spotify = [Match(MusicService.Spotify, "sp1", "Signos", "Soda Stereo", 1986)]; + var cut = Open(); + + cut.Find("#q-search").Input("soda stereo signos"); + cut.Find("#q-search").KeyDown("Enter"); // searches + cut.WaitForAssertion(() => Assert.Single(cut.FindAll("li.q-result"))); + cut.Find("#q-search").KeyDown("Enter"); // adds the highlighted one + + Assert.Single(Stores.QueueOf("alice").LoadAll()); + Toasts.Current!.Action!(); + Assert.Empty(Stores.QueueOf("alice").LoadAll()); + } + + [Fact] + public void Clearing_the_box_while_a_search_runs_stops_the_spinner_and_drops_the_results() + { + SaveKeys(tidal: false); + Catalogs.Spotify = [Match(MusicService.Spotify, "sp1", "Signos", "Soda Stereo", 1986)]; + Catalogs.Gate = new TaskCompletionSource(); + var cut = Open(); + + cut.Find("#q-search").Input("soda stereo signos"); + cut.Find("#q-search").KeyDown("Enter"); + cut.WaitForAssertion(() => Assert.Contains(Loc.T("search.searching"), cut.Find(".q-status").TextContent)); + + cut.Find("#q-search").Input("so"); // too short: the running search is abandoned + Catalogs.Gate.SetResult(); + + cut.WaitForAssertion(() => + { + Assert.DoesNotContain(Loc.T("search.searching"), cut.Find(".q-status").TextContent); + Assert.Empty(cut.FindAll("li.q-result")); + }); + } + + [Fact] + public void Adding_by_hand_while_a_search_runs_does_not_bring_old_results_back() + { + SaveKeys(tidal: false); + Catalogs.Spotify = [Match(MusicService.Spotify, "sp1", "Signos", "Soda Stereo", 1986)]; + Catalogs.Gate = new TaskCompletionSource(); + var cut = Open(); + + cut.Find("#q-search").Input("soda stereo signos"); + cut.Find("#q-search").KeyDown("Enter"); + cut.WaitForAssertion(() => Assert.Contains(Loc.T("search.searching"), cut.Find(".q-status").TextContent)); + cut.Find("#qa-album").Input("Artaud"); + cut.Find("form.q-quick-body").Submit(); + Catalogs.Gate.SetResult(); + + cut.WaitForAssertion(() => Assert.DoesNotContain(Loc.T("search.searching"), cut.Find(".q-status").TextContent)); + 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() + { + Stores.SaveSettings("alice", new AppSettings { LastSource = "Rolling Stone" }); + Assert.Equal("Rolling Stone", Open().Find("#q-magazine").GetAttribute("value")); + } + + [Fact] + public void An_album_that_is_already_saved_says_so_and_cannot_be_added_twice() + { + SaveKeys(tidal: false); + Seed("Soda Stereo", "Signos", spotify: "sp1"); + Catalogs.Spotify = [Match(MusicService.Spotify, "sp1", "Signos", "Soda Stereo", 1986)]; + var cut = Open(); + + cut.Find("#q-search").Input("soda stereo signos"); + cut.Find("#q-search").KeyDown("Enter"); + + cut.WaitForAssertion(() => Assert.Contains(Loc.T("search.state.queued"), cut.Markup)); + Assert.Empty(cut.FindAll("li.q-result button.q-btn.primary")); + } + + [Fact] + public void Without_a_close_match_adding_without_a_link_is_offered_and_splits_artist_and_album() + { + SaveKeys(tidal: false); + var cut = Open(); + + cut.Find("#q-search").Input("Los Abuelos - Himno de mi corazón 1986"); + cut.Find("#q-search").KeyDown("Enter"); + + cut.WaitForAssertion(() => cut.Find("button.q-btn.wide").Click()); + var saved = Stores.QueueOf("alice").LoadAll().Single(); + Assert.Equal(("Los Abuelos", "Himno de mi corazón", 1986), (saved.Artist, saved.Album, saved.Year)); + Assert.Null(saved.SpotifyId); + } + + [Fact] + public void The_quick_form_adds_an_album_by_hand() + { + var cut = Open(); + + cut.Find("#qa-artist").Input("Spinetta"); + cut.Find("#qa-album").Input("Artaud"); + cut.Find("#qa-year").Input("1973"); + cut.Find("form.q-quick-body").Submit(); + + var saved = Stores.QueueOf("alice").LoadAll().Single(); + Assert.Equal(("Spinetta", "Artaud", 1973), (saved.Artist, saved.Album, saved.Year)); + } + + [Fact] + public void The_quick_form_needs_an_album_name() + { + var cut = Open(); + cut.Find("#qa-artist").Input("Spinetta"); + Assert.NotNull(cut.Find("form.q-quick-body button[type=submit]").GetAttribute("disabled")); + cut.Find("form.q-quick-body").Submit(); + Assert.Empty(Stores.QueueOf("alice").LoadAll()); + } + + [Fact] + public void A_failing_service_is_reported_without_losing_the_other() + { + SaveKeys(); + Catalogs.Tidal = [Match(MusicService.Tidal, "td1", "Signos", "Soda Stereo", 1986)]; + Services.AddSingleton(new ThrowingSpotify(Catalogs)); + var cut = Open(); + + cut.Find("#q-search").Input("soda stereo signos"); + cut.Find("#q-search").KeyDown("Enter"); + + cut.WaitForAssertion(() => + { + Assert.Single(cut.FindAll("li.q-result")); + Assert.Contains("Spotify:", cut.Find(".q-status").TextContent); + }); + } + + private sealed class ThrowingSpotify(FakeCatalogs inner) : ICatalogs + { + public Task> SearchAsync(MusicService service, string query, string userId, AppSettings settings, CancellationToken ct) => + service == MusicService.Spotify ? throw new CatalogException("Spotify refused") : inner.SearchAsync(service, query, userId, settings, ct); + } +} diff --git a/Queueify.Web.Tests/Data/DataEndpointTests.cs b/Queueify.Web.Tests/Data/DataEndpointTests.cs new file mode 100644 index 0000000..c14c4d2 --- /dev/null +++ b/Queueify.Web.Tests/Data/DataEndpointTests.cs @@ -0,0 +1,162 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text; +using System.Text.Json; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Data.Sqlite; +using Queueify.Models; +using Queueify.Web.Services; +using Queueify.Web.Storage; +using Queueify.Web.Tests.Support; + +namespace Queueify.Web.Tests.Data; + +public sealed class DataEndpointTests : IClassFixture>, IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "qe-" + Guid.NewGuid().ToString("N")); + private readonly WebApplicationFactory _factory; + + public DataEndpointTests(WebApplicationFactory factory) => _factory = ScratchHost.On(factory, _root); + public void Dispose() { SqliteConnection.ClearAllPools(); try { Directory.Delete(_root, true); } catch (IOException) { } } + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private UserStores Stores() => new(_root); // same folders as the app; secrets are not needed here + + private void Seed(string user, string artist, string album, string uid) + { + Stores().QueueOf(user).Insert(new BacklogItem { Artist = artist, Album = album, Uid = uid, AddedAt = DateTime.UtcNow }); + } + + private static ByteArrayContent Body(byte[] bytes, string type = "application/octet-stream") + { + var c = new ByteArrayContent(bytes); + c.Headers.ContentType = new(type); + return c; + } + + [Theory] + [InlineData("/api/export.json")] + [InlineData("/api/export.csv")] + public async Task Exports_need_a_signed_in_user(string url) + { + var response = await _factory.ClientFor(null).GetAsync(url, Ct); + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + public async Task The_json_export_is_a_download_of_only_my_albums_and_never_cached() + { + Seed("alice", "Charly García", "Clics modernos", "a1"); + Seed("bob", "Bob's Band", "Bob's Album", "b1"); + + var response = await _factory.ClientFor("alice").GetAsync("/api/export.json", Ct); + var text = await response.Content.ReadAsStringAsync(Ct); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("attachment", response.Content.Headers.ContentDisposition!.DispositionType); + Assert.EndsWith(".json", response.Content.Headers.ContentDisposition.FileName!.Trim('"')); + Assert.Contains("no-store", response.Headers.CacheControl!.ToString()); + Assert.Contains("Clics modernos", text); + Assert.DoesNotContain("Bob", text); + } + + [Fact] + public async Task The_csv_export_opens_in_a_spreadsheet_with_its_accents() + { + Seed("alice", "Charly García", "Clics modernos", "a1"); + + var response = await _factory.ClientFor("alice").GetAsync("/api/export.csv", Ct); + var bytes = await response.Content.ReadAsByteArrayAsync(Ct); + + Assert.StartsWith("text/csv", response.Content.Headers.ContentType!.ToString()); + Assert.Equal(new byte[] { 0xEF, 0xBB, 0xBF }, bytes[..3]); // BOM: Excel reads UTF-8 only with it + Assert.Contains("Charly García", Encoding.UTF8.GetString(bytes)); + } + + [Fact] + public async Task Importing_an_export_brings_the_albums_in_once() + { + Seed("alice", "A", "One", "a1"); + var json = await (await _factory.ClientFor("alice").GetAsync("/api/export.json", Ct)).Content.ReadAsByteArrayAsync(Ct); + + var first = await _factory.ClientFor("bob").PostAsync("/api/import", Body(json, "application/json"), Ct); + var second = await _factory.ClientFor("bob").PostAsync("/api/import", Body(json, "application/json"), Ct); + + var report = await first.Content.ReadFromJsonAsync(Ct); + Assert.Equal(1, report.GetProperty("added").GetInt32()); + Assert.Equal(1, (await second.Content.ReadFromJsonAsync(Ct)).GetProperty("alreadyHere").GetInt32()); + Assert.Single(Stores().QueueOf("bob").LoadAll()); + } + + [Fact] + public async Task Import_needs_a_signed_in_user() + { + var response = await _factory.ClientFor(null).PostAsync("/api/import", Body("{}"u8.ToArray()), Ct); + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + [Fact] + public async Task A_cross_site_form_cannot_import_into_someones_queue() + { + var form = new FormUrlEncodedContent([new("a", "b")]); + var plain = new StringContent("{}", Encoding.UTF8, "text/plain"); + + Assert.Equal(HttpStatusCode.UnsupportedMediaType, (await _factory.ClientFor("alice").PostAsync("/api/import", form, Ct)).StatusCode); + Assert.Equal(HttpStatusCode.UnsupportedMediaType, (await _factory.ClientFor("alice").PostAsync("/api/import", plain, Ct)).StatusCode); + } + + [Fact] + public async Task A_crafted_database_is_refused_with_a_message_code_and_changes_nothing() + { + var path = Path.Combine(_root, "evil.db"); + Directory.CreateDirectory(_root); + using (var db = new SqliteConnection($"Data Source={path};Pooling=False")) + { + db.Open(); + foreach (var sql in new[] { "CREATE TABLE other (artist, album, added_at)", "CREATE VIEW items AS SELECT artist, album, added_at FROM other" }) + { using var c = db.CreateCommand(); c.CommandText = sql; c.ExecuteNonQuery(); } + } + SqliteConnection.ClearAllPools(); + + var response = await _factory.ClientFor("alice").PostAsync("/api/import", Body(await File.ReadAllBytesAsync(path, Ct)), Ct); + + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("invalid", (await response.Content.ReadFromJsonAsync(Ct)).GetProperty("error").GetString()); + Assert.Empty(Stores().QueueOf("alice").LoadAll()); + } + + [Fact] + public async Task An_upload_over_the_limit_is_refused_by_its_length() + { + var response = await _factory.ClientFor("alice").PostAsync("/api/import", Body(new byte[DataTransfer.MaxBytes + 10]), Ct); + Assert.Equal(HttpStatusCode.RequestEntityTooLarge, response.StatusCode); + } + + [Fact] + public async Task A_chunked_upload_over_the_limit_is_stopped_while_reading() + { + var content = new StreamContent(new MemoryStream(new byte[DataTransfer.MaxBytes + 10])); + content.Headers.ContentType = new("application/octet-stream"); + var request = new HttpRequestMessage(HttpMethod.Post, "/api/import") { Content = content }; + request.Headers.TransferEncodingChunked = true; + request.Headers.Add(HeaderUserAuthHandler.Header, "alice"); + + Assert.Equal(HttpStatusCode.RequestEntityTooLarge, (await _factory.CreateClient().SendAsync(request, Ct)).StatusCode); + } + + [Fact] + public async Task No_response_here_ever_carries_a_saved_secret() + { + Seed("alice", "A", "One", "a1"); + var stores = new UserStores(_root); + stores.SaveSettings("alice", new AppSettings { SpotifyClientId = "SPOTID", SpotifyClientSecret = "SPOTSECRET", TidalClientSecret = "TIDALSECRET" }); + var client = _factory.ClientFor("alice"); + + foreach (var url in new[] { "/api/export.json", "/api/export.csv" }) + { + var text = await (await client.GetAsync(url, Ct)).Content.ReadAsStringAsync(Ct); + Assert.DoesNotContain("SECRET", text); + } + } +} diff --git a/Queueify.Web.Tests/Data/DataTransferTests.cs b/Queueify.Web.Tests/Data/DataTransferTests.cs new file mode 100644 index 0000000..17d75ea --- /dev/null +++ b/Queueify.Web.Tests/Data/DataTransferTests.cs @@ -0,0 +1,433 @@ +using System.Text; +using System.Text.Json; +using Microsoft.Data.Sqlite; +using Queueify.Models; +using Queueify.Services; +using Queueify.Web.Services; +using Queueify.Web.Storage; + +namespace Queueify.Web.Tests.Data; + +public sealed class DataTransferTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "qd-" + Guid.NewGuid().ToString("N")); + private readonly UserStores _stores; + private readonly DataTransfer _transfer; + + public DataTransferTests() + { + _stores = new UserStores(_root); + _transfer = new DataTransfer(_stores); + } + + public void Dispose() { SqliteConnection.ClearAllPools(); try { Directory.Delete(_root, true); } catch (IOException) { } } + + private static BacklogItem Album(string artist, string album, string uid = "") => + new() { Artist = artist, Album = album, Uid = uid, Year = 1983, Source = "Rolling Stone 214", AddedAt = new DateTime(2026, 1, 2, 3, 4, 5, DateTimeKind.Utc), SpotifyId = "sp1", TidalId = "td1" }; + + /// A database as the desktop app writes it: made by BacklogStore itself. + private byte[] DesktopDb(params BacklogItem[] items) + { + var path = Path.Combine(_root, "desktop-" + Guid.NewGuid().ToString("N") + ".db"); + var store = new BacklogStore(path); + foreach (var item in items) store.Insert(item); + SqliteConnection.ClearAllPools(); + return File.ReadAllBytes(path); + } + + private byte[] RawDb(params string[] statements) + { + var path = Path.Combine(_root, "raw-" + Guid.NewGuid().ToString("N") + ".db"); + Directory.CreateDirectory(_root); + using (var db = new SqliteConnection($"Data Source={path};Pooling=False")) + { + db.Open(); + foreach (var sql in statements) + { + using var cmd = db.CreateCommand(); + cmd.CommandText = sql; + cmd.ExecuteNonQuery(); + } + } + SqliteConnection.ClearAllPools(); + return File.ReadAllBytes(path); + } + + private ImportProblem ProblemOf(byte[] bytes) => + Assert.Throws(() => _transfer.Import("alice", bytes)).Problem; + + private static string ItemsTable(string columns = "id INTEGER PRIMARY KEY, uid TEXT, artist TEXT, album TEXT, year INTEGER, source TEXT, cover_url TEXT, spotify_id TEXT, tidal_id TEXT, added_at TEXT, listened_at TEXT, rating REAL, updated_at TEXT, deleted INTEGER") => + $"CREATE TABLE items ({columns})"; + + // ── the desktop database ── + + [Fact] + public void The_desktop_queue_comes_in_with_its_uids_dates_and_ratings() + { + var listened = Album("Spinetta Jade", "Bajo Belgrano", "uid-2"); + listened.ListenedAt = new DateTime(2026, 2, 3, 0, 0, 0, DateTimeKind.Utc); + listened.Rating = 4.5; + var bytes = DesktopDb(Album("Charly García", "Clics modernos", "uid-1"), listened); + + var report = _transfer.Import("alice", bytes); + + Assert.Equal(new ImportReport(2, 0, 0), report); + var items = _stores.QueueOf("alice").LoadAll().OrderBy(i => i.Uid).ToList(); + Assert.Equal(["uid-1", "uid-2"], items.Select(i => i.Uid)); + Assert.Equal(("Charly García", "Clics modernos", 1983, "Rolling Stone 214"), (items[0].Artist, items[0].Album, items[0].Year, items[0].Source)); + Assert.Equal((4.5, true), (items[1].Rating, items[1].IsListened)); + Assert.Equal(("sp1", "td1"), (items[0].SpotifyId, items[0].TidalId)); + } + + [Fact] + public void Importing_the_same_file_twice_adds_nothing_the_second_time() + { + var bytes = DesktopDb(Album("A", "One", "u1"), Album("B", "Two", "u2")); + _transfer.Import("alice", bytes); + + var again = _transfer.Import("alice", bytes); + + Assert.Equal(new ImportReport(0, 2, 0), again); + Assert.Equal(2, _stores.QueueOf("alice").LoadAll().Count); + } + + [Fact] + public void A_newer_row_in_the_file_updates_the_one_here_and_an_older_one_does_not() + { + var store = _stores.QueueOf("alice"); + var here = Album("A", "Here", "u1"); + store.Insert(here); + + var stamp = (DateTime d) => d.ToString("O"); + var newer = RawDb(ItemsTable(), $"INSERT INTO items (uid, artist, album, added_at, rating, updated_at, deleted) VALUES ('u1','A','Newer title','{stamp(DateTime.UtcNow.AddDays(1))}',-1,'{stamp(DateTime.UtcNow.AddDays(1))}',0)"); + var stale = RawDb(ItemsTable(), $"INSERT INTO items (uid, artist, album, added_at, rating, updated_at, deleted) VALUES ('u1','A','Stale title','{stamp(DateTime.UtcNow.AddDays(-5))}',-1,'{stamp(DateTime.UtcNow.AddDays(-5))}',0)"); + + Assert.Equal(new ImportReport(0, 1, 0), _transfer.Import("alice", stale)); + Assert.Equal("Here", store.FindByUid("u1")!.Album); + + Assert.Equal(new ImportReport(0, 1, 0), _transfer.Import("alice", newer)); + Assert.Equal("Newer title", store.FindByUid("u1")!.Album); + } + + [Fact] + public void The_files_own_last_edit_time_is_kept_so_a_newer_backup_imported_later_still_wins() + { + string Backup(string album, double rating, string updated) => JsonSerializer.Serialize(new + { + format = "queueify-export", version = 1, + albums = new[] { new { uid = "u1", artist = "A", album, rating, addedAt = "2026-01-01T00:00:00Z", updatedAt = updated } }, + }); + + _transfer.Import("alice", Encoding.UTF8.GetBytes(Backup("Old title", -1, "2026-01-02T00:00:00Z"))); + var stored = _stores.QueueOf("alice").FindByUid("u1")!; + Assert.Equal(new DateTime(2026, 1, 2, 0, 0, 0, DateTimeKind.Utc), stored.UpdatedAt); + + _transfer.Import("alice", Encoding.UTF8.GetBytes(Backup("New title", 5, "2026-06-01T00:00:00Z"))); + + var after = _stores.QueueOf("alice").FindByUid("u1")!; + Assert.Equal(("New title", 5.0), (after.Album, after.Rating)); + } + + [Fact] + public void An_updated_time_in_the_future_or_without_a_zone_cannot_beat_real_edits() + { + var future = JsonSerializer.Serialize(new { format = "queueify-export", version = 1, albums = new[] { new { uid = "u1", artist = "A", album = "One", addedAt = "2026-01-01T00:00:00Z", updatedAt = "2999-01-01T00:00:00" } } }); + _transfer.Import("alice", Encoding.UTF8.GetBytes(future)); + Assert.True(_stores.QueueOf("alice").FindByUid("u1")!.UpdatedAt <= DateTime.UtcNow); + } + + [Fact] + public void JSON_saved_with_a_byte_order_mark_still_imports() + { + _stores.QueueOf("alice").Insert(Album("A", "One", "u1")); + var json = new byte[] { 0xEF, 0xBB, 0xBF }.Concat(Encoding.UTF8.GetBytes(_transfer.ExportJson("alice"))).ToArray(); + + Assert.Equal(1, _transfer.Import("bob", json).Added); + } + + [Fact] + public void A_table_with_a_generated_column_is_refused_because_reading_it_could_cost_gigabytes() + { + var bytes = RawDb("CREATE TABLE items (id INTEGER PRIMARY KEY, artist TEXT, album TEXT, added_at TEXT, cover_url TEXT AS (hex(zeroblob(400000000))))", + $"INSERT INTO items (artist, album, added_at) VALUES ('A','B','{DateTime.UtcNow:O}')"); + + Assert.Equal(ImportProblem.Invalid, ProblemOf(bytes)); + } + + [Fact] + public void A_virtual_table_named_items_is_refused() + { + var bytes = RawDb("CREATE VIRTUAL TABLE items USING fts5(artist, album, added_at)"); + Assert.Equal(ImportProblem.Invalid, ProblemOf(bytes)); + } + + [Fact] + public void A_large_import_is_one_quick_transaction() + { + var albums = Enumerable.Range(0, 3000).Select(i => new { uid = $"u{i}", artist = "A", album = $"Album {i}", addedAt = "2026-01-01T00:00:00Z" }); + var json = JsonSerializer.Serialize(new { format = "queueify-export", version = 1, albums }); + + var watch = System.Diagnostics.Stopwatch.StartNew(); + var report = _transfer.Import("alice", Encoding.UTF8.GetBytes(json)); + + Assert.Equal(3000, report.Added); + Assert.True(watch.Elapsed < TimeSpan.FromSeconds(8), $"took {watch.Elapsed}"); + } + + [Fact] + public async Task Two_imports_at_once_for_one_user_are_not_allowed_to_collide() + { + var albums = Enumerable.Range(0, 3000).Select(i => new { uid = $"u{i}", artist = "A", album = $"Album {i}", addedAt = "2026-01-01T00:00:00Z" }); + var json = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new { format = "queueify-export", version = 1, albums })); + + var results = await Task.WhenAll(Enumerable.Range(0, 3).Select(_ => Task.Run(() => + { + try { _transfer.Import("alice", json); return (ImportProblem?)null; } + catch (ImportException ex) { return ex.Problem; } + }, TestContext.Current.CancellationToken))); + + Assert.All(results, r => Assert.True(r is null or ImportProblem.Busy)); + Assert.Equal(3000, _stores.QueueOf("alice").LoadAll().Count); + } + + [Fact] + public void An_album_the_user_deleted_here_stays_deleted() + { + var store = _stores.QueueOf("alice"); + var item = Album("A", "One", "u1"); + store.Insert(item); + store.Delete(item); + + var report = _transfer.Import("alice", DesktopDb(Album("A", "One", "u1"))); + + Assert.Equal(0, report.Added); + Assert.Empty(store.LoadAll()); + } + + [Fact] + public void Albums_deleted_in_the_file_are_not_brought_in() + { + var bytes = RawDb(ItemsTable(), $"INSERT INTO items (uid, artist, album, added_at, rating, deleted) VALUES ('u1','A','One','{DateTime.UtcNow:O}',-1,1)"); + Assert.Equal(new ImportReport(0, 0, 1), _transfer.Import("alice", bytes)); + } + + [Fact] + public void A_database_from_before_sync_without_uids_still_imports_and_does_not_duplicate() + { + var bytes = RawDb("CREATE TABLE items (id INTEGER PRIMARY KEY AUTOINCREMENT, artist TEXT NOT NULL, album TEXT NOT NULL, year INTEGER NULL, source TEXT NULL, cover_url TEXT NULL, spotify_id TEXT NULL, tidal_id TEXT NULL, added_at TEXT NOT NULL, listened_at TEXT NULL, rating REAL NOT NULL DEFAULT -1)", + $"INSERT INTO items (artist, album, added_at) VALUES ('Old','Disc','{DateTime.UtcNow:O}')"); + + Assert.Equal(1, _transfer.Import("alice", bytes).Added); + Assert.Equal(new ImportReport(0, 1, 0), _transfer.Import("alice", bytes)); + Assert.Single(_stores.QueueOf("alice").LoadAll()); + } + + [Fact] + public void A_wal_mode_database_copied_without_its_side_files_can_be_read() + { + var path = Path.Combine(_root, "wal.db"); + Directory.CreateDirectory(_root); + using (var db = new SqliteConnection($"Data Source={path};Pooling=False")) + { + db.Open(); + foreach (var sql in new[] { "PRAGMA journal_mode=WAL", ItemsTable(), $"INSERT INTO items (uid, artist, album, added_at, rating, deleted) VALUES ('w1','A','One','{DateTime.UtcNow:O}',-1,0)" }) + { using var c = db.CreateCommand(); c.CommandText = sql; c.ExecuteNonQuery(); } + using var cp = db.CreateCommand(); cp.CommandText = "PRAGMA wal_checkpoint(TRUNCATE)"; cp.ExecuteNonQuery(); + } + SqliteConnection.ClearAllPools(); + + Assert.Equal(1, _transfer.Import("alice", File.ReadAllBytes(path)).Added); + } + + // ── a hostile database ── + + [Fact] + public void Garbage_is_not_a_queue() => Assert.Equal(ImportProblem.Invalid, ProblemOf("MZ\u0090\0 not a database at all"u8.ToArray())); + + [Fact] + public void An_empty_upload_is_not_a_queue() => Assert.Equal(ImportProblem.Invalid, ProblemOf([])); + + [Fact] + public void A_database_cut_short_is_refused_without_a_crash() + { + var bytes = DesktopDb(Album("A", "One", "u1")); + Assert.Equal(ImportProblem.Invalid, ProblemOf(bytes[..20])); + Assert.Equal(ImportProblem.Invalid, ProblemOf(bytes[..(bytes.Length / 2)])); + } + + [Fact] + public void A_database_with_some_other_table_is_not_a_queue() => + Assert.Equal(ImportProblem.Invalid, ProblemOf(RawDb("CREATE TABLE secrets (a TEXT)", "INSERT INTO secrets VALUES ('x')"))); + + [Fact] + public void A_view_named_items_is_refused_because_it_could_run_anything_when_read() => + Assert.Equal(ImportProblem.Invalid, ProblemOf(RawDb("CREATE TABLE other (artist, album, added_at)", "CREATE VIEW items AS SELECT artist, album, added_at FROM other"))); + + [Fact] + public void A_table_without_the_needed_columns_is_refused() => + Assert.Equal(ImportProblem.Invalid, ProblemOf(RawDb("CREATE TABLE items (artist TEXT)"))); + + [Fact] + public void An_enormous_text_is_cut_not_loaded() + { + var bytes = RawDb(ItemsTable(), $"INSERT INTO items (uid, artist, album, added_at, rating, deleted) VALUES ('u1', printf('%.*c', 3000000, 'x'), 'Album','{DateTime.UtcNow:O}',-1,0)"); + + _transfer.Import("alice", bytes); + + Assert.Equal(500, _stores.QueueOf("alice").FindByUid("u1")!.Artist.Length); + } + + [Fact] + public void Odd_types_and_bad_values_skip_that_row_and_keep_the_rest() + { + var now = DateTime.UtcNow.ToString("O"); + var bytes = RawDb(ItemsTable("uid, artist, album, year, added_at, rating, deleted"), + $"INSERT INTO items VALUES ('ok','A','One',1983,'{now}',3,0)", + $"INSERT INTO items VALUES ('blob', x'0102', x'0304', 'abc', '{now}', 'high', 0)", + "INSERT INTO items VALUES ('nodate','A','Two',1990,'not a date',-1,0)", + "INSERT INTO items VALUES (NULL, NULL, NULL, NULL, NULL, NULL, NULL)", + $"INSERT INTO items VALUES ('empty','','',1990,'{now}',-1,0)", + $"INSERT INTO items VALUES ('year','A','Three',99999,'{now}',99,0)"); + + var report = _transfer.Import("alice", bytes); + + var kept = _stores.QueueOf("alice").LoadAll().ToDictionary(i => i.Uid); + Assert.Contains("ok", kept.Keys); + Assert.DoesNotContain("nodate", kept.Keys); + Assert.DoesNotContain("empty", kept.Keys); + Assert.Null(kept["year"].Year); + Assert.Equal(-1, kept["year"].Rating); // out of range: unrated + Assert.Equal(6, report.Added + report.AlreadyHere + report.Skipped); + } + + [Fact] + public void A_trigger_or_a_second_table_in_the_file_does_nothing_because_it_is_only_read() + { + var bytes = RawDb(ItemsTable(), "CREATE TABLE audit (n)", + "CREATE TRIGGER t AFTER INSERT ON items BEGIN INSERT INTO audit VALUES (1); END", + $"INSERT INTO items (uid, artist, album, added_at, rating, deleted) VALUES ('u1','A','One','{DateTime.UtcNow:O}',-1,0)"); + + Assert.Equal(1, _transfer.Import("alice", bytes).Added); + } + + [Fact] + public void More_rows_than_any_queue_is_refused() + { + var bytes = RawDb(ItemsTable("uid, artist, album, added_at, rating, deleted"), + $"WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i+1 FROM n WHERE i < {DataTransfer.MaxRows + 5}) INSERT INTO items SELECT i, 'A', 'B', '{DateTime.UtcNow:O}', -1, 0 FROM n"); + Assert.Equal(ImportProblem.TooLarge, ProblemOf(bytes)); + } + + [Fact] + public void An_upload_over_the_size_limit_is_refused_before_it_is_opened() => + Assert.Equal(ImportProblem.TooLarge, ProblemOf(new byte[DataTransfer.MaxBytes + 1])); + + [Fact] + public void No_temporary_copy_of_the_upload_is_left_behind() + { + var before = Directory.GetFiles(Path.GetTempPath(), "queueify-import-*"); + _transfer.Import("alice", DesktopDb(Album("A", "One", "u1"))); + Assert.Empty(Directory.GetFiles(Path.GetTempPath(), "queueify-import-*").Except(before)); + + Assert.Throws(() => _transfer.Import("alice", "SQLite format 3\0 and then nonsense"u8.ToArray())); + Assert.Empty(Directory.GetFiles(Path.GetTempPath(), "queueify-import-*").Except(before)); + } + + // ── JSON ── + + [Fact] + public void An_exported_queue_imports_into_another_account_with_the_same_uids() + { + var store = _stores.QueueOf("alice"); + var a = Album("Charly García", "Clics modernos", "u1"); + a.ListenedAt = new DateTime(2026, 3, 3, 0, 0, 0, DateTimeKind.Utc); + a.Rating = 5; + store.Insert(a); + store.Insert(Album("Spinetta Jade", "Bajo Belgrano", "u2")); + var json = Encoding.UTF8.GetBytes(_transfer.ExportJson("alice")); + + var report = _transfer.Import("bob", json); + + Assert.Equal(new ImportReport(2, 0, 0), report); + var copy = _stores.QueueOf("bob").FindByUid("u1")!; + Assert.Equal(("Charly García", 5.0), (copy.Artist, copy.Rating)); + Assert.True(copy.IsListened); + Assert.Equal(new ImportReport(0, 2, 0), _transfer.Import("bob", json)); + } + + [Fact] + public void The_export_leaves_out_deleted_albums_and_keeps_no_secrets() + { + var store = _stores.QueueOf("alice"); + var gone = Album("Gone", "Away", "u9"); + store.Insert(gone); + store.Delete(gone); + store.Insert(Album("Here", "Now", "u1")); + _stores.SaveSettings("alice", new AppSettings { SpotifyClientId = "SPOTID", SpotifyClientSecret = "SPOTSECRET" }); + + var json = _transfer.ExportJson("alice"); + + Assert.DoesNotContain("Gone", json); + Assert.DoesNotContain("SPOT", json); + Assert.Contains("\"Here\"", json); + } + + [Theory] + [InlineData("{ not json")] + [InlineData("[]")] + [InlineData("""{"format":"something-else","albums":[]}""")] + [InlineData("""{"format":"queueify-export","version":99,"albums":[]}""")] + [InlineData("""{"format":"queueify-export","version":1,"albums":"x"}""")] + public void JSON_that_is_not_an_export_is_refused(string json) => + Assert.Equal(ImportProblem.Invalid, ProblemOf(Encoding.UTF8.GetBytes(json))); + + [Fact] + public void JSON_rows_are_cut_and_clamped_like_database_rows() + { + var json = JsonSerializer.Serialize(new + { + format = "queueify-export", + version = 1, + albums = new object[] + { + new { uid = "j1", artist = new string('x', 9000), album = "A", year = 1990, rating = 99, addedAt = "2026-01-01T00:00:00Z", deleted = false }, + new { uid = "j2", artist = "", album = "", addedAt = "2026-01-01T00:00:00Z" }, + new { uid = "j3", artist = "Z", album = "A", addedAt = "garbage" }, + }, + }); + + var report = _transfer.Import("alice", Encoding.UTF8.GetBytes(json)); + + Assert.Equal(new ImportReport(1, 0, 2), report); + var item = _stores.QueueOf("alice").FindByUid("j1")!; + Assert.Equal((500, -1.0), (item.Artist.Length, item.Rating)); + } + + // ── CSV ── + + [Fact] + public void The_csv_quotes_what_needs_it_and_defuses_spreadsheet_formulas() + { + var store = _stores.QueueOf("alice"); + store.Insert(Album("Comma, Inc", "He said \"hi\"\nnewline", "u1")); + store.Insert(Album("=HYPERLINK(\"http://evil\")", "+cmd|' /C calc'!A0", "u2")); + + var csv = _transfer.ExportCsv("alice"); + + var lines = csv.Split("\r\n", StringSplitOptions.RemoveEmptyEntries); + Assert.StartsWith("artist,album,year,source,added,listened,rating,spotify_id,tidal_id,uid", lines[0]); + Assert.Contains("\"Comma, Inc\"", csv); + Assert.Contains("\"He said \"\"hi\"\"\nnewline\"", csv); + Assert.DoesNotContain(",=HYPERLINK", csv); + Assert.DoesNotContain("\n=HYPERLINK", csv); + Assert.Contains("'=HYPERLINK", csv); + Assert.Contains("'+cmd", csv); + } + + [Fact] + public void An_empty_queue_exports_just_the_header() + { + Assert.Single(_transfer.ExportCsv("nobody").Split("\r\n", StringSplitOptions.RemoveEmptyEntries)); + Assert.Contains("\"albums\":[]", _transfer.ExportJson("nobody")); + } +} 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); + } +} diff --git a/Queueify.Web.Tests/MusicSettings/PreferencesStoreTests.cs b/Queueify.Web.Tests/MusicSettings/PreferencesStoreTests.cs new file mode 100644 index 0000000..5851bed --- /dev/null +++ b/Queueify.Web.Tests/MusicSettings/PreferencesStoreTests.cs @@ -0,0 +1,95 @@ +using Queueify.Web.Services; +using Queueify.Web.Storage; + +namespace Queueify.Web.Tests.MusicSettings; + +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":""))); + + [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..965f56d --- /dev/null +++ b/Queueify.Web.Tests/Ocr/PhotoEndpointTests.cs @@ -0,0 +1,154 @@ +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; + +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) + { + return Support.TestImages.Png(w, h); + } + + 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..4180590 --- /dev/null +++ b/Queueify.Web.Tests/Ocr/PhotoReaderTests.cs @@ -0,0 +1,152 @@ +using Queueify.Services; +using Queueify.Web.Ocr; + +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) + { + return Support.TestImages.PngStream(w, h); + } + + 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); + } + + private sealed class ExplodingStream : MemoryStream + { + public override int Read(byte[] buffer, int offset, int count) => throw new InvalidOperationException("read before admission"); + public override ValueTask ReadAsync(Memory buffer, CancellationToken ct = default) => throw new InvalidOperationException("read before admission"); + } + + [Fact] + public async Task A_turned_away_photo_is_never_read_so_a_flood_costs_no_memory() + { + var release = new TaskCompletionSource(); + var started = new TaskCompletionSource(); + var reader = Reader(new FakeOcr(async (_, _, _) => { started.TrySetResult(); await release.Task; return new OcrReading([], 1, 1, "x"); })); + var first = reader.ReadAsync("alice", Photo(), "auto", TestContext.Current.CancellationToken); + await started.Task; + + var ex = await Assert.ThrowsAsync(() => reader.ReadAsync("alice", new ExplodingStream(), "auto", TestContext.Current.CancellationToken)); + + Assert.Equal(PhotoProblem.Busy, ex.Problem); + release.SetResult(); + await first; + } + + [Fact] + public async Task An_upload_over_the_size_limit_is_refused_while_reading_it() + { + var reader = Reader(new FakeOcr(), new OcrOptions { MaxBytes = 100 }); + var ex = await Assert.ThrowsAsync(() => reader.ReadAsync("alice", new MemoryStream(new byte[500]), "auto", TestContext.Current.CancellationToken)); + Assert.Equal(PhotoProblem.TooLarge, ex.Problem); + } + + [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..469a3dd --- /dev/null +++ b/Queueify.Web.Tests/Ocr/TesseractTsvTests.cs @@ -0,0 +1,94 @@ +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 A_line_whose_box_is_unreadable_is_dropped_with_its_words_and_does_not_merge_into_the_previous_one() + { + 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, "A") + + "4\t1\t1\t1\t2\t0\tbad\t20\t50\t10\t-1\t\n" + + Row(5, 1, 1, 2, 1, 5, 20, 50, 10, 90, "B"); + + Assert.Equal(["A"], TesseractOcr.ParseTsv(tsv, "x").Lines.Select(l => l.Text)); + } + + [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/Pages/AddPrefillTests.cs b/Queueify.Web.Tests/Pages/AddPrefillTests.cs new file mode 100644 index 0000000..a0c7d5c --- /dev/null +++ b/Queueify.Web.Tests/Pages/AddPrefillTests.cs @@ -0,0 +1,33 @@ +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Queueify.Models; +using Queueify.Services; +using Queueify.Web.Services; +using Queueify.Web.Storage; +using Queueify.Web.Tests.Support; + +namespace Queueify.Web.Tests.Pages; + +public sealed class AddPrefillTests : IClassFixture>, IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "qf-" + Guid.NewGuid().ToString("N")); + private readonly WebComponentTests.FakeCatalogs _catalogs = new(); + private readonly WebApplicationFactory _factory; + + public AddPrefillTests(WebApplicationFactory factory) => + _factory = ScratchHost.On(factory, _root, services => services.AddSingleton(_catalogs)); + + public void Dispose() { Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); try { Directory.Delete(_root, true); } catch (IOException) { } } + + [Fact] + public async Task A_shared_search_link_does_not_call_the_catalogs_while_the_page_is_drawn_on_the_server() + { + new UserStores(_root).SaveSettings("alice", new AppSettings { SpotifyClientId = "id", SpotifyClientSecret = "s", TidalClientId = "id", TidalClientSecret = "s" }); + + var html = await _factory.ClientFor("alice").GetStringAsync("/add?q=soda%20stereo%20signos", TestContext.Current.CancellationToken); + + // The text is in the box for the browser to see; the search itself waits for the live page, so it runs once. + Assert.Contains("soda stereo signos", html); + Assert.Empty(_catalogs.Queries); + } +} diff --git a/Queueify.Web.Tests/Pages/HelpTests.cs b/Queueify.Web.Tests/Pages/HelpTests.cs new file mode 100644 index 0000000..8ba574a --- /dev/null +++ b/Queueify.Web.Tests/Pages/HelpTests.cs @@ -0,0 +1,182 @@ +using System.Security.Claims; +using Bunit; +using Microsoft.Extensions.DependencyInjection; +using Queueify.Services; +using Queueify.Web.Components.Pages; +using Queueify.Web.Components.Shared; +using Queueify.Web.Services; +using Queueify.Web.Storage; + +namespace Queueify.Web.Tests.Pages; + +public sealed class HelpTests : BunitContext +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "qh-" + Guid.NewGuid().ToString("N")); + private readonly PreferencesStore _prefs; + private readonly TourService _tour = new(); + + public HelpTests() + { + var stores = new UserStores(_root); + _prefs = new PreferencesStore(stores); + Services.AddSingleton(_prefs); + Services.AddSingleton(_tour); + var auth = AddAuthorization(); + auth.SetAuthorized("alice@example.test"); + auth.SetClaims(new Claim(ClaimTypes.NameIdentifier, "alice")); + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + try { Directory.Delete(_root, true); } catch (IOException) { } + } + + // ── the Help page ── + + [Fact] + public void Lists_every_shortcut_with_its_keys_and_meaning() + { + var cut = Render(); + + var rows = cut.FindAll("table.shortcuts tbody tr"); + 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")); + } + + [Fact] + public void Carries_the_quick_guide_and_troubleshooting() + { + var text = Render().Markup; + + foreach (var key in new[] { "help.guide", "help.guide.1", "help.guide.2", "help.guide.3", "help.guide.4", "webHelp.guide.5", "webHelp.sync", "webHelp.trouble.1", "webHelp.trouble.2", "webHelp.trouble.3" }) + Assert.Contains(System.Net.WebUtility.HtmlEncode(Loc.T(key)).Replace("'", "'"), text.Replace("'", "'")); + } + + [Fact] + public void Reads_in_Rioplatense_Spanish_when_the_app_is_in_Spanish() + { + using var _ = Loc.Override("es"); + var text = Render().Markup; + + Assert.Contains("Atajos de teclado", text); + Assert.DoesNotContain("Keyboard shortcuts", text); + } + + [Fact] + public void Replay_asks_the_tour_to_start_again() + { + var asked = 0; + _tour.Replayed += () => asked++; + + Render().Find("button.replay").Click(); + + Assert.Equal(1, asked); + } + + [Fact] + public void The_help_page_is_open_to_visitors_who_are_not_signed_in() + { + var attributes = typeof(Help).GetCustomAttributes(typeof(Microsoft.AspNetCore.Authorization.AuthorizeAttribute), true); + Assert.Empty(attributes); + } + + // ── the quick tour ── + + private IRenderedComponent Tour() => Render(); + + [Fact] + public void Shows_itself_on_the_first_visit_at_step_one() + { + var cut = Tour(); + + var dialog = cut.Find("[role=dialog]"); + Assert.Contains(Loc.T("webHelp.tour.1.title"), dialog.TextContent); + Assert.Contains(Loc.T("webHelp.tour.1"), dialog.TextContent); + Assert.Contains(Loc.F("tour.counter", Loc.T("webHelp.tour.title"), 1, 4), dialog.TextContent); + } + + [Fact] + public void Next_goes_through_every_step_and_done_remembers_it_was_seen() + { + var cut = Tour(); + for (var step = 2; step <= 4; step++) + { + cut.Find("button.next").Click(); + Assert.Contains(Loc.T($"webHelp.tour.{step}.title"), cut.Find("[role=dialog]").TextContent); + } + Assert.Equal(Loc.T("tour.done"), cut.Find("button.next").TextContent.Trim()); + + cut.Find("button.next").Click(); + + Assert.Empty(cut.FindAll("[role=dialog]")); + Assert.True(_prefs.Load("alice").TourSeen); + } + + [Fact] + public void Skip_closes_it_and_it_stays_closed_next_time() + { + var cut = Tour(); + cut.Find("button.skip").Click(); + + Assert.Empty(cut.FindAll("[role=dialog]")); + Assert.True(_prefs.Load("alice").TourSeen); + Assert.Empty(Render().FindAll("[role=dialog]")); + } + + [Fact] + public void Escape_closes_it() + { + var cut = Tour(); + cut.Find("[role=dialog]").KeyDown(new Microsoft.AspNetCore.Components.Web.KeyboardEventArgs { Key = "Escape" }); + Assert.Empty(cut.FindAll("[role=dialog]")); + } + + [Fact] + public void Replay_brings_it_back_from_step_one_even_after_it_was_seen() + { + _prefs.Save("alice", Preferences.Default with { TourSeen = true }); + var cut = Tour(); + Assert.Empty(cut.FindAll("[role=dialog]")); + + cut.InvokeAsync(_tour.Replay); + + Assert.Contains(Loc.T("webHelp.tour.1.title"), cut.Find("[role=dialog]").TextContent); + } + + [Fact] + public void Only_one_mounted_tour_shows_so_two_never_overlap() + { + var first = Tour(); + var second = Tour(); + + Assert.Single(first.FindAll("[role=dialog]")); + Assert.Empty(second.FindAll("[role=dialog]")); + + first.Dispose(); + _tour.Replay(); // a new owner can take over once the first is gone + Assert.NotNull(Tour()); + } + + [Fact] + public void A_visitor_who_is_not_signed_in_gets_no_tour() + { + using var anonymous = new BunitContext(); + anonymous.Services.AddSingleton(_prefs); + anonymous.Services.AddSingleton(new TourService()); + anonymous.AddAuthorization(); + + Assert.Empty(anonymous.Render().FindAll("[role=dialog]")); + } + + [Fact] + public void The_dialog_is_named_and_the_buttons_are_real_buttons() + { + var cut = Tour(); + Assert.False(string.IsNullOrWhiteSpace(cut.Find("[role=dialog]").GetAttribute("aria-label"))); + Assert.Equal("button", cut.Find("button.next").GetAttribute("type")); + Assert.Equal(Loc.T("tour.skip"), cut.Find("button.skip").TextContent.Trim()); + } +} diff --git a/Queueify.Web.Tests/Pages/PhotoPageTests.cs b/Queueify.Web.Tests/Pages/PhotoPageTests.cs new file mode 100644 index 0000000..c4fdc88 --- /dev/null +++ b/Queueify.Web.Tests/Pages/PhotoPageTests.cs @@ -0,0 +1,266 @@ +using System.Security.Claims; +using Bunit; +using Microsoft.AspNetCore.Components; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.JSInterop; +using Queueify.Services; +using Queueify.Web.Components.Pages; +using Queueify.Web.Ocr; +using Queueify.Web.Services; +using Queueify.Web.Storage; + +namespace Queueify.Web.Tests.Pages; + +public sealed class PhotoPageTests : BunitContext +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "qb-" + Guid.NewGuid().ToString("N")); + private readonly BunitJSModuleInterop _module; + private DotNetObjectReference? _page; + + public PhotoPageTests() + { + var stores = new UserStores(_root); + Services.AddSingleton(stores); + Services.AddSingleton(new PreferencesStore(stores)); + Services.AddSingleton(new OcrOptions { MaxBytes = 5 * 1024 * 1024 }); + var auth = AddAuthorization(); + auth.SetAuthorized("alice@example.test"); + auth.SetClaims(new Claim(ClaimTypes.NameIdentifier, "alice")); + + _module = JSInterop.SetupModule("./js/queueify-upload.js"); + var watcher = _module.SetupModule("watch", _ => true); + watcher.SetupVoid("dispose"); + _module.SetupVoid("release", _ => true).SetVoidResult(); + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + try { Directory.Delete(_root, true); } catch (IOException) { } + } + + private IRenderedComponent Open() + { + var cut = Render(); + var watch = Assert.Single(_module.Invocations["watch"]); + _page = (DotNetObjectReference)watch.Arguments[2]!; + return cut; + } + + private async Task Choose(IRenderedComponent cut, string reply, int status = 200, long size = 1000) + { + _module.Setup("send", _ => true).SetResult(new UploadResult(status, reply)); + await cut.InvokeAsync(() => _page!.Value.OnFileChosen("1", "page.jpg", size, "blob:preview")); + } + + private const string Page = """ + {"width":1000,"height":500,"lines":[ + {"text":"CHARLY GARCÍA","x":100,"y":50,"width":400,"height":50}, + {"text":"Clics modernos (Interdisc, 1983)","x":100,"y":150,"width":600,"height":40}]} + """; + + [Fact] + public void Offers_a_picker_a_camera_and_a_language_and_says_nothing_is_kept() + { + var cut = Open(); + + Assert.Equal("image/*", cut.Find("#photo-choose").GetAttribute("accept")); + Assert.Equal("environment", cut.Find("#photo-take").GetAttribute("capture")); + Assert.Equal(["auto", "es", "en"], cut.FindAll("#photo-lang option").Select(o => o.GetAttribute("value")!)); + Assert.Contains(Loc.T("webPhoto.privacy"), cut.Markup); + Assert.Equal("auto", cut.Find("#photo-lang").GetAttribute("value")); + } + + [Fact] + public void The_language_saved_in_settings_is_the_one_shown() + { + new PreferencesStore(new UserStores(_root)).Save("alice", Preferences.Default with { OcrLanguage = "es" }); + Assert.Equal("es", Open().Find("#photo-lang").GetAttribute("value")); + } + + [Fact] + public void Choosing_another_language_remembers_it() + { + var cut = Open(); + cut.Find("#photo-lang").Change("en"); + Assert.Equal("en", new PreferencesStore(new UserStores(_root)).Load("alice").OcrLanguage); + } + + [Fact] + public async Task A_read_photo_shows_its_lines_with_boxes_over_the_picture() + { + var cut = Open(); + await Choose(cut, Page); + + Assert.Equal("blob:preview", cut.Find(".sheet img").GetAttribute("src")); + Assert.Equal(2, cut.FindAll(".box").Count); + Assert.Contains("left:10%;top:10%;width:40%;height:10%", cut.FindAll(".box")[0].GetAttribute("style")); + Assert.Equal(["CHARLY GARCÍA", "Clics modernos (Interdisc, 1983)"], cut.FindAll(".line").Select(l => l.TextContent.Trim())); + var request = _module.Invocations["send"].Single(); + Assert.Equal("/api/photo?lang=auto", request.Arguments[1]); + } + + [Fact] + public async Task Tapping_the_artist_then_the_album_builds_a_link_to_the_add_page_search() + { + var cut = Open(); + await Choose(cut, Page); + + cut.FindAll(".line")[0].Click(); + cut.FindAll(".line")[1].Click(); + + var go = cut.Find("a.go"); + Assert.Equal("/add?q=" + Uri.EscapeDataString("Charly García Clics modernos 1983"), go.GetAttribute("href")); + Assert.Equal("true", cut.FindAll(".line")[0].GetAttribute("aria-pressed")); + } + + [Fact] + public async Task Tapping_a_picked_line_again_unpicks_it_and_clearing_removes_the_link() + { + var cut = Open(); + await Choose(cut, Page); + + cut.FindAll(".line")[0].Click(); + cut.FindAll(".line")[0].Click(); + Assert.Empty(cut.FindAll("a.go")); + + cut.FindAll(".line")[1].Click(); + cut.Find(".plain").Click(); + Assert.Empty(cut.FindAll("a.go")); + } + + [Fact] + public async Task The_box_on_the_photo_picks_the_same_line_as_the_list() + { + var cut = Open(); + await Choose(cut, Page); + + cut.FindAll(".box")[0].Click(); + + Assert.Equal("true", cut.FindAll(".line")[0].GetAttribute("aria-pressed")); + } + + [Fact] + public async Task A_line_with_markup_in_it_is_shown_as_text_and_encoded_in_the_link() + { + var cut = Open(); + await Choose(cut, """{"width":10,"height":10,"lines":[{"text":" & \"q\"","x":0,"y":0,"width":5,"height":5}]}"""); + + Assert.Empty(cut.FindAll("img[onerror]")); + cut.Find(".line").Click(); + Assert.DoesNotContain("502 Bad Gateway", status: 502); + Assert.NotEmpty(cut.FindAll(".error")); + } + + [Fact] + public async Task A_file_over_the_limit_is_not_even_sent() + { + var cut = Open(); + await Choose(cut, Page, size: 50L * 1024 * 1024); + + Assert.Empty(_module.Invocations["send"]); + Assert.Equal(Loc.F("webPhoto.err.tooLarge", 5), cut.Find(".error").TextContent.Trim()); + } + + [Fact] + public async Task A_second_photo_dropped_while_one_is_being_read_is_let_go_and_cannot_mix_with_the_first() + { + var cut = Open(); + var send = _module.Setup("send", _ => true); + var first = cut.InvokeAsync(() => _page!.Value.OnFileChosen("1", "a.jpg", 10, "blob:a")); + cut.WaitForAssertion(() => Assert.Contains(Loc.T("webPhoto.reading"), cut.Markup)); + + await cut.InvokeAsync(() => _page!.Value.OnFileChosen("2", "b.jpg", 10, "blob:b")); + send.SetResult(new UploadResult(200, Page)); + await first; + + Assert.Single(_module.Invocations["send"]); + Assert.Equal("blob:a", cut.Find(".sheet img").GetAttribute("src")); + Assert.Contains(_module.Invocations["release"], i => i.Arguments[0]!.ToString() == "2"); + } + + [Fact] + public async Task A_line_with_no_text_left_after_cleaning_is_no_search_so_no_link_is_offered() + { + var cut = Open(); + await Choose(cut, """{"width":10,"height":10,"lines":[{"text":"•","x":0,"y":0,"width":5,"height":5}]}"""); + + cut.Find(".line").Click(); + + Assert.Empty(cut.FindAll("a.go")); + } + + [Fact] + public async Task The_number_of_lines_found_is_announced_in_the_live_region() + { + var cut = Open(); + await Choose(cut, Page); + + Assert.Contains(Loc.F("webPhoto.found", 2), cut.Find("[role=status]").TextContent); + } + + [Fact] + public async Task An_unknown_failure_says_to_try_again_not_to_call_the_administrator() + { + var cut = Open(); + await Choose(cut, "oops", status: 500); + Assert.Equal(Loc.T("webPhoto.err.unknown"), cut.Find(".error").TextContent.Trim()); + } + + [Fact] + public async Task The_pickers_are_disabled_while_a_photo_is_being_read() + { + var cut = Open(); + var send = _module.Setup("send", _ => true); // no answer yet: the read is "in flight" + var running = cut.InvokeAsync(() => _page!.Value.OnFileChosen("1", "p.jpg", 10, "blob:x")); + + cut.WaitForAssertion(() => Assert.NotNull(cut.Find("#photo-choose").GetAttribute("disabled"))); + Assert.Contains(Loc.T("webPhoto.reading"), cut.Find("[role=status]").TextContent); + + send.SetResult(new UploadResult(200, Page)); + await running; + Assert.Null(cut.Find("#photo-choose").GetAttribute("disabled")); + } +} diff --git a/Queueify.Web.Tests/Pages/SettingsDataTests.cs b/Queueify.Web.Tests/Pages/SettingsDataTests.cs new file mode 100644 index 0000000..4427c7c --- /dev/null +++ b/Queueify.Web.Tests/Pages/SettingsDataTests.cs @@ -0,0 +1,87 @@ +using Bunit; +using Microsoft.JSInterop; +using Queueify.Services; +using Queueify.Web.Components.Shared; +using Queueify.Web.Services; + +namespace Queueify.Web.Tests.Pages; + +public sealed class SettingsDataTests : BunitContext +{ + private readonly BunitJSModuleInterop _module; + + public SettingsDataTests() + { + _module = JSInterop.SetupModule("./js/queueify-upload.js"); + _module.SetupModule("watch", _ => true).SetupVoid("dispose"); + _module.SetupVoid("release", _ => true).SetVoidResult(); + } + + private (IRenderedComponent Cut, DotNetObjectReference Page) Open() + { + var cut = Render(); + var watch = Assert.Single(_module.Invocations["watch"]); + return (cut, (DotNetObjectReference)watch.Arguments[2]!); + } + + private async Task ImportAs(IRenderedComponent cut, DotNetObjectReference page, UploadResult answer, long size = 100) + { + _module.Setup("send", _ => true).SetResult(answer); + await cut.InvokeAsync(() => page.Value.OnFileChosen("1", "queueify.db", size, null)); + cut.Find("button.import").Click(); + } + + [Fact] + public void Offers_json_and_csv_downloads_and_an_import_that_waits_for_a_file() + { + var (cut, _) = Open(); + + Assert.Equal("/api/export.json", cut.Find("a.json").GetAttribute("href")); + Assert.Equal("/api/export.csv", cut.Find("a.csv").GetAttribute("href")); + Assert.NotNull(cut.Find("button.import").GetAttribute("disabled")); + } + + [Fact] + public async Task Choosing_a_file_shows_its_name_and_sends_nothing_until_import_is_pressed() + { + var (cut, page) = Open(); + await cut.InvokeAsync(() => page.Value.OnFileChosen("1", "queueify.db", 100, null)); + + Assert.Contains("queueify.db", cut.Find(".name").TextContent); + Assert.Null(cut.Find("button.import").GetAttribute("disabled")); + Assert.Empty(_module.Invocations["send"]); + } + + [Fact] + public async Task Import_sends_the_file_as_binary_to_the_import_endpoint_and_reports_the_counts() + { + var (cut, page) = Open(); + await ImportAs(cut, page, new UploadResult(200, """{"added":3,"alreadyHere":2,"skipped":1}""")); + + var call = Assert.Single(_module.Invocations["send"]); + Assert.Equal(["1", "/api/import", "application/octet-stream"], call.Arguments.Select(a => a?.ToString())); + cut.WaitForAssertion(() => Assert.Equal("✓ " + Loc.F("webData.import.done", 3, 2, 1), cut.Find("[data-status=import]").TextContent)); + } + + [Theory] + [InlineData(422, """{"error":"invalid"}""", "webData.import.invalid")] + [InlineData(500, "boom", "webData.import.failed")] + [InlineData(0, "", "webData.import.failed")] + public async Task A_refused_file_says_what_to_do_next(int status, string body, string key) + { + var (cut, page) = Open(); + await ImportAs(cut, page, new UploadResult(status, body)); + + cut.WaitForAssertion(() => Assert.Contains(Loc.T(key), cut.Find("[data-status=import]").TextContent)); + Assert.Contains("error", cut.Find("[data-status=import]").ClassList); + } + + [Fact] + public async Task A_file_over_the_limit_is_flagged_at_once() + { + var (cut, page) = Open(); + await cut.InvokeAsync(() => page.Value.OnFileChosen("1", "huge.db", 500L * 1024 * 1024, null)); + + Assert.Contains(Loc.F("webData.import.too_big", 25), cut.Find("[data-status=import]").TextContent); + } +} diff --git a/Queueify.Web.Tests/Pages/SettingsPageTests.cs b/Queueify.Web.Tests/Pages/SettingsPageTests.cs new file mode 100644 index 0000000..0a4dd5d --- /dev/null +++ b/Queueify.Web.Tests/Pages/SettingsPageTests.cs @@ -0,0 +1,328 @@ +using System.Net; +using System.Security.Claims; +using System.Text; +using Bunit; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.Extensions.DependencyInjection; +using Queueify.Models; +using Queueify.Services; +using Queueify.Web.Components.Pages; +using Queueify.Web.Ocr; +using Queueify.Web.Services; +using Queueify.Web.Storage; + +namespace Queueify.Web.Tests.Pages; + +public sealed class SettingsPageTests : BunitContext +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "qz-" + Guid.NewGuid().ToString("N")); + private readonly UserStores _stores; + private readonly PreferencesStore _prefs; + private HttpStatusCode _token = HttpStatusCode.OK; + + private sealed class FakeApi(Func token) : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + var isToken = request.RequestUri!.ToString().Contains("token"); + var status = isToken ? token() : HttpStatusCode.OK; + var body = isToken && status == HttpStatusCode.OK ? """{"access_token":"t","expires_in":3600}""" : """{"albums":{"items":[]}}"""; + return Task.FromResult(new HttpResponseMessage(status) { Content = new StringContent(body, Encoding.UTF8, "application/json") }); + } + } + + public SettingsPageTests() + { + _stores = new UserStores(_root, new EphemeralDataProtectionProvider().CreateProtector("t")); + _prefs = new PreferencesStore(_stores); + Services.AddSingleton(_stores); + Services.AddSingleton(_prefs); + Services.AddSingleton(new Queueify.Web.Sync.SyncEngine(_stores, TimeProvider.System)); + Services.AddSingleton(new SettingsService(_stores, () => new HttpClient(new FakeApi(() => _token)))); + Services.AddSingleton(new Queueify.Web.Services.DataTransfer(_stores)); + Services.AddSingleton(new OcrOptions()); + var auth = AddAuthorization(); + auth.SetAuthorized("alice@example.test"); + auth.SetClaims(new Claim(ClaimTypes.NameIdentifier, "alice")); + var module = JSInterop.SetupModule("./js/queueify-upload.js"); + module.SetupModule("watch", _ => true).SetupVoid("dispose"); + module.SetupVoid("release", _ => true); + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + try { Directory.Delete(_root, true); } catch (IOException) { } + } + + private void Configure(string spotifySecret = "SPOTSECRET", string tidalSecret = "TIDALSECRET") => + _stores.SaveSettings("alice", new AppSettings { SpotifyClientId = "spot-id", SpotifyClientSecret = spotifySecret, TidalClientId = "tidal-id", TidalClientSecret = tidalSecret }); + + // ── secrets stay on the server ── + + [Fact] + public void Says_whether_each_service_is_configured_and_never_shows_a_saved_secret() + { + Configure(); + var cut = Render(); + + Assert.DoesNotContain("SPOTSECRET", cut.Markup); + Assert.DoesNotContain("TIDALSECRET", cut.Markup); + Assert.Contains(Loc.T("webSettings.keys.on"), cut.Find("[data-service=spotify] .state").TextContent); + Assert.Equal("spot-id", cut.Find("#spotify-id").GetAttribute("value")); // an id is not a secret + Assert.Equal(Loc.T("webSettings.secret.saved"), cut.Find("#spotify-secret").GetAttribute("placeholder")); + } + + [Fact] + public void A_service_without_keys_says_so() + { + var cut = Render(); + Assert.Contains(Loc.T("webSettings.keys.off"), cut.Find("[data-service=tidal] .state").TextContent); + Assert.Equal(Loc.T("webSettings.secret.empty"), cut.Find("#tidal-secret").GetAttribute("placeholder")); + } + + [Fact] + public void The_secret_fields_are_password_fields_that_start_empty_and_are_not_remembered_by_the_browser() + { + Configure(); + var field = Render().Find("#spotify-secret"); + + Assert.Equal("password", field.GetAttribute("type")); + Assert.Equal("new-password", field.GetAttribute("autocomplete")); + Assert.True(string.IsNullOrEmpty(field.GetAttribute("value"))); + } + + [Fact] + public void A_typed_secret_is_saved_and_the_field_is_emptied_afterwards() + { + var cut = Render(); + cut.Find("#spotify-id").Change("new-id"); + cut.Find("#spotify-secret").Input("brand-new-secret"); + + cut.Find("button.save-music").Click(); + + var stored = _stores.LoadSettings("alice"); + Assert.Equal(("new-id", "brand-new-secret"), (stored.SpotifyClientId, stored.SpotifyClientSecret)); + Assert.DoesNotContain("brand-new-secret", cut.Markup); + Assert.Contains(Loc.T("webSettings.saved"), cut.Find("[data-status=music]").TextContent); + Assert.Contains(Loc.T("webSettings.keys.on"), cut.Find("[data-service=spotify] .state").TextContent); + } + + [Fact] + public void Saving_without_touching_anything_says_nothing_changed_and_keeps_the_secrets() + { + Configure(); + var cut = Render(); + + cut.Find("button.save-music").Click(); + + Assert.Contains(Loc.T("webSettings.unchanged"), cut.Find("[data-status=music]").TextContent); + Assert.Equal("SPOTSECRET", _stores.LoadSettings("alice").SpotifyClientSecret); + } + + [Fact] + public void Only_the_changed_field_counts_as_an_edit() + { + Configure(); + var cut = Render(); + _stores.SaveSettings("alice", _stores.LoadSettings("alice").Also(s => s.CountryCode = "ES")); // a PC synced a new country meanwhile + + cut.Find("#preferred").Change("Spotify"); + cut.Find("button.save-music").Click(); + + var stored = _stores.LoadSettings("alice"); + Assert.Equal(("Spotify", "ES"), (stored.PreferredService, stored.CountryCode)); + } + + [Fact] + public void The_country_list_comes_from_Core_and_shows_the_current_one() + { + _stores.SaveSettings("alice", new AppSettings { CountryCode = "ES" }); + var select = Render().Find("#country"); + + Assert.Equal("ES", select.GetAttribute("value")); + Assert.Equal(Countries.Codes.Count, select.QuerySelectorAll("option").Length); + } + + [Fact] + public void Removing_a_services_keys_asks_nothing_twice_and_leaves_the_other() + { + Configure(); + var cut = Render(); + + cut.Find("button.remove-spotify").Click(); + + var stored = _stores.LoadSettings("alice"); + Assert.False(stored.SpotifyConfigured); + Assert.True(stored.TidalConfigured); + Assert.Contains(Loc.T("webSettings.keys.off"), cut.Find("[data-service=spotify] .state").TextContent); + } + + [Fact] + public void Removing_one_services_keys_says_so_and_keeps_what_was_typed_for_the_other() + { + Configure(); + var cut = Render(); + cut.Find("#tidal-id").Change("typed-for-tidal"); + + cut.Find("button.remove-spotify").Click(); + + Assert.Contains(Loc.F("webSettings.removed", "Spotify"), cut.Find("[data-status=spotify]").TextContent); + Assert.Equal("typed-for-tidal", cut.Find("#tidal-id").GetAttribute("value")); + } + + [Fact] + public void Changing_a_preference_says_it_was_saved() + { + var cut = Render(); + cut.Find("#theme").Change("dark"); + Assert.Contains(Loc.T("webSettings.saved"), cut.Find("[data-status=prefs]").TextContent); + cut.Find("#ocr").Change("en"); + Assert.Contains(Loc.T("webSettings.saved"), cut.Find("[data-status=prefs-ocr]").TextContent); + } + + [Fact] + public void A_delete_that_hits_a_file_in_use_is_a_message_not_a_dead_page() + { + _stores.QueueOf("alice").Insert(new BacklogItem { Artist = "A", Album = "One" }); + var cut = Render(); + cut.Find("#sure").Change(true); + + using (new FileStream(_stores.FileOf("alice", "queueify.db"), FileMode.Open, FileAccess.ReadWrite, FileShare.None)) + cut.Find("button.delete").Click(); + + Assert.Contains("error", cut.Find("[data-status=delete]").ClassList); + } + + // ── testing the keys ── + + [Fact] + public async Task The_test_button_reports_that_working_keys_work() + { + Configure(); + var cut = Render(); + + cut.Find("button.test-spotify").Click(); + await cut.WaitForAssertionAsync(() => Assert.Contains(Loc.F("webSettings.test.ok", "Spotify"), cut.Find("[data-status=spotify]").TextContent)); + } + + [Fact] + public async Task The_test_button_passes_on_the_catalogs_actionable_text_without_the_secret() + { + Configure(spotifySecret: "SPOTSECRET"); + _token = HttpStatusCode.Unauthorized; + var cut = Render(); + + cut.Find("button.test-spotify").Click(); + + await cut.WaitForAssertionAsync(() => Assert.Contains(Loc.F("catalog.rejected", "Spotify"), cut.Find("[data-status=spotify]").TextContent)); + Assert.DoesNotContain("SPOTSECRET", cut.Markup); + } + + [Fact] + public async Task Testing_with_no_saved_keys_says_to_save_them_first() + { + var cut = Render(); + cut.Find("button.test-tidal").Click(); + await cut.WaitForAssertionAsync(() => Assert.Contains(Loc.F("webSettings.test.missing", "Tidal"), cut.Find("[data-status=tidal]").TextContent)); + } + + [Fact] + public void Unsaved_typing_is_not_tested_because_the_test_uses_what_is_saved() + { + var cut = Render(); + cut.Find("#tidal-id").Change("typed-not-saved"); + cut.Find("#tidal-secret").Input("typed-not-saved"); + + cut.Find("button.test-tidal").Click(); + + Assert.False(_stores.LoadSettings("alice").TidalConfigured); + } + + // ── appearance, language, OCR ── + + [Fact] + public void Theme_language_and_reading_language_are_saved_on_change() + { + var cut = Render(); + + cut.Find("#theme").Change("dark"); + cut.Find("#ocr").Change("es"); + + var p = _prefs.Load("alice"); + Assert.Equal(("dark", "system", "es"), (p.Theme, p.Language, p.OcrLanguage)); + } + + [Fact] + public void Changing_the_language_reloads_so_the_whole_page_changes_language() + { + var cut = Render(); + var nav = Services.GetRequiredService() as Bunit.TestDoubles.BunitNavigationManager; + + cut.Find("#language").Change("es"); + + Assert.Equal("es", _prefs.Load("alice").Language); + Assert.Contains(nav!.History, h => h.Options.ForceLoad); + } + + [Fact] + public void An_unknown_theme_posted_by_a_tampered_page_is_ignored() + { + var cut = Render(); + cut.Find("#theme").Change(""); + Assert.Equal("system", _prefs.Load("alice").Theme); + } + + // ── links, sign-out, delete ── + + [Fact] + public void Links_to_connecting_a_pc_and_to_the_account_page() + { + var cut = Render(); + Assert.Equal("connect", cut.Find("a.connect").GetAttribute("href")); + Assert.Equal("Account/Manage", cut.Find("a.account").GetAttribute("href")); + Assert.Contains(Loc.T("webSettings.signout.text"), cut.Markup); + } + + [Fact] + public void Deleting_data_needs_the_box_ticked_and_then_removes_only_this_users_data() + { + Configure(); + _stores.QueueOf("alice").Insert(new BacklogItem { Artist = "A", Album = "One" }); + _stores.QueueOf("bob").Insert(new BacklogItem { Artist = "B", Album = "Two" }); + var cut = Render(); + Assert.NotNull(cut.Find("button.delete").GetAttribute("disabled")); + + cut.Find("#sure").Change(true); + cut.Find("button.delete").Click(); + + Assert.Empty(_stores.QueueOf("alice").LoadAll()); + Assert.False(_stores.LoadSettings("alice").SpotifyConfigured); + Assert.Single(_stores.QueueOf("bob").LoadAll()); + Assert.Contains(Loc.T("webSettings.delete.done"), cut.Markup); + } + + [Fact] + public void Reads_in_Spanish_when_the_app_is_in_Spanish() + { + using var _ = Loc.Override("es"); + var cut = Render(); + Assert.Contains("Configuración", cut.Find("h1").TextContent); + Assert.Contains(Loc.T("webSettings.delete.title"), cut.Markup); + Assert.DoesNotContain("Delete my data", cut.Markup); + } + + [Fact] + public void Every_control_has_a_label() + { + var cut = Render(); + foreach (var field in cut.FindAll("input:not([type=file]):not([type=checkbox]), select")) + Assert.NotEmpty(cut.FindAll($"label[for={field.Id}]")); + Assert.NotEmpty(cut.FindAll("label[for=sure]")); + } +} + +internal static class SettingsTestExtensions +{ + public static T Also(this T value, Action change) { change(value); return value; } +} diff --git a/Queueify.Web.Tests/PreferencesNeededTests.cs b/Queueify.Web.Tests/PreferencesNeededTests.cs new file mode 100644 index 0000000..2632137 --- /dev/null +++ b/Queueify.Web.Tests/PreferencesNeededTests.cs @@ -0,0 +1,30 @@ +using Queueify.Web.Services; + +namespace Queueify.Web.Tests; + +/// Only requests that draw a page need the signed-in user's language and theme; files and framework scripts do not. +public class PreferencesNeededTests +{ + [Theory] + [InlineData("/")] + [InlineData("/add")] + [InlineData("/Account/Login")] + [InlineData("/Account/Manage/ChangePassword")] + [InlineData("/not-found")] + [InlineData("/_blazor/negotiate")] + [InlineData("/prefs")] + public void Pages_and_forms_need_them(string path) => Assert.True(QueueifyUi.NeedsPreferences(path)); + + [Theory] + [InlineData("/queueify.css")] + [InlineData("/queueify.abc123.js")] + [InlineData("/js/queueify-upload.js")] + [InlineData("/icons/icon-512.png")] + [InlineData("/manifest.webmanifest")] + [InlineData("/sw.js")] + [InlineData("/favicon.png")] + [InlineData("/_framework/blazor.web.js")] + [InlineData("/_content/Microsoft.FluentUI.AspNetCore.Components/x.bundle.scp.css")] + [InlineData("/Components/Layout/ReconnectModal.razor.js")] + public void Static_files_do_not(string path) => Assert.False(QueueifyUi.NeedsPreferences(path)); +} diff --git a/Queueify.Web.Tests/PrefsTests.cs b/Queueify.Web.Tests/PrefsTests.cs new file mode 100644 index 0000000..dd81368 --- /dev/null +++ b/Queueify.Web.Tests/PrefsTests.cs @@ -0,0 +1,49 @@ +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 => 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 new file mode 100644 index 0000000..adf54bb --- /dev/null +++ b/Queueify.Web/Components/Layout/MainLayout.razor @@ -0,0 +1,67 @@ +@inherits LayoutComponentBase + +@Loc.T("web.nav.skip") + + + +
+ +
+ @* Account pages other than Manage (which has its own card) are narrow forms: give them a card too. *@ +
+ @if (PlainAccountPage) {
@Body
} else { @Body } +
+
+
+ + +
+ +
+
+
+ +

Queueify

+
+
@Body
+
+
+
+
+ +
+ @Loc.T("web.error.unhandled") + @Loc.T("web.error.reload") + +
+ +@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!; + + // Fluent components keep their own theme tokens; give them the same mode and violet as the rest of the page. + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (!firstRender) return; + try + { + var chosen = await JS.InvokeAsync("queueify.theme"); + var mode = chosen switch { "light" => ThemeMode.Light, "dark" => ThemeMode.Dark, _ => ThemeMode.System }; + await Themes.SetThemeAsync(new ThemeSettings { Color = "#6544E6", Mode = mode, IsExact = true }); + } + catch (JSException) { } + catch (JSDisconnectedException) { } + catch (InvalidOperationException) { } + } +} + diff --git a/Queueify.Web/Components/Layout/NavMenu.razor b/Queueify.Web/Components/Layout/NavMenu.razor new file mode 100644 index 0000000..8c0c711 --- /dev/null +++ b/Queueify.Web/Components/Layout/NavMenu.razor @@ -0,0 +1,97 @@ +@implements IDisposable +@inject UserQueue Queue +@inject NavigationManager Nav + +@* One list of every page, drawn twice: the left rail on desktops, the bottom bar (with a More sheet) on phones. *@ + + + + +@code { + private sealed record Page(string Href, string Icon, string Label, string Tip, NavLinkMatch Match = NavLinkMatch.Prefix, int Count = 0, string? CountKey = null, string? Data = null); + + private Page[] Pages => [ + new("", "queue", Loc.T("nav.queue"), Loc.T("nav.queue.tip"), NavLinkMatch.All, Queue.Pending, "badge.waiting"), + new("add", "add", Loc.T("web.nav.add"), Loc.T("web.nav.add.tip")), + new("listened", "listened", Loc.T("nav.listened"), Loc.T("nav.listened.tip"), Count: Queue.Heard, CountKey: "badge.listened"), + new("photo", "photo", Loc.T("nav.photo"), Loc.T("nav.photo.tip")), + new("help", "help", Loc.T("nav.help"), Loc.T("nav.help.tip"), Data: "help"), + new("settings", "settings", Loc.T("nav.settings"), Loc.T("nav.settings.tip")), + ]; + + private Page Connect => new("connect", "connect", Loc.T("web.nav.connect"), Loc.T("web.nav.connect.tip")); + + private string ReturnUrl => Nav.ToBaseRelativePath(Nav.Uri); + + protected override async Task OnInitializedAsync() + { + Queue.Changed += OnChanged; // subscribed before the await, so a disposal during the load cannot leave it attached + Nav.LocationChanged += OnLocation; + await Queue.LoadAsync(); + } + + private void OnChanged() => Redraw(); + + private void OnLocation(object? sender, LocationChangedEventArgs e) => Redraw(); + + private async void Redraw() + { + try { await InvokeAsync(StateHasChanged); } + catch (ObjectDisposedException) { } + catch (Exception ex) { await DispatchExceptionAsync(ex); } + } + + public void Dispose() + { + 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/PrefsMenu.razor b/Queueify.Web/Components/Layout/PrefsMenu.razor new file mode 100644 index 0000000..e6eed18 --- /dev/null +++ b/Queueify.Web/Components/Layout/PrefsMenu.razor @@ -0,0 +1,41 @@ +@inject IJSRuntime JS +@* 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; } = ""; + + private string _theme = "system"; + + private string Pressed(string theme) => _theme == theme ? "true" : "false"; + + // The theme lives in a cookie the page already turned into an attribute; read it from there. + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (!firstRender) return; + try + { + _theme = await JS.InvokeAsync("queueify.theme") ?? "system"; + StateHasChanged(); + } + catch (JSException) { } + catch (JSDisconnectedException) { } + catch (InvalidOperationException) { } + } +} diff --git a/Queueify.Web/Components/Layout/ReconnectModal.razor b/Queueify.Web/Components/Layout/ReconnectModal.razor new file mode 100644 index 0000000..e118b6f --- /dev/null +++ b/Queueify.Web/Components/Layout/ReconnectModal.razor @@ -0,0 +1,15 @@ + + + +
+

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

+

+ @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.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/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..b6c2e57 --- /dev/null +++ b/Queueify.Web/Components/Pages/Add.razor @@ -0,0 +1,253 @@ +@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]; +
  • + +
    +
    @r.Title
    +
    @r.Details
    +
    +
    +
    + Spotify@if (r.Spotify == null) { (@Loc.T("web.add.not_on")) } + Tidal@if (r.Tidal == null) { (@Loc.T("web.add.not_on")) } + @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 bool _prefillPending, _focusPending; + 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(); + _prefillPending = true; // searched once the page is live: OnInitializedAsync also runs while the server draws the page + } + } + + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (firstRender) _focusPending = true; + if (_focusPending) + { + _focusPending = false; + try { await JS.InvokeAsync("queueify.focus", "[data-q-search]"); } + catch (JSException) { } + catch (JSDisconnectedException) { } + catch (InvalidOperationException) { } + } + if (_prefillPending) + { + _prefillPending = false; + await RunSearch(_cts = new CancellationTokenSource()); + } + } + + private async Task OnInput(ChangeEventArgs e) + { + _query = e.Value?.ToString() ?? ""; + // Whatever was running or shown belongs to the old text. + ClearSearch(); + 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 = ""; ClearSearch(); break; + case "Enter": + if (_resultsFor == _query.Trim() && _selected >= 0 && _selected < _results.Count) AddResult(_results[_selected]); + else { ClearSearch(); await RunSearch(_cts = new CancellationTokenSource()); } + break; + } + } + + /// Abandons a running search and forgets its results, so a late answer can never reappear. + private void ClearSearch() + { + _cts?.Cancel(); + _searching = false; _results = []; _errors = []; _status = ""; _resultsFor = null; _offerNoLink = false; _selected = -1; + } + + 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 (ReferenceEquals(_cts, cts)) _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) + { + ClearSearch(); + try { item = Queue.Add(item, _magazine); } + catch (Exception ex) when (ex is IOException or InvalidOperationException or Microsoft.Data.Sqlite.SqliteException) + { + Toasts.Show(new Toast(Loc.T("web.error.save"), Warning: true)); + return; + } + _query = ""; + Toasts.Show(new Toast(Loc.F("toast.added", item.Album), Loc.T("toast.undo"), () => Queue.Remove(item))); + _focusPending = true; // done after the next render, where errors are caught + } + + public void Dispose() => _cts?.Cancel(); +} diff --git a/Queueify.Web/Components/Pages/ConnectPc.razor b/Queueify.Web/Components/Pages/ConnectPc.razor new file mode 100644 index 0000000..b903547 --- /dev/null +++ b/Queueify.Web/Components/Pages/ConnectPc.razor @@ -0,0 +1,134 @@ +@page "/connect" +@attribute [Authorize] +@using Microsoft.AspNetCore.Authorization +@using Queueify.Web.Services +@using Queueify.Web.Sync +@inject PersonalAccessTokens Tokens +@inject Reauthentication Reauth +@inject AuthenticationStateProvider Auth +@inject NavigationManager Navigation +@inject IConfiguration Config + +@Loc.T("connect.title") - Queueify + +
+ +
+

@Loc.T("connect.title")

+

@Loc.T("connect.intro")

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

@Loc.T("connect.tokens")

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

@Loc.T("connect.empty")

+ } + else + { +
    + @foreach (var token in _tokens) + { +
  • +
    +
    @token.Name
    +
    @Loc.T("connect.created"): @token.CreatedAt.ToString("yyyy-MM-dd HH:mm") UTC
    +
    @Loc.T("connect.last_used"): @(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 bool _wrongPassword; + private string _password = ""; + 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; + // 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); + _connectText = SyncConnect.Format(PublicUrl.Of(Config) ?? 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/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/Help.razor b/Queueify.Web/Components/Pages/Help.razor new file mode 100644 index 0000000..12dcbb2 --- /dev/null +++ b/Queueify.Web/Components/Pages/Help.razor @@ -0,0 +1,54 @@ +@page "/help" +@rendermode InteractiveServer +@using Queueify.Services +@using Queueify.Web.Components.Shared +@using Queueify.Web.Services +@inject TourService Tour + +@Loc.T("webHelp.title") + +

@Loc.T("webHelp.title")

+

@Loc.T("webHelp.summary")

+ +
+

@Loc.T("help.guide")

+

@Loc.T("help.guide.1")

+

@Loc.T("help.guide.2")

+

@Loc.T("help.guide.3")

+

@Loc.T("help.guide.4")

+

@Loc.T("webHelp.guide.5")

+ +
+ +
+

@Loc.T("help.shortcuts")

+ + + + + + @foreach (var shortcut in Shortcuts.Web) + { + + + + + } + +
@Loc.T("webHelp.col.keys")@Loc.T("webHelp.col.does")
@shortcut.Keys@shortcut.Description
+

@Loc.T("webHelp.touch")

+
+ +
+

@Loc.T("webSettings.connect.title")

+

@Loc.T("webHelp.sync")

+
+ +
+

@Loc.T("help.trouble")

+

@Loc.T("webHelp.trouble.1")

+

@Loc.T("webHelp.trouble.2")

+

@Loc.T("webHelp.trouble.3")

+
+ + diff --git a/Queueify.Web/Components/Pages/Help.razor.css b/Queueify.Web/Components/Pages/Help.razor.css new file mode 100644 index 0000000..d6ea970 --- /dev/null +++ b/Queueify.Web/Components/Pages/Help.razor.css @@ -0,0 +1,30 @@ +.summary { color: var(--colorNeutralForeground2, #424242); } + +section { margin-block: 24px; max-width: 46rem; } +h2 { font-size: 1.25rem; margin-bottom: 8px; } + +.replay { + min-height: 44px; + padding: 0 16px; + font: inherit; + font-weight: 600; + border-radius: var(--borderRadiusMedium, 4px); + border: 1px solid var(--colorNeutralStroke1, #d1d1d1); + background: var(--colorNeutralBackground1, #fff); + color: var(--colorNeutralForeground1, #242424); +} +.replay:focus-visible { outline: 2px solid var(--colorStrokeFocus2, #000); outline-offset: 2px; } + +.shortcuts { border-collapse: collapse; width: 100%; } +.shortcuts th, .shortcuts td { text-align: start; padding: 8px 12px 8px 0; vertical-align: top; border-bottom: 1px solid var(--colorNeutralStroke2, #e0e0e0); } +.shortcuts th { white-space: nowrap; width: 1%; font-weight: 400; } +kbd { + font: inherit; + font-size: 0.875rem; + padding: 2px 8px; + border: 1px solid var(--colorNeutralStroke1, #d1d1d1); + border-bottom-width: 2px; + border-radius: var(--borderRadiusMedium, 4px); + background: var(--colorNeutralBackground3, #f5f5f5); +} +.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } diff --git a/Queueify.Web/Components/Pages/Home.razor b/Queueify.Web/Components/Pages/Home.razor new file mode 100644 index 0000000..bb89ad4 --- /dev/null +++ b/Queueify.Web/Components/Pages/Home.razor @@ -0,0 +1,6 @@ +@page "/" +@attribute [Microsoft.AspNetCore.Authorization.Authorize] + +@Loc.T("nav.queue") - Queueify + + 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/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/Pages/Photo.razor b/Queueify.Web/Components/Pages/Photo.razor new file mode 100644 index 0000000..4981454 --- /dev/null +++ b/Queueify.Web/Components/Pages/Photo.razor @@ -0,0 +1,249 @@ +@page "/photo" +@attribute [Authorize] +@rendermode InteractiveServer +@implements IAsyncDisposable +@using System.Globalization +@using System.Text.Json +@using Microsoft.AspNetCore.Authorization +@using Queueify.Services +@using Queueify.Web.Ocr +@using Queueify.Web.Services +@inject IJSRuntime JS +@inject AuthenticationStateProvider Auth +@inject PreferencesStore Prefs +@inject OcrOptions Limits + +@Loc.T("webPhoto.title") + +

@Loc.T("webPhoto.title")

+

@Loc.T("webPhoto.summary")

+ +
+

@Loc.T("webPhoto.drop")

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

@Loc.T("webPhoto.privacy")

+
+ +
+ @if (_reading) + { +

@Loc.T("webPhoto.reading")

+ } + else if (_error is not null) + { +

@_error

+ } + else if (_lines is { Count: 0 }) + { +

@Loc.T("webPhoto.no_text")

+ } + else if (_lines is { Count: > 0 }) + { +

@Loc.F("webPhoto.found", _lines.Count)

+ } +
+ +@if (_preview is not null && _lines is { Count: > 0 }) +{ + + +
    + @for (var i = 0; i < _lines.Count; i++) + { + var index = i; + var line = _lines[i]; +
  • + +
  • + } +
+ + @if (_picked.Count > 0 && SearchText.Trim().Length > 0) + { + + } +} + +@code { + private sealed record Line(string Text, double X, double Y, double Width, double Height); + private sealed record Reading(int Width, int Height, List? Lines); + + private ElementReference _zone, _choose, _take; + private IJSObjectReference? _module, _watcher; + private DotNetObjectReference? _self; + private string? _userId, _fileId, _preview, _error; + private string _language = "auto"; + private bool _reading; + private int _width = 1, _height = 1; + private List? _lines; + private readonly List _picked = []; + + protected override async Task OnInitializedAsync() + { + _userId = await Auth.IdAsync(); + if (_userId is not null) _language = Prefs.Load(_userId).OcrLanguage; + } + + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (!firstRender) return; + _self = DotNetObjectReference.Create(this); + _module = await JS.InvokeAsync("import", "./js/queueify-upload.js"); + _watcher = await _module.InvokeAsync("watch", new[] { _choose, _take }, _zone, _self); + } + + /// Called from the browser when a photo is chosen, taken, dropped or pasted. + [JSInvokable] + public async Task OnFileChosen(string id, string name, long size, string? preview) + { + if (_reading) + { + // A photo dropped or pasted while another is being read: the new one is let go, so a late answer + // can never be drawn over the wrong picture. + try { await _module!.InvokeVoidAsync("release", id, preview); } + catch (Exception ex) when (ex is JSException or JSDisconnectedException) { } + return; + } + await ReleaseFileAsync(); + (_fileId, _preview, _lines, _error) = (id, preview, null, null); + _picked.Clear(); + + if (size > Limits.MaxBytes) + { + _error = Loc.F("webPhoto.err.tooLarge", Limits.MaxBytes / (1024 * 1024)); + await InvokeAsync(StateHasChanged); + return; + } + + _reading = true; + await InvokeAsync(StateHasChanged); + try + { + var result = await _module!.InvokeAsync("send", id, $"/api/photo?lang={_language}", null); + Apply(result); + } + catch (Exception ex) when (ex is JSException or JSDisconnectedException or TaskCanceledException) + { + _error = Loc.T("webPhoto.err.network"); + } + finally + { + _reading = false; + } + await InvokeAsync(StateHasChanged); + } + + private void Apply(UploadResult result) + { + if (result.Status == 200 && Parse(result.Body) is { Lines: { } lines } reading) + { + (_lines, _width, _height) = (lines, Math.Max(1, reading.Width), Math.Max(1, reading.Height)); + return; + } + + var code = result.Status == 0 ? "network" : Parse(result.Body)?.Error ?? "unknown"; + _error = code switch + { + "tooLarge" => Loc.F("webPhoto.err.tooLarge", Limits.MaxBytes / (1024 * 1024)), + "tooManyPixels" => Loc.T("webPhoto.err.tooManyPixels"), + "notAnImage" => Loc.T("webPhoto.err.notAnImage"), + "corrupt" => Loc.T("webPhoto.err.corrupt"), + "busy" => Loc.T("webPhoto.err.busy"), + "timeout" => Loc.T("webPhoto.err.timeout"), + "unauthorized" => Loc.T("webPhoto.err.unauthorized"), + "network" => Loc.T("webPhoto.err.network"), + "language" => Loc.T("webPhoto.err.language"), + "engineMissing" =>Loc.T("webPhoto.err.engineMissing"), + _ => Loc.T("webPhoto.err.unknown"), + }; + } + + private sealed record ErrorBody(string? Error); + + private static T? Parse(string body) + { + try { return JsonSerializer.Deserialize(body, new JsonSerializerOptions(JsonSerializerDefaults.Web)); } + catch (JsonException) { return default; } + } + + private async Task LanguageChanged(ChangeEventArgs e) + { + _language = e.Value?.ToString() is "es" or "en" ? e.Value!.ToString()! : "auto"; + if (_userId is not null) Prefs.Save(_userId, Prefs.Load(_userId) with { OcrLanguage = _language }); + await Task.CompletedTask; + } + + private void Toggle(int index) + { + if (!_picked.Remove(index)) _picked.Add(index); + } + + private string Box(Line l) => string.Create(CultureInfo.InvariantCulture, + $"left:{l.X / _width * 100:0.###}%;top:{l.Y / _height * 100:0.###}%;width:{l.Width / _width * 100:0.###}%;height:{l.Height / _height * 100:0.###}%"); + + /// The picked lines cleaned and joined, with the first year found: what the Add page's search takes. + private string SearchText + { + get + { + var parts = _picked.Select(i => OcrService.CleanLine(_lines![i].Text)).ToList(); + var text = string.Join(' ', parts.Select(p => p.Text).Where(t => t.Length > 0)); + // A year alone (a junk line) is no search: the link stays hidden until a title or an artist is picked. + if (text.Length == 0) return ""; + return parts.FirstOrDefault(p => p.Year is not null).Year is int year ? $"{text} {year}" : text; + } + } + + private string SearchHref => "/add?q=" + Uri.EscapeDataString(SearchText); + + private async Task ReleaseFileAsync() + { + if (_module is null || _fileId is null) return; + try { await _module.InvokeVoidAsync("release", _fileId, _preview); } + catch (Exception ex) when (ex is JSException or JSDisconnectedException) { } + _fileId = null; + } + + public async ValueTask DisposeAsync() + { + await ReleaseFileAsync(); + try + { + if (_watcher is not null) await _watcher.InvokeVoidAsync("dispose"); + if (_watcher is not null) await _watcher.DisposeAsync(); + if (_module is not null) await _module.DisposeAsync(); + } + catch (Exception ex) when (ex is JSException or JSDisconnectedException) { } + _self?.Dispose(); + } +} diff --git a/Queueify.Web/Components/Pages/Photo.razor.css b/Queueify.Web/Components/Pages/Photo.razor.css new file mode 100644 index 0000000..2b054a5 --- /dev/null +++ b/Queueify.Web/Components/Pages/Photo.razor.css @@ -0,0 +1,79 @@ +.summary { color: var(--colorNeutralForeground2, #424242); } + +.zone { + border: 2px dashed var(--colorNeutralStroke1, #d1d1d1); + border-radius: var(--borderRadiusLarge, 8px); + padding: 16px; + margin-block: 16px; +} + +.hint, .privacy { margin: 0 0 12px; color: var(--colorNeutralForeground2, #424242); } +.privacy { margin: 12px 0 0; font-size: 0.875rem; } + +.picks { display: flex; flex-wrap: wrap; gap: 16px; } +.pick { display: flex; flex-direction: column; gap: 4px; min-width: 14rem; } +.pick label { font-weight: 600; } +.pick select, .pick input { min-height: 44px; font: inherit; } + +.status { min-height: 1.5rem; } +.error { color: var(--colorPaletteRedForeground1, #b10e1c); } +.error::before { content: "\26A0\FE0E "; } + +.sheet { position: relative; display: block; max-width: 100%; width: fit-content; margin-block: 12px; } +.sheet img { display: block; max-width: 100%; height: auto; border-radius: var(--borderRadiusMedium, 4px); } +.box { + position: absolute; + border: 2px solid var(--colorBrandStroke1, #0f6cbd); + background: color-mix(in srgb, var(--colorBrandBackground, #0f6cbd) 12%, transparent); + border-radius: 2px; + cursor: pointer; +} +.box.picked { background: color-mix(in srgb, var(--colorBrandBackground, #0f6cbd) 45%, transparent); border-width: 3px; } + +.lines { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; } +.line { + width: 100%; + min-height: 44px; + text-align: start; + font: inherit; + padding: 6px 12px; + border: 1px solid var(--colorNeutralStroke1, #d1d1d1); + border-radius: var(--borderRadiusMedium, 4px); + background: var(--colorNeutralBackground1, #fff); + color: var(--colorNeutralForeground1, #242424); +} +.line[aria-pressed="true"] { + border-color: var(--colorBrandStroke1, #0f6cbd); + background: color-mix(in srgb, var(--colorBrandBackground, #0f6cbd) 18%, var(--colorNeutralBackground1, #fff)); + font-weight: 600; +} +.line[aria-pressed="true"]::before { content: "\2713 "; } + +.line:focus-visible, .go:focus-visible, .plain:focus-visible, .pick select:focus-visible, .pick input:focus-visible { + outline: 2px solid var(--colorStrokeFocus2, #000); + outline-offset: 2px; +} + +.searchbar { + position: sticky; + bottom: 0; + display: flex; + flex-wrap: wrap; + gap: 12px; + align-items: center; + margin-top: 16px; + padding: 12px 0; + background: var(--colorNeutralBackground1, #fff); +} +.go { + display: inline-flex; + align-items: center; + min-height: 44px; + padding: 0 16px; + border-radius: var(--borderRadiusMedium, 4px); + background: var(--colorBrandBackground, #0f6cbd); + color: var(--colorNeutralForegroundOnBrand, #fff); + text-decoration: none; + font-weight: 600; +} +.plain { min-height: 44px; font: inherit; background: none; border: none; text-decoration: underline; color: inherit; } diff --git a/Queueify.Web/Components/Pages/Settings.razor b/Queueify.Web/Components/Pages/Settings.razor new file mode 100644 index 0000000..d96c2c3 --- /dev/null +++ b/Queueify.Web/Components/Pages/Settings.razor @@ -0,0 +1,235 @@ +@page "/settings" +@attribute [Authorize] +@rendermode InteractiveServer +@using Microsoft.AspNetCore.Authorization +@using Queueify.Models +@using Queueify.Services +@using Queueify.Web.Components.Shared +@using Queueify.Web.Services +@using Queueify.Web.Sync +@inject AuthenticationStateProvider Auth +@inject SettingsService Music +@inject PreferencesStore Prefs +@inject SyncEngine Engine +@inject NavigationManager Nav + +@Loc.T("webSettings.title") + +

@Loc.T("webSettings.title")

+

@Loc.T("webSettings.summary")

+ +@if (_opened is not null) +{ + + + + +
+ + + @Loc.T("settings.preferred.text") +
+
+ + + @Loc.T("settings.country.text") +
+ +

@Show(_musicNotice)

+
+ + +
+ + + @Loc.T("webSettings.theme.text") +
+
+ + + @Loc.T("webSettings.language.text") +
+

@Show(_prefsNotice)

+
+ + +
+ + + @Loc.T("webSettings.ocr.text") +
+

@Show(_ocrNotice)

+
+ + + @Loc.T("webSettings.connect.open") + + + + + + + + + + + +
+ + +
+ +

@Show(_deleteNotice)

+
+} + +@code { + private string? _uid; + private SettingsSnapshot? _opened; + private Preferences _prefs = Preferences.Default; + private string _spotifyId = "", _spotifySecret = "", _tidalId = "", _tidalSecret = "", _preferred = "Tidal", _country = "AR"; + private MusicService? _testing; + private bool _sure; + private Notice? _musicNotice, _spotifyNotice, _tidalNotice, _deleteNotice, _prefsNotice, _ocrNotice; + + protected override async Task OnInitializedAsync() + { + _uid = await Auth.IdAsync(); + if (_uid is not null) Reload(); + } + + private void Reload() + { + _opened = Music.Snapshot(_uid!); + _prefs = Prefs.Load(_uid!); + (_spotifyId, _spotifySecret, _tidalId, _tidalSecret) = (_opened.SpotifyClientId, "", _opened.TidalClientId, ""); + (_preferred, _country) = (_opened.PreferredService, _opened.CountryCode); + } + + private static string Show(Notice? n) => n is null ? "" : (n.IsError ? "⚠︎ " : "✓ ") + n.Text; + + private void SaveMusic() + { + try + { + var edit = new SettingsEdit(_spotifyId, _spotifySecret, _tidalId, _tidalSecret, _preferred, _country); + _musicNotice = new(Loc.T(Music.Save(_uid!, _opened!, edit) ? "webSettings.saved" : "webSettings.unchanged")); + Reload(); + } + catch (Exception ex) when (ex is ArgumentException or IOException) + { + _musicNotice = new(Loc.F("webSettings.failed", ex.GetType().Name), true); + } + } + + private void Remove(MusicService service) + { + Notice notice; + try + { + Music.RemoveKeys(_uid!, service); + _opened = Music.Snapshot(_uid!); + // Only this service's fields are emptied; whatever was typed in the other fields stays. + if (service == MusicService.Spotify) (_spotifyId, _spotifySecret) = ("", ""); + else (_tidalId, _tidalSecret) = ("", ""); + notice = new(Loc.F("webSettings.removed", service.ToString())); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + notice = new(Loc.F("webSettings.failed", ex.GetType().Name), true); + } + _musicNotice = null; + if (service == MusicService.Spotify) _spotifyNotice = notice; else _tidalNotice = notice; + } + + private async Task TestAsync(MusicService service) + { + _testing = service; + var name = service.ToString(); + Notice notice; + try + { + var result = await Music.TestAsync(_uid!, service, CancellationToken.None); + notice = result.Outcome switch + { + KeyTestOutcome.Ok => new(Loc.F("webSettings.test.ok", name)), + KeyTestOutcome.Missing => new(Loc.F("webSettings.test.missing", name), true), + KeyTestOutcome.Unexpected => new(Loc.F("webSettings.test.unexpected", name), true), + _ => new(result.Message ?? Loc.F("webSettings.test.unexpected", name), true), + }; + } + finally + { + _testing = null; + } + if (service == MusicService.Spotify) _spotifyNotice = notice; else _tidalNotice = notice; + } + + private void ThemeChanged(ChangeEventArgs e) => Remember(p => Preferences.Themes.Contains(e.Value as string ?? "") ? p with { Theme = (string)e.Value! } : p); + + private void OcrChanged(ChangeEventArgs e) => Remember(p => Preferences.OcrLanguages.Contains(e.Value as string ?? "") ? p with { OcrLanguage = (string)e.Value! } : p, ocr: true); + + private void LanguageChanged(ChangeEventArgs e) + { + var before = _prefs.Language; + Remember(p => Preferences.Languages.Contains(e.Value as string ?? "") ? p with { Language = (string)e.Value! } : p); + // Every text on the page comes from the language, so the page is loaded again in the new one. + if (_prefs.Language != before) Nav.NavigateTo(Nav.Uri, forceLoad: true); + } + + private void Remember(Func change, bool ocr = false) + { + try + { + _prefs = change(Prefs.Load(_uid!)); + Prefs.Save(_uid!, _prefs); + var notice = new Notice(Loc.T("webSettings.saved")); if (ocr) _ocrNotice = notice; else _prefsNotice = notice; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + var failed = new Notice(Loc.F("webSettings.failed", ex.GetType().Name), true); if (ocr) _ocrNotice = failed; else _prefsNotice = failed; + } + } + + private async Task DeleteAll() + { + if (!_sure) return; + try + { + // Through the sync engine: it waits for a running sync and forgets the file it had prepared. + await Engine.DeleteUserDataAsync(_uid!); + _sure = false; + Reload(); + _deleteNotice = new(Loc.T("webSettings.delete.done")); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // A file in use (an import or a photo is running): nothing is lost that wasn't already being written. + _deleteNotice = new(Loc.F("webSettings.failed", ex.GetType().Name), true); + } + } +} diff --git a/Queueify.Web/Components/Pages/Settings.razor.css b/Queueify.Web/Components/Pages/Settings.razor.css new file mode 100644 index 0000000..be77ebb --- /dev/null +++ b/Queueify.Web/Components/Pages/Settings.razor.css @@ -0,0 +1,26 @@ +.summary { color: var(--colorNeutralForeground2, #424242); } + +.field { display: flex; flex-direction: column; gap: 4px; margin-block: 12px; max-width: 28rem; } +.field label { font-weight: 600; } +.help { font-size: 0.875rem; color: var(--colorNeutralForeground2, #424242); } +select { min-height: 44px; font: inherit; padding: 0 8px; border-radius: var(--borderRadiusMedium, 4px); border: 1px solid var(--colorNeutralStroke1, #d1d1d1); background: var(--colorNeutralBackground1, #fff); color: inherit; } + +.primary, .danger, .link { + display: inline-flex; align-items: center; min-height: 44px; padding: 0 16px; font: inherit; font-weight: 600; + border-radius: var(--borderRadiusMedium, 4px); border: 1px solid transparent; text-decoration: none; cursor: pointer; +} +.primary { background: var(--colorBrandBackground, #0f6cbd); color: var(--colorNeutralForegroundOnBrand, #fff); } +.link { border-color: var(--colorNeutralStroke1, #d1d1d1); background: var(--colorNeutralBackground1, #fff); color: inherit; } +.danger { background: var(--colorPaletteRedBackground3, #b10e1c); color: #fff; } +.danger:disabled { opacity: 0.5; cursor: not-allowed; } + +.check { display: flex; align-items: center; gap: 8px; margin-bottom: 12px; min-height: 44px; } +.check input { width: 24px; height: 24px; } + +.notice { min-height: 1.5rem; margin: 8px 0 0; } +.notice.error { color: var(--colorPaletteRedForeground1, #b10e1c); } + +select:focus-visible, .primary:focus-visible, .danger:focus-visible, .link:focus-visible, .check input:focus-visible { + outline: 2px solid var(--colorStrokeFocus2, #000); + outline-offset: 2px; +} diff --git a/Queueify.Web/Components/Routes.razor b/Queueify.Web/Components/Routes.razor new file mode 100644 index 0000000..3fa5213 --- /dev/null +++ b/Queueify.Web/Components/Routes.razor @@ -0,0 +1,28 @@ +@using Queueify.Web.Components.Account.Shared +@inject LanguageState State + + + + + + + + + + + + +@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/Cover.razor b/Queueify.Web/Components/Shared/Cover.razor new file mode 100644 index 0000000..1a7b8c6 --- /dev/null +++ b/Queueify.Web/Components/Shared/Cover.razor @@ -0,0 +1,35 @@ +@using Queueify.Services +@* The album cover, or a tinted sleeve with the artist's initials when there is none (or it can't load). *@ +
+ + @if (Src is { } src) + { + + } +
+ +@code { + [Parameter] public string? Url { get; set; } + [Parameter] public string Artist { get; set; } = ""; + [Parameter] public string Album { get; set; } = ""; + [Parameter] public string? Class { get; set; } + + // Covers come from catalogs and from sync: web addresses only, and never plain http inside an https page. + private string? Src => CoverUrls.Loadable(Url) is { } uri ? new UriBuilder(uri) { Scheme = Uri.UriSchemeHttps, Port = uri.IsDefaultPort ? -1 : uri.Port }.Uri.AbsoluteUri : null; + + /// A hue from the name, the same on every run (string.GetHashCode is not), so a sleeve keeps its colour. + public static int Hue(string s) + { + uint h = 2166136261; + foreach (var c in s) h = (h ^ c) * 16777619; + return 250 + (int)(h % 100); // violet to pink to red, the logo's range + } + + public static string Initials(string artist, string album) + { + var words = (artist.Length > 0 ? artist : album).Split(' ', StringSplitOptions.RemoveEmptyEntries); + var letters = words.Take(2).Select(w => w.FirstOrDefault(char.IsLetterOrDigit)).Where(c => c != '\0'); + var text = string.Concat(letters).ToUpperInvariant(); + return text.Length > 0 ? text : "♪"; + } +} diff --git a/Queueify.Web/Components/Shared/HelpTour.razor b/Queueify.Web/Components/Shared/HelpTour.razor new file mode 100644 index 0000000..8ac81b6 --- /dev/null +++ b/Queueify.Web/Components/Shared/HelpTour.razor @@ -0,0 +1,82 @@ +@implements IDisposable +@using Queueify.Services +@using Queueify.Web.Services +@inject AuthenticationStateProvider Auth +@inject PreferencesStore Prefs +@inject TourService Tour + +@if (_step is { } step) +{ + +} + +@code { + private const int Steps = 4; + private string? _userId; + private int? _step; + private bool _owner; + private bool _focus; + private ElementReference _dialog; + + protected override async Task OnInitializedAsync() + { + _owner = Tour.TryAttach(this); + if (!_owner) return; + Tour.Replayed += Replay; + _userId = await Auth.IdAsync(); + if (_userId is not null && !Prefs.Load(_userId).TourSeen) Start(); + } + + private void Start() + { + _step = 0; + _focus = true; + } + + private void Replay() => _ = InvokeAsync(() => + { + if (_userId is null) return; + Start(); + StateHasChanged(); + }); + + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (!_focus || _step is null) return; + _focus = false; + try { await _dialog.FocusAsync(); } + catch (Exception ex) when (ex is InvalidOperationException or JSException or JSDisconnectedException) { } + } + + private void Next() + { + if (_step + 1 >= Steps) Finish(); + else _step++; + } + + private void Finish() + { + _step = null; + if (_userId is not null) Prefs.Save(_userId, Prefs.Load(_userId) with { TourSeen = true }); + } + + private void KeyPressed(KeyboardEventArgs e) + { + if (e.Key == "Escape") Finish(); + } + + public void Dispose() + { + if (!_owner) return; + Tour.Replayed -= Replay; + Tour.Detach(this); + } +} diff --git a/Queueify.Web/Components/Shared/HelpTour.razor.css b/Queueify.Web/Components/Shared/HelpTour.razor.css new file mode 100644 index 0000000..548dc64 --- /dev/null +++ b/Queueify.Web/Components/Shared/HelpTour.razor.css @@ -0,0 +1,31 @@ +.tour { + position: fixed; + inset-inline: 16px; + bottom: 16px; + margin-inline: auto; + max-width: 28rem; + z-index: 1000; + padding: 16px 20px; + border-radius: var(--borderRadiusXLarge, 8px); + border: 1px solid var(--colorNeutralStroke1, #d1d1d1); + background: var(--colorNeutralBackground1, #fff); + color: var(--colorNeutralForeground1, #242424); + box-shadow: var(--shadow16, 0 8px 16px rgba(0, 0, 0, 0.28)); +} +.tour:focus-visible { outline: 2px solid var(--colorStrokeFocus2, #000); outline-offset: 2px; } +.counter { margin: 0 0 4px; font-size: 0.8125rem; color: var(--colorNeutralForeground2, #424242); } +h2 { font-size: 1.125rem; margin: 0 0 6px; } +.actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 12px; } +.actions button { + min-height: 44px; + padding: 0 16px; + font: inherit; + border-radius: var(--borderRadiusMedium, 4px); + border: 1px solid var(--colorNeutralStroke1, #d1d1d1); + background: var(--colorNeutralBackground1, #fff); + color: inherit; +} +.actions .next { background: var(--colorBrandBackground, #0f6cbd); border-color: transparent; color: var(--colorNeutralForegroundOnBrand, #fff); font-weight: 600; } +.actions button:focus-visible { outline: 2px solid var(--colorStrokeFocus2, #000); outline-offset: 2px; } +@media (prefers-reduced-motion: no-preference) { .tour { animation: rise 160ms ease-out; } } +@keyframes rise { from { opacity: 0; transform: translateY(8px); } } diff --git a/Queueify.Web/Components/Shared/Ico.razor b/Queueify.Web/Components/Shared/Ico.razor new file mode 100644 index 0000000..482608d --- /dev/null +++ b/Queueify.Web/Components/Shared/Ico.razor @@ -0,0 +1,40 @@ +@* One stroke icon set for the whole app, drawn on a 24 grid; always decorative, the button or link around it carries the name. *@ + + +@code { + [Parameter, EditorRequired] public string Name { get; set; } = ""; + + private static string[] Paths(string name) => name switch + { + "queue" => ["M4 6h16", "M4 12h9", "M4 18h9", "M16 13l5 3.5-5 3.5z"], + "listened" => ["M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0z", "M8 12.5l3 3 5-6"], + "add" => ["M12 5v14", "M5 12h14"], + "photo" => ["M4 8h3l2-2h6l2 2h3v11H4z", "M12 17a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7z"], + "help" => ["M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0z", "M9.5 9.5a2.5 2.5 0 1 1 3.5 2.3c-.7.4-1 .9-1 1.7", "M12 17h.01"], + "settings" => ["M4 7h9", "M17 7h3", "M4 17h3", "M11 17h9", "M15 5v4", "M9 15v4"], + "connect" => ["M3 5h18v11H3z", "M8 20h8", "M12 16v4"], + "signout" => ["M9 4H5v16h4", "M16 8l4 4-4 4", "M20 12H9"], + "more" => ["M5 12h.01", "M12 12h.01", "M19 12h.01"], + "search" => ["M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14z", "M20 20l-4-4"], + "play" => ["M7 4l13 8-13 8z"], + "check" => ["M5 12.5l4.5 4.5L19 7.5"], + "star" => ["M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1L3.2 9.5l6.1-.9z"], + "trash" => ["M4 7h16", "M9 7V4h6v3", "M6 7l1 13h10l1-13", "M10 11v6", "M14 11v6"], + "dice" => ["M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z", "M8 8h.01", "M16 8h.01", "M8 16h.01", "M16 16h.01", "M12 12h.01"], + "grid" => ["M4 4h7v7H4z", "M13 4h7v7h-7z", "M4 13h7v7H4z", "M13 13h7v7h-7z"], + "list" => ["M8 6h13", "M8 12h13", "M8 18h13", "M3 6h.01", "M3 12h.01", "M3 18h.01"], + "undo" => ["M9 14L4 9l5-5", "M4 9h10a6 6 0 0 1 0 12h-3"], + "info" => ["M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0z", "M12 11v5", "M12 8h.01"], + "warn" => ["M12 3l10 18H2z", "M12 10v5", "M12 18h.01"], + "close" => ["M6 6l12 12", "M18 6L6 18"], + "globe" => ["M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0z", "M3 12h18", "M12 3c3 3 3 15 0 18", "M12 3c-3 3-3 15 0 18"], + "open" => ["M14 4h6v6", "M20 4l-9 9", "M18 14v5H5V6h5"], + "person" => ["M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8z", "M4 20c1-4 4-6 8-6s7 2 8 6"], + _ => [], + }; +} diff --git a/Queueify.Web/Components/Shared/QueueBrowser.razor b/Queueify.Web/Components/Shared/QueueBrowser.razor new file mode 100644 index 0000000..0dae7be --- /dev/null +++ b/Queueify.Web/Components/Shared/QueueBrowser.razor @@ -0,0 +1,306 @@ +@implements IDisposable +@inject UserQueue Queue +@inject Toasts Toasts +@inject IJSRuntime JS + +@{ + var items = View(); + var shown = items.Count > _shown ? items.GetRange(0, _shown) : items; +} + +
+ +
+

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

+

@(Listened ? QueueText.ListenedSummary(Queue.HeardItems) : QueueText.PendingSummary(Queue.PendingItems, DateTime.Now))

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

@EmptyTitle

+

@EmptyText

+ @if (!Listened && _typed.Length == 0) + { + @Loc.T("web.nav.add") + } +
+} +else if (_covers) +{ +
    + @foreach (var item in shown) + { +
  • + +
    +
    @item.Album
    +
    @item.ArtistLine
    +
    @Subtitle(item)
    +
    + @if (Listened) { } +
    @Actions(item)
    +
  • + } +
+} +else +{ +
    + @foreach (var item in shown) + { +
  • + +
    +
    @item.Album
    +
    @item.ArtistLine
    +
    @Subtitle(item)
    + @if (Listened) { } +
    +
    @Actions(item)
    +
  • + } +
+} + +@if (items.Count > shown.Count) +{ +

+} + +@code { + [Parameter] public bool Listened { get; set; } + + /// Albums drawn per page; the rest wait behind a button, so a queue of tens of thousands stays light. + private const int PageSize = 100; + + private string _typed = ""; // what the box shows, at once + private string _filter = ""; // what the list uses, after a pause in typing + private int _shown = PageSize; + private CancellationTokenSource? _pause; + private List _view = []; + private (int Version, bool Listened, string Filter, string Sort) _viewOf = (-1, false, "", ""); + private string _sort = "oldest"; + private bool _covers; + private string? _picked; + + private RenderFragment Actions(BacklogItem item) => @ + @{ + var link = PlayLinks.Of(item, Queue.Preferred); + var service = link != null && link.Web.Contains("tidal.com") ? "Tidal" : "Spotify"; + } + @if (link != null) + { + @service + } + else + { + @Loc.T("item.no_link") + } + +
+ +
+ @if (PlayLinks.Only(item, MusicService.Tidal) is { } tidal) + { + @Loc.T("menu.open_tidal") + } + @if (PlayLinks.Only(item, MusicService.Spotify) is { } spotify) + { + @Loc.T("menu.open_spotify") + } + +
+
+
; + + protected override async Task OnInitializedAsync() + { + Queue.Changed += OnChanged; // before the await, so a disposal during the load cannot leave it attached + await Queue.LoadAsync(); + } + + /// The albums to list: worked out again only when the queue, the filter or the order changed. + private List View() + { + var of = (Queue.Version, Listened, _filter, _sort); + if (of != _viewOf) + { + _view = QueueView.Apply(Queue.Search(_filter), Listened, "", _sort); + _viewOf = of; + } + return _view; + } + + private void ShowMore() => _shown += PageSize; + + // Waits for a pause in typing; a newer keystroke cancels this wait. The box itself never lags. + private async Task OnFilterInput(ChangeEventArgs e) + { + _typed = e.Value?.ToString() ?? ""; + _pause?.Cancel(); + var pause = _pause = new CancellationTokenSource(); + try { await Task.Delay(250, pause.Token); } + catch (OperationCanceledException) { return; } + _filter = _typed; + _shown = PageSize; + } + + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (!firstRender) return; + try + { + var saved = await JS.InvokeAsync("queueify.getMany", (object)new[] { "q-sort", "q-covers" }); + if (saved is [var sort, var covers]) + { + if (sort != null && QueueView.SortKeys.Contains(sort)) _sort = sort; + _covers = covers == "1"; + StateHasChanged(); + } + } + catch (JSException) { } + catch (JSDisconnectedException) { } // the tab closed while the call was out + catch (InvalidOperationException) { } + } + + private async void OnChanged() + { + try { await InvokeAsync(StateHasChanged); } + catch (ObjectDisposedException) { } // the page went away first + catch (Exception ex) { await DispatchExceptionAsync(ex); } + } + + private static string SortLabel(string key) => key switch + { + "newest" => Loc.T("sort.newest"), + "artist" => Loc.T("sort.artist"), + "year" => Loc.T("sort.year"), + "source" => Loc.T("sort.magazine"), + _ => Loc.T("sort.oldest"), + }; + + private string Subtitle(BacklogItem item) => item.Subtitle; + + private string EmptyTitle => _typed.Length > 0 ? Loc.T("empty.filter.title") : Listened ? Loc.T("empty.listened.title") : Loc.T("empty.queue.title"); + private string EmptyText => _typed.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"; + _shown = PageSize; + 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 (JSDisconnectedException) { } + catch (InvalidOperationException) { } + } + + private void OnFilterKey(KeyboardEventArgs e) + { + if (e.Key != "Escape") return; + _pause?.Cancel(); + _typed = _filter = ""; + _shown = PageSize; + } + + // A disk problem must reach the user as a message, not end the circuit. + private void Guarded(Action action) + { + try { action(); } + catch (Exception ex) when (ex is IOException or InvalidOperationException or Microsoft.Data.Sqlite.SqliteException) + { + Toasts.Show(new Toast(Loc.T("web.error.save"), Warning: true)); + } + } + + private void Toggle(BacklogItem item) + { + var listened = !item.IsListened; + Guarded(() => + { + 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 => Guarded(() => Queue.Rate(item, stars)) : null)); + }); + } + + private void Delete(BacklogItem item) + { + Guarded(() => + { + 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.PendingItems; + if (pending.Count == 0) + { + Toasts.Show(new Toast(Loc.T("toast.surprise_empty"))); + return; + } + var pick = pending[Random.Shared.Next(pending.Count)]; + _pause?.Cancel(); + _typed = _filter = ""; + _picked = pick.Uid; + var at = View().FindIndex(i => i.Uid == pick.Uid); + if (at >= _shown) _shown = at + 1; // the pick must be on the page to be scrolled to + 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 (JSDisconnectedException) { } + catch (InvalidOperationException) { } + } + + public void Dispose() + { + Queue.Changed -= OnChanged; + _pause?.Cancel(); + _pause?.Dispose(); + } +} diff --git a/Queueify.Web/Components/Shared/SettingsData.razor b/Queueify.Web/Components/Shared/SettingsData.razor new file mode 100644 index 0000000..0b83cd3 --- /dev/null +++ b/Queueify.Web/Components/Shared/SettingsData.razor @@ -0,0 +1,108 @@ +@implements IAsyncDisposable +@using System.Text.Json +@using Queueify.Services +@using Queueify.Web.Services +@inject IJSRuntime JS + +
+

+ @Loc.T("webData.export.json") + @Loc.T("webData.export.csv") +

+ +

@Loc.T("webData.import.title")

+

@Loc.T("webData.import.text")

+
+ + +
+ + @if (_fileName is not null) + { + @_fileName + } +

@(_result is null ? "" : (_result.IsError ? "⚠︎ " : "✓ ") + _result.Text)

+
+ +@code { + private ElementReference _input; + private IJSObjectReference? _module, _watcher; + private DotNetObjectReference? _self; + private string? _fileId, _fileName; + private bool _working; + private Notice? _result; + + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (!firstRender) return; + _self = DotNetObjectReference.Create(this); + _module = await JS.InvokeAsync("import", "./js/queueify-upload.js"); + _watcher = await _module.InvokeAsync("watch", new[] { _input }, null, _self); + } + + /// Called from the browser when a file is chosen; nothing is sent until Import is pressed. + [JSInvokable] + public async Task OnFileChosen(string id, string name, long size, string? preview) + { + (_fileId, _fileName, _result) = (id, name, null); + if (size > Queueify.Web.Services.DataTransfer.MaxBytes) _result = new(Loc.F("webData.import.too_big", Queueify.Web.Services.DataTransfer.MaxBytes / (1024 * 1024)), true); + await InvokeAsync(StateHasChanged); + } + + private async Task ImportAsync() + { + if (_fileId is null || _module is null) return; + _working = true; + _result = null; + try + { + var answer = await _module.InvokeAsync("send", _fileId, "/api/import", "application/octet-stream"); + _result = Describe(answer); + } + catch (Exception ex) when (ex is JSException or JSDisconnectedException or TaskCanceledException) + { + _result = new(Loc.T("webData.import.failed"), true); + } + finally + { + _working = false; + } + } + + private sealed record Report(int Added, int AlreadyHere, int Skipped); + private sealed record ErrorBody(string? Error); + + private static Notice Describe(UploadResult answer) + { + var options = new JsonSerializerOptions(JsonSerializerDefaults.Web); + try + { + if (answer.Status == 200 && JsonSerializer.Deserialize(answer.Body, options) is { } r) + return new(Loc.F("webData.import.done", r.Added, r.AlreadyHere, r.Skipped)); + return JsonSerializer.Deserialize(answer.Body, options)?.Error switch + { + "tooLarge" => new(Loc.F("webData.import.too_big", Queueify.Web.Services.DataTransfer.MaxBytes / (1024 * 1024)), true), + "invalid" => new(Loc.T("webData.import.invalid"), true), + _ => new(Loc.T("webData.import.failed"), true), + }; + } + catch (JsonException) + { + return new(Loc.T("webData.import.failed"), true); + } + } + + public async ValueTask DisposeAsync() + { + try + { + if (_module is not null && _fileId is not null) await _module.InvokeVoidAsync("release", _fileId, null); + if (_watcher is not null) { await _watcher.InvokeVoidAsync("dispose"); await _watcher.DisposeAsync(); } + if (_module is not null) await _module.DisposeAsync(); + } + catch (Exception ex) when (ex is JSException or JSDisconnectedException) { } + _self?.Dispose(); + } +} diff --git a/Queueify.Web/Components/Shared/SettingsData.razor.css b/Queueify.Web/Components/Shared/SettingsData.razor.css new file mode 100644 index 0000000..e3bf0c3 --- /dev/null +++ b/Queueify.Web/Components/Shared/SettingsData.razor.css @@ -0,0 +1,16 @@ +h3 { font-size: 1rem; margin: 16px 0 4px; } +.text { margin: 0 0 8px; color: var(--colorNeutralForeground2, #424242); } +.actions { display: flex; flex-wrap: wrap; gap: 8px; margin: 0; } +.download, .import { + display: inline-flex; align-items: center; min-height: 44px; padding: 0 16px; font: inherit; + border-radius: var(--borderRadiusMedium, 4px); border: 1px solid var(--colorNeutralStroke1, #d1d1d1); + background: var(--colorNeutralBackground1, #fff); color: inherit; text-decoration: none; +} +.import:disabled { opacity: 0.6; } +.field { display: flex; flex-direction: column; gap: 4px; margin-bottom: 8px; max-width: 28rem; } +.field label { font-weight: 600; } +input { min-height: 44px; font: inherit; } +.name { margin-inline-start: 12px; overflow-wrap: anywhere; } +.notice { min-height: 1.5rem; margin: 8px 0 0; } +.notice.error { color: var(--colorPaletteRedForeground1, #b10e1c); } +a:focus-visible, button:focus-visible, input:focus-visible { outline: 2px solid var(--colorStrokeFocus2, #000); outline-offset: 2px; } diff --git a/Queueify.Web/Components/Shared/SettingsKeysCard.razor b/Queueify.Web/Components/Shared/SettingsKeysCard.razor new file mode 100644 index 0000000..0137b98 --- /dev/null +++ b/Queueify.Web/Components/Shared/SettingsKeysCard.razor @@ -0,0 +1,48 @@ +@using Queueify.Services +@using Queueify.Web.Services + +
+

@Name @(Configured ? "✓ " : "○ ")@Loc.T(Configured ? "webSettings.keys.on" : "webSettings.keys.off")

+
+ @Loc.T("webSettings.steps") +

@Steps

+
+ +
+ + +
+
+ + +
+ +
+ + @if (Configured) + { + + } +
+

@(Result is null ? "" : (Result.IsError ? "⚠︎ " : "✓ ") + Result.Text)

+
+ +@code { + [Parameter, EditorRequired] public string Service { get; set; } = ""; + [Parameter, EditorRequired] public string Name { get; set; } = ""; + [Parameter, EditorRequired] public string Steps { get; set; } = ""; + [Parameter] public bool Configured { get; set; } + [Parameter] public bool Testing { get; set; } + [Parameter] public Notice? Result { get; set; } + [Parameter] public string ClientId { get; set; } = ""; + [Parameter] public EventCallback ClientIdChanged { get; set; } + [Parameter] public string Secret { get; set; } = ""; + [Parameter] public EventCallback SecretChanged { get; set; } + [Parameter] public EventCallback OnTest { get; set; } + [Parameter] public EventCallback OnRemove { get; set; } +} diff --git a/Queueify.Web/Components/Shared/SettingsKeysCard.razor.css b/Queueify.Web/Components/Shared/SettingsKeysCard.razor.css new file mode 100644 index 0000000..52b55fe --- /dev/null +++ b/Queueify.Web/Components/Shared/SettingsKeysCard.razor.css @@ -0,0 +1,15 @@ +.keys { padding-block: 12px; border-top: 1px solid var(--colorNeutralStroke2, #e0e0e0); } +.keys:first-of-type { border-top: none; } +h3 { font-size: 1rem; margin: 0 0 6px; display: flex; flex-wrap: wrap; gap: 12px; align-items: baseline; } +.state { font-size: 0.8125rem; font-weight: 400; padding: 2px 8px; border-radius: 999px; border: 1px solid var(--colorNeutralStroke1, #d1d1d1); } +.state.on { border-color: var(--colorPaletteGreenBorder2, #107c10); } +.steps { white-space: pre-line; margin: 8px 0; color: var(--colorNeutralForeground2, #424242); } +.field { display: flex; flex-direction: column; gap: 4px; margin-block: 8px; max-width: 28rem; } +.field label { font-weight: 600; } +input { min-height: 44px; font: inherit; padding: 0 10px; border-radius: var(--borderRadiusMedium, 4px); border: 1px solid var(--colorNeutralStroke1, #d1d1d1); background: var(--colorNeutralBackground1, #fff); color: inherit; } +.actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 8px; } +button { min-height: 44px; padding: 0 16px; font: inherit; border-radius: var(--borderRadiusMedium, 4px); border: 1px solid var(--colorNeutralStroke1, #d1d1d1); background: var(--colorNeutralBackground1, #fff); color: inherit; } +button:disabled { opacity: 0.6; } +input:focus-visible, button:focus-visible, summary:focus-visible { outline: 2px solid var(--colorStrokeFocus2, #000); outline-offset: 2px; } +.notice { min-height: 1.5rem; margin: 8px 0 0; } +.notice.error { color: var(--colorPaletteRedForeground1, #b10e1c); } diff --git a/Queueify.Web/Components/Shared/SettingsSection.razor b/Queueify.Web/Components/Shared/SettingsSection.razor new file mode 100644 index 0000000..3b018a3 --- /dev/null +++ b/Queueify.Web/Components/Shared/SettingsSection.razor @@ -0,0 +1,15 @@ +
+

@Title

+ @if (!string.IsNullOrEmpty(Text)) + { +

@Text

+ } + @ChildContent +
+ +@code { + [Parameter, EditorRequired] public string Id { get; set; } = ""; + [Parameter, EditorRequired] public string Title { get; set; } = ""; + [Parameter] public string? Text { get; set; } + [Parameter] public RenderFragment? ChildContent { get; set; } +} diff --git a/Queueify.Web/Components/Shared/SettingsSection.razor.css b/Queueify.Web/Components/Shared/SettingsSection.razor.css new file mode 100644 index 0000000..8f07584 --- /dev/null +++ b/Queueify.Web/Components/Shared/SettingsSection.razor.css @@ -0,0 +1,11 @@ +.card { + margin-block: 16px; + padding: 16px 20px; + max-width: 46rem; + border: 1px solid var(--colorNeutralStroke2, #e0e0e0); + border-radius: var(--borderRadiusXLarge, 8px); + background: var(--colorNeutralBackground1, #fff); + color: var(--colorNeutralForeground1, #242424); +} +h2 { font-size: 1.125rem; margin: 0 0 6px; } +.text { margin: 0 0 12px; color: var(--colorNeutralForeground2, #424242); } diff --git a/Queueify.Web/Components/Shared/Snackbar.razor b/Queueify.Web/Components/Shared/Snackbar.razor new file mode 100644 index 0000000..cd3d785 --- /dev/null +++ b/Queueify.Web/Components/Shared/Snackbar.razor @@ -0,0 +1,64 @@ +@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(); + var shown = Toasts.Current; + _ = Task.Delay(TimeSpan.FromSeconds(Toasts.Current.Action != null ? 15 : 9), cts.Token).ContinueWith( + _ => InvokeAsync(() => { if (ReferenceEquals(Toasts.Current, shown)) 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..d3fb966 --- /dev/null +++ b/Queueify.Web/Components/Shared/Stars.razor @@ -0,0 +1,16 @@ +@* 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 { + public static string Label(int stars) => stars == 1 ? Loc.T("web.queue.star.one") : Loc.F("web.queue.stars", stars); + + [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 new file mode 100644 index 0000000..9da16cd --- /dev/null +++ b/Queueify.Web/Components/_Imports.razor @@ -0,0 +1,17 @@ +@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 Microsoft.FluentUI.AspNetCore.Components +@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/Data/ApplicationDbContext.cs b/Queueify.Web/Data/ApplicationDbContext.cs new file mode 100644 index 0000000..6a312d1 --- /dev/null +++ b/Queueify.Web/Data/ApplicationDbContext.cs @@ -0,0 +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/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/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/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 new file mode 100644 index 0000000..f0bb514 --- /dev/null +++ b/Queueify.Web/Data/Migrations/ApplicationDbContextModelSnapshot.cs @@ -0,0 +1,398 @@ +// +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("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/Ocr/ImageGuard.cs b/Queueify.Web/Ocr/ImageGuard.cs new file mode 100644 index 0000000..f7e6b20 --- /dev/null +++ b/Queueify.Web/Ocr/ImageGuard.cs @@ -0,0 +1,100 @@ +using SkiaSharp; + +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 + { + // 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 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); + + 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)); + decoded.SetImmutable(); // lets the image share the pixels instead of copying them + 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 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(); + 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..06465c0 --- /dev/null +++ b/Queueify.Web/Ocr/OcrExtensions.cs @@ -0,0 +1,84 @@ +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 + { + var reading = await reader.ReadAsync(user, ctx.Request.Body, 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 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..ecdf6c0 --- /dev/null +++ b/Queueify.Web/Ocr/PhotoReader.cs @@ -0,0 +1,64 @@ +using Queueify.Services; + +namespace Queueify.Web.Ocr; + +/// +/// Reads one uploaded photo: admission first (so a turned-away upload is never read into memory), then the +/// check and re-encode, the engine, and a time limit. The photo only exists in memory, as the bytes of the +/// upload and then of the clean PNG; nothing is written to disk and the clean PNG's buffer is wiped afterwards. +/// +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 + { + using var bytes = await BufferAsync(upload, options.MaxBytes, limit.Token); + // Decoding can't be interrupted, so the slot is kept until it ends: the "one at a time" bound holds even when it is slow. + prepared = await Task.Run(() => ImageGuard.Prepare(bytes, options), CancellationToken.None); + limit.Token.ThrowIfCancellationRequested(); + 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); + } + } + + 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; + } + + /// 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..464faf4 --- /dev/null +++ b/Queueify.Web/Ocr/TesseractOcr.cs @@ -0,0 +1,163 @@ +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); + // The first download has its own (HTTP) time limit: under the photo's 40 s it would restart from zero every time. + var folder = await tessdata.EnsureAsync(CancellationToken.None); + + 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: + Finish(); // a line whose box can't be read is dropped with its words, not merged into the previous one + if (TryBox(cells, out var line)) 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) + { + // Past the cap the rest is read and thrown away, so the engine never blocks on a full pipe. + if (text.Length + n <= MaxOutputChars) 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 new file mode 100644 index 0000000..407f191 --- /dev/null +++ b/Queueify.Web/Program.cs @@ -0,0 +1,83 @@ +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; +using Queueify.Web.Ocr; +using Queueify.Web.Services; +using Queueify.Web.Sync; + +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 = QueueifyStorageExtensions.AccountConnectionString(builder.Configuration, builder.Environment); +// A factory for component code (one short context per call), and a scoped context built from it for Identity. +builder.Services.AddDbContextFactory(options => options.UseSqlite(connectionString)); +builder.Services.AddScoped(sp => sp.GetRequiredService>().CreateDbContext()); +if (builder.Environment.IsDevelopment()) builder.Services.AddDatabaseDeveloperPageExceptionFilter(); + +builder.Services.AddIdentityCore(options => + { + options.SignIn.RequireConfirmedAccount = true; + options.Stores.SchemaVersion = IdentitySchemaVersions.Version3; + }) + .AddEntityFrameworkStores() + .AddSignInManager() + .AddDefaultTokenProviders(); + +builder.Services.AddSingleton, IdentityNoOpEmailSender>(); +builder.AddQueueifyUi(); +builder.Services.AddQueueifyOcr(builder.Configuration, builder.Environment); +builder.Services.AddQueueifyData(); +builder.Services.AddQueueifySync(); + +var app = builder.Build(); +app.UseQueueifySecureScheme(); + +// 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.MapQueueifyUi(); + +app.MapStaticAssets(); +app.MapRazorComponents() + .AddInteractiveServerRenderMode(); + +// Add additional endpoints required by the Identity /Account Razor components. +app.MapAdditionalIdentityEndpoints(); + +app.MapQueueifyPhoto(); +app.MapQueueifyData(); +app.MapQueueifySync(); + +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..f5efc11 --- /dev/null +++ b/Queueify.Web/Queueify.Web.csproj @@ -0,0 +1,27 @@ + + + + net10.0 + enable + enable + aspnet-Queueify_Web-86f5f9b8-1fbe-4cb8-8319-bc31a324140e + true + + + + + + + + + + + + + + + + + + + diff --git a/Queueify.Web/Services/AlbumSearch.cs b/Queueify.Web/Services/AlbumSearch.cs new file mode 100644 index 0000000..0f91b3c --- /dev/null +++ b/Queueify.Web/Services/AlbumSearch.cs @@ -0,0 +1,123 @@ +using System.Collections.Concurrent; +using Queueify.Models; +using Queueify.Services; + +namespace Queueify.Web.Services; + +/// Searches one catalog for one user, with the keys that user saved. The seam tests replace. +public interface ICatalogs +{ + Task> SearchAsync(MusicService service, string query, string userId, AppSettings settings, CancellationToken ct); +} + +/// +/// The real catalogs. Each user keeps their own Spotify/Tidal objects, so a token is reused between their +/// searches but never between users, and the keys are only ever read here on the server. +/// +public sealed class HttpCatalogs(IHttpClientFactory http) : ICatalogs +{ + public const string ClientName = "catalogs"; + + private sealed class Pair + { + public volatile AppSettings Settings = new(); + public SpotifyCatalog Spotify { get; } + public TidalCatalog Tidal { get; } + + public Pair(HttpClient client) + { + Spotify = new(client, () => Settings); + Tidal = new(client, () => Settings); + } + } + + private readonly ConcurrentDictionary _users = new(); + + public Task> SearchAsync(MusicService service, string query, string userId, AppSettings settings, CancellationToken ct) + { + var pair = _users.GetOrAdd(userId, _ => new Pair(http.CreateClient(ClientName))); + pair.Settings = settings; + return service == MusicService.Spotify ? pair.Spotify.SearchAsync(query, ct) : pair.Tidal.SearchAsync(query, ct); + } +} + +/// What one search found: the merged rows, what went wrong per service, and whether the best row is a confident match. +public sealed record SearchOutcome(IReadOnlyList Results, IReadOnlyList Errors, bool Confident, bool NeedsKeys = false, bool Throttled = false); + +/// The Add box's search: both services at once, then the year retry, mirroring the desktop app. +public sealed class AlbumSearch(ICatalogs catalogs) +{ + /// Null when was cancelled because a newer search replaced this one. + // One server IP talks to Spotify and Tidal for everybody, so a user (or a script driving their circuit) + // gets a fixed number of searches per minute; the rest wait for the window to pass. + private const int SearchesPerMinute = 30; + private static readonly System.Collections.Concurrent.ConcurrentDictionary> Recent = new(); + + private static bool Allowed(string userId) + { + var window = Recent.GetOrAdd(userId, _ => new Queue()); + lock (window) + { + var now = DateTime.UtcNow; + while (window.Count > 0 && now - window.Peek() > TimeSpan.FromMinutes(1)) window.Dequeue(); + if (window.Count >= SearchesPerMinute) return false; + window.Enqueue(now); + return true; + } + } + + public async Task RunAsync(string raw, string userId, AppSettings settings, CancellationToken ct) + { + if (!settings.SpotifyConfigured && !settings.TidalConfigured) + return new SearchOutcome([], [], false, NeedsKeys: true); + if (!Allowed(userId)) + return new SearchOutcome([], [Loc.T("web.add.throttled")], false, Throttled: true); + + var errors = new List(); + var found = new List(); + + async Task AskBothAsync(string q) + { + var asks = new List>>(); + if (settings.SpotifyConfigured) asks.Add(SafeAsync(MusicService.Spotify, q)); + if (settings.TidalConfigured) asks.Add(SafeAsync(MusicService.Tidal, q)); + foreach (var matches in await Task.WhenAll(asks)) + found.AddRange(matches.Where(m => !found.Any(f => f.Service == m.Service && f.Id == m.Id))); + } + + async Task> SafeAsync(MusicService service, string q) + { + var name = service.ToString(); + try { return await catalogs.SearchAsync(service, q, userId, settings, ct); } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { return []; } + catch (OperationCanceledException) { Report(name, Loc.T("search.timeout")); } + catch (CatalogException ex) { Report(name, ex.Message); } + catch (HttpRequestException ex) { Report(name, Loc.F("search.network", ex.Message)); } + catch (Exception ex) { Report(name, Loc.F("search.unexpected", ex.Message)); } + return []; + } + + void Report(string service, string message) + { + var line = $"{service}: {message}"; + lock (errors) { if (!errors.Contains(line)) errors.Add(line); } + } + + List Combine() => Matcher.Combine( + found.Where(m => m.Service == MusicService.Spotify), found.Where(m => m.Service == MusicService.Tidal), raw); + + await AskBothAsync(Matcher.SearchText(raw)); + if (ct.IsCancellationRequested) return null; + var results = Combine(); + + // "Prince 1999": the first search left the year out; the number may be the title, so try with it. + if (Matcher.ShouldRetryWithYear(raw, results)) + { + await AskBothAsync(raw); + if (ct.IsCancellationRequested) return null; + results = Combine(); + } + + return new SearchOutcome(results, errors, results.Count > 0 && results[0].Score >= Matcher.ConfidentScore); + } +} diff --git a/Queueify.Web/Services/CurrentUser.cs b/Queueify.Web/Services/CurrentUser.cs new file mode 100644 index 0000000..fcc1cb7 --- /dev/null +++ b/Queueify.Web/Services/CurrentUser.cs @@ -0,0 +1,14 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Components.Authorization; + +namespace Queueify.Web.Services; + +public static class CurrentUser +{ + /// The signed-in user's id (their data folder), or null when nobody is signed in. + public static async Task IdAsync(this AuthenticationStateProvider auth) + { + var user = (await auth.GetAuthenticationStateAsync()).User; + return user.Identity?.IsAuthenticated == true && user.FindFirstValue(ClaimTypes.NameIdentifier) is { Length: > 0 } id ? id : null; + } +} diff --git a/Queueify.Web/Services/DataEndpoints.cs b/Queueify.Web/Services/DataEndpoints.cs new file mode 100644 index 0000000..b194627 --- /dev/null +++ b/Queueify.Web/Services/DataEndpoints.cs @@ -0,0 +1,90 @@ +using System.Security.Claims; +using System.Text; +using Microsoft.AspNetCore.Http.Features; +using Queueify.Web.Storage; + +namespace Queueify.Web.Services; + +public static class DataEndpoints +{ + /// Settings, preferences, key tests, and export and import of the queue. + public static IServiceCollection AddQueueifyData(this IServiceCollection services) + { + services.AddSingleton(); + services.AddSingleton(); + services.AddScoped(); + services.AddSingleton(sp => + { + var factory = sp.GetRequiredService(); + return new SettingsService(sp.GetRequiredService(), () => factory.CreateClient("catalogs")); + }); + return services; + } + + public static IEndpointRouteBuilder MapQueueifyData(this IEndpointRouteBuilder app) + { + app.MapGet("/api/export.json", (HttpContext ctx, DataTransfer data) => + Download(ctx, "queueify.json", "application/json", Encoding.UTF8.GetBytes, data.ExportJson)); + app.MapGet("/api/export.csv", (HttpContext ctx, DataTransfer data) => + Download(ctx, "queueify.csv", "text/csv; charset=utf-8", s => [.. Encoding.UTF8.GetPreamble(), .. Encoding.UTF8.GetBytes(s)], data.ExportCsv)); + app.MapPost("/api/import", ImportAsync).DisableAntiforgery(); + return app; + } + + private static string? UserOf(HttpContext ctx) => + ctx.User.Identity?.IsAuthenticated == true && ctx.User.FindFirstValue(ClaimTypes.NameIdentifier) is { Length: > 0 } id ? id : null; + + // Responses carry a body even for errors: otherwise the status-code page would replace them. + private static IResult Error(string code, int status) => Results.Json(new { error = code }, statusCode: status); + + private static IResult Download(HttpContext ctx, string fileName, string type, Func encode, Func make) + { + if (UserOf(ctx) is not { } user) return Error("unauthorized", StatusCodes.Status401Unauthorized); + ctx.Response.Headers.CacheControl = "no-store"; + return Results.File(encode(make(user)), type, fileName); + } + + private static async Task ImportAsync(HttpContext ctx, DataTransfer data, CancellationToken ct) + { + if (UserOf(ctx) is not { } user) return Error("unauthorized", StatusCodes.Status401Unauthorized); + ctx.Response.Headers.CacheControl = "no-store"; + + // Neither type can be sent by a cross-site form, and a cross-site fetch with one needs CORS approval + // that this app never gives: that, with SameSite cookies, is the CSRF defence. + var type = ctx.Request.ContentType?.Split(';')[0].Trim(); + if (!string.Equals(type, "application/octet-stream", StringComparison.OrdinalIgnoreCase) + && !string.Equals(type, "application/json", StringComparison.OrdinalIgnoreCase)) + return Error("invalid", StatusCodes.Status415UnsupportedMediaType); + if (ctx.Request.ContentLength > DataTransfer.MaxBytes) return Error("tooLarge", StatusCodes.Status413PayloadTooLarge); + + var limit = ctx.Features.Get(); + if (limit is { IsReadOnly: false }) limit.MaxRequestBodySize = DataTransfer.MaxBytes; + + try + { + using var buffer = new MemoryStream(); + var chunk = new byte[81920]; + int n; + while ((n = await ctx.Request.Body.ReadAsync(chunk, ct)) > 0) + { + if (buffer.Length + n > DataTransfer.MaxBytes) return Error("tooLarge", StatusCodes.Status413PayloadTooLarge); + buffer.Write(chunk, 0, n); + } + var report = await Task.Run(() => data.Import(user, buffer.ToArray()), ct); + return Results.Json(new { added = report.Added, alreadyHere = report.AlreadyHere, skipped = report.Skipped }); + } + catch (ImportException ex) + { + return ex.Problem switch + { + ImportProblem.TooLarge => Error("tooLarge", StatusCodes.Status413PayloadTooLarge), + ImportProblem.Busy => Error("busy", StatusCodes.Status429TooManyRequests), + _ => Error("invalid", StatusCodes.Status422UnprocessableEntity), + }; + } + catch (BadHttpRequestException) + { + return Error("tooLarge", StatusCodes.Status413PayloadTooLarge); + } + } +} diff --git a/Queueify.Web/Services/DataTransfer.cs b/Queueify.Web/Services/DataTransfer.cs new file mode 100644 index 0000000..fa357d1 --- /dev/null +++ b/Queueify.Web/Services/DataTransfer.cs @@ -0,0 +1,268 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Microsoft.Data.Sqlite; +using Queueify.Models; +using Queueify.Services; +using Queueify.Web.Storage; + +namespace Queueify.Web.Services; + +public enum ImportProblem { Invalid, TooLarge, Busy } + +public sealed class ImportException(ImportProblem problem) : Exception(problem.ToString()) +{ + public ImportProblem Problem { get; } = problem; +} + +/// Albums that were not here before. +/// Albums already here (an older or equal copy, or one the user deleted here). +/// Rows that could not be used (no title, no date, deleted in the file, odd values). +public sealed record ImportReport(int Added, int AlreadyHere, int Skipped); + +/// +/// Backup and restore of a user's queue: JSON and CSV out; the desktop's queueify.db or an exported JSON in. +/// An upload is untrusted. A database is copied to a private temp file, opened read-only with the schema +/// distrusted, checked to hold a real items table, and read row by row with every value cut and +/// range-checked; it is never attached to a live database. What survives goes in through . +/// +public sealed partial class DataTransfer(UserStores stores) +{ + public const int MaxBytes = 25 * 1024 * 1024; + public const int MaxRows = 20_000; + private const int MaxText = 500; + private const string Format = "queueify-export"; + private static readonly byte[] SqliteMagic = "SQLite format 3\0"u8.ToArray(); + + // ── export ── + + public string ExportJson(string userId) + { + var albums = stores.QueueOf(userId).LoadAll().OrderBy(i => i.AddedAt).Select(i => new SyncAlbum( + i.Uid, i.Artist, i.Album, i.Year, i.Source, i.CoverUrl, i.SpotifyId, i.TidalId, i.AddedAt, i.ListenedAt, i.Rating, i.UpdatedAt, false)); + return JsonSerializer.Serialize(new { format = Format, version = 1, albums }, new JsonSerializerOptions(JsonSerializerDefaults.Web)); + } + + public string ExportCsv(string userId) + { + var csv = new StringBuilder("artist,album,year,source,added,listened,rating,spotify_id,tidal_id,uid\r\n"); + foreach (var i in stores.QueueOf(userId).LoadAll().OrderBy(i => i.AddedAt)) + { + csv.AppendJoin(',', + Cell(i.Artist), Cell(i.Album), i.Year?.ToString(CultureInfo.InvariantCulture) ?? "", Cell(i.Source ?? ""), + i.AddedAt.ToString("O", CultureInfo.InvariantCulture), i.ListenedAt?.ToString("O", CultureInfo.InvariantCulture) ?? "", + i.Rating >= 0 ? i.Rating.ToString(CultureInfo.InvariantCulture) : "", Cell(i.SpotifyId ?? ""), Cell(i.TidalId ?? ""), Cell(i.Uid)); + csv.Append("\r\n"); + } + return csv.ToString(); + } + + /// + /// One CSV cell. A text starting with = + - @ (or a tab or return) would run as a formula when the file is + /// opened in a spreadsheet, so it gets a leading apostrophe, which spreadsheets show as plain text. + /// + private static string Cell(string text) + { + if (text.Length > 0 && text[0] is '=' or '+' or '-' or '@' or '\t' or '\r') text = "'" + text; + return text.AsSpan().IndexOfAny(",\"\r\n") >= 0 || text.StartsWith(' ') || text.EndsWith(' ') + ? "\"" + text.Replace("\"", "\"\"") + "\"" + : text; + } + + // ── import ── + + /// Reads a queueify.db or an exported JSON, told apart by the first bytes, into the user's queue. + public ImportReport Import(string userId, byte[] upload) + { + if (upload.Length > MaxBytes) throw new ImportException(ImportProblem.TooLarge); + + // One import per user at a time: a second one (a retry after a slow answer) is turned away, not interleaved. + var gate = Gates.GetOrAdd(userId, _ => new SemaphoreSlim(1, 1)); + if (!gate.Wait(0)) throw new ImportException(ImportProblem.Busy); + try + { + var rows = upload.AsSpan().StartsWith(SqliteMagic) ? ReadDatabase(upload) : ReadJson(upload); + + var items = new List(); + int skipped = 0; + foreach (var row in rows) + { + if (row.Deleted || Build(row) is not { } item) skipped++; + else items.Add(item); + } + // Newest change wins, as in sync, by each album's own last edit; an album deleted here stays deleted. + var (added, here) = stores.QueueOf(userId).MergeBackup(items); + return new ImportReport(added, here, skipped); + } + finally + { + gate.Release(); + } + } + + private readonly System.Collections.Concurrent.ConcurrentDictionary Gates = new(); + + private sealed record Row(string? Uid, string? Artist, string? Album, long? Year, string? Source, string? CoverUrl, string? SpotifyId, + string? TidalId, string? AddedAt, string? ListenedAt, double? Rating, string? UpdatedAt, bool Deleted); + + private static IEnumerable ReadJson(byte[] upload) + { + try + { + var body = upload.AsSpan().StartsWith(Encoding.UTF8.GetPreamble()) ? upload.AsMemory(3) : upload.AsMemory(); // Notepad and PowerShell add a BOM + using var doc = JsonDocument.Parse(body, new JsonDocumentOptions { MaxDepth = 16 }); + var root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object + || !root.TryGetProperty("format", out var format) || format.ValueKind != JsonValueKind.String || format.GetString() != Format + || !root.TryGetProperty("version", out var version) || version.ValueKind != JsonValueKind.Number || version.GetInt32() != 1 + || !root.TryGetProperty("albums", out var albums) || albums.ValueKind != JsonValueKind.Array) + throw new ImportException(ImportProblem.Invalid); + if (albums.GetArrayLength() > MaxRows) throw new ImportException(ImportProblem.TooLarge); + + var rows = new List(); + foreach (var a in albums.EnumerateArray()) + { + if (a.ValueKind != JsonValueKind.Object) { rows.Add(new Row(null, null, null, null, null, null, null, null, null, null, null, null, false)); continue; } + rows.Add(new Row( + Str(a, "uid"), Str(a, "artist"), Str(a, "album"), Num(a, "year") is { } y ? (long)y : null, Str(a, "source"), Str(a, "coverUrl"), + Str(a, "spotifyId"), Str(a, "tidalId"), Str(a, "addedAt"), Str(a, "listenedAt"), Num(a, "rating"), Str(a, "updatedAt"), + a.TryGetProperty("deleted", out var d) && d.ValueKind == JsonValueKind.True)); + } + return rows; + } + catch (Exception ex) when (ex is JsonException or InvalidOperationException or FormatException or OverflowException) + { + throw new ImportException(ImportProblem.Invalid); + } + } + + private static string? Str(JsonElement o, string name) => + o.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String ? Cut(v.GetString()) : null; + + private static double? Num(JsonElement o, string name) => + o.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetDouble(out var d) ? d : null; + + private static List ReadDatabase(byte[] upload) + { + // Our own file name in the temp folder, so nothing the upload says picks a path. + var path = Path.Combine(Path.GetTempPath(), $"queueify-import-{Guid.NewGuid():N}.db"); + try + { + using (var file = PrivateFile.CreateNew(path)) file.Write(upload); + + // immutable: no journal or side files are looked for or created; read-only: nothing can be written. + var uri = "file:" + path.Replace('\\', '/').Replace("%", "%25").Replace("?", "%3f").Replace("#", "%23"); + var connection = new SqliteConnectionStringBuilder { DataSource = uri + "?immutable=1", Mode = SqliteOpenMode.ReadOnly, Pooling = false }; + using var db = new SqliteConnection(connection.ToString()); + db.Open(); + Run(db, "PRAGMA trusted_schema = OFF"); + Run(db, "PRAGMA query_only = ON"); + + using (var kind = db.CreateCommand()) + { + kind.CommandText = "SELECT type, sql FROM sqlite_master WHERE name = 'items' COLLATE NOCASE"; + using var r = kind.ExecuteReader(); + // A real table only: a view or a virtual table could run anything when read. + if (!r.Read() || r.GetString(0) != "table" || (r.IsDBNull(1) ? "" : r.GetString(1)).Contains("VIRTUAL", StringComparison.OrdinalIgnoreCase)) + throw new ImportException(ImportProblem.Invalid); + } + + var columns = new HashSet(StringComparer.OrdinalIgnoreCase); + using (var info = db.CreateCommand()) + { + info.CommandText = "PRAGMA table_xinfo(items)"; + using var r = info.ExecuteReader(); + while (r.Read()) + { + // hidden != 0 marks generated columns: their expressions run on every read (a few bytes of file + // can ask for gigabytes of memory), so a table that has one is refused. + if (r.GetInt64(6) != 0) throw new ImportException(ImportProblem.Invalid); + columns.Add(r.GetString(1)); + } + } + if (!columns.IsSupersetOf(["artist", "album", "added_at"])) throw new ImportException(ImportProblem.Invalid); + + string Text(string c) => columns.Contains(c) ? $"substr(CAST({c} AS TEXT), 1, {MaxText})" : "NULL"; + string Number(string c) => columns.Contains(c) ? $"CASE WHEN typeof({c}) IN ('integer','real') THEN {c} END" : "NULL"; + + using var cmd = db.CreateCommand(); + cmd.CommandText = $"SELECT {Text("uid")}, {Text("artist")}, {Text("album")}, {Number("year")}, {Text("source")}, {Text("cover_url")}, " + + $"{Text("spotify_id")}, {Text("tidal_id")}, {Text("added_at")}, {Text("listened_at")}, {Number("rating")}, {Text("updated_at")}, {Number("deleted")} " + + $"FROM main.items LIMIT {MaxRows + 1}"; + var rows = new List(); + using var reader = cmd.ExecuteReader(); + while (reader.Read()) + { + if (rows.Count == MaxRows) throw new ImportException(ImportProblem.TooLarge); + string? S(int i) => reader.IsDBNull(i) ? null : reader.GetString(i); + rows.Add(new Row(S(0), S(1), S(2), reader.IsDBNull(3) ? null : (long)reader.GetDouble(3), S(4), S(5), S(6), S(7), S(8), S(9), + reader.IsDBNull(10) ? null : reader.GetDouble(10), S(11), !reader.IsDBNull(12) && reader.GetDouble(12) != 0)); + } + return rows; + } + catch (SqliteException) + { + throw new ImportException(ImportProblem.Invalid); + } + finally + { + try { File.Delete(path); } catch (IOException) { } catch (UnauthorizedAccessException) { } + } + } + + private static void Run(SqliteConnection db, string sql) + { + using var cmd = db.CreateCommand(); + cmd.CommandText = sql; + cmd.ExecuteNonQuery(); + } + + // ── one row to one album ── + + private static BacklogItem? Build(Row row) + { + var artist = Tidy(row.Artist); + var album = Tidy(row.Album); + if (artist.Length == 0 && album.Length == 0) return null; + if (ParseDate(row.AddedAt) is not { } added) return null; + + return new BacklogItem + { + Uid = SafeId(row.Uid, 64) ?? Fingerprint(artist, album, added), + Artist = artist, + Album = album, + Year = AlbumYear.OrNull(row.Year), + Source = Tidy(row.Source) is { Length: > 0 } source ? source : null, + CoverUrl = row.CoverUrl is { } cover && cover.StartsWith("https://", StringComparison.OrdinalIgnoreCase) && Uri.TryCreate(cover, UriKind.Absolute, out _) ? cover : null, + SpotifyId = SafeId(row.SpotifyId, 64), + TidalId = SafeId(row.TidalId, 64), + AddedAt = added, + // The album's own last edit (never in the future, so it can't beat real edits); its added time when the file has none. + UpdatedAt = new[] { ParseDate(row.UpdatedAt) ?? added, DateTime.UtcNow }.Min().ToUniversalTime(), + ListenedAt = ParseDate(row.ListenedAt), + Rating = row.Rating is -1 or (>= 0 and <= 5) ? row.Rating.Value : -1, + }; + } + + private static string? Cut(string? s) => s is null ? null : s.Length > MaxText ? s[..MaxText] : s; + + /// No control characters, no stray spaces, at most 500 characters. + private static string Tidy(string? s) => s is null ? "" : new string(Cut(s)!.Where(c => !char.IsControl(c)).ToArray()).Trim(); + + private static string? SafeId(string? s, int max) => s is not null && s.Length <= max && IdShape().IsMatch(s) ? s : null; + + /// The same album in the same file always gets the same id, so importing it twice never duplicates. + private static string Fingerprint(string artist, string album, DateTime added) => + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes($"{artist}\n{album}\n{added.ToString("O", CultureInfo.InvariantCulture)}")))[..32].ToLowerInvariant(); + + /// A date with no zone is taken as UTC, so the server's time zone never changes what an import means. + private static DateTime? ParseDate(string? s) => + s is not null && DateTime.TryParse(s, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var d) && d.Year is >= 1950 and <= 2999 + ? (d.Kind == DateTimeKind.Unspecified ? DateTime.SpecifyKind(d, DateTimeKind.Utc) : d) + : null; + + [GeneratedRegex("^[A-Za-z0-9_:.-]+$")] + private static partial Regex IdShape(); +} diff --git a/Queueify.Web/Services/Notice.cs b/Queueify.Web/Services/Notice.cs new file mode 100644 index 0000000..fe972a7 --- /dev/null +++ b/Queueify.Web/Services/Notice.cs @@ -0,0 +1,4 @@ +namespace Queueify.Web.Services; + +/// A one-line result shown under a control; errors get a mark as well as a colour. +public sealed record Notice(string Text, bool IsError = false); diff --git a/Queueify.Web/Services/PreferencesStore.cs b/Queueify.Web/Services/PreferencesStore.cs new file mode 100644 index 0000000..3e86b64 --- /dev/null +++ b/Queueify.Web/Services/PreferencesStore.cs @@ -0,0 +1,67 @@ +using System.Collections.Concurrent; +using System.Text.Json; +using Queueify.Web.Storage; + +namespace Queueify.Web.Services; + +/// What a user picked for how the app looks and reads photos; per user, never synced with PCs. +/// "system", "light" or "dark". +/// "system", "en" or "es". +/// "auto", "es" or "en". +/// The quick tour has been shown once. +public sealed record Preferences(string Theme, string Language, string OcrLanguage, bool TourSeen) +{ + public static Preferences Default { get; } = new("system", "system", "auto", false); + + public static readonly string[] Themes = ["system", "light", "dark"]; + public static readonly string[] Languages = ["system", "en", "es"]; + public static readonly string[] OcrLanguages = ["auto", "es", "en"]; + + public bool IsValid => Themes.Contains(Theme) && Languages.Contains(Language) && OcrLanguages.Contains(OcrLanguage); +} + +/// prefs.json in the user's folder. Anything unreadable or out of range reads as the default. +public sealed class PreferencesStore(UserStores stores) +{ + // Every signed-in request asks for the language and theme, so the parsed file is kept and trusted for as long as + // its size and time stamp are the ones it was read at. That still sees a save, a deletion or an edit from outside. + private readonly ConcurrentDictionary _cache = new(); + + public Preferences Load(string userId) + { + try + { + var path = stores.FileOf(userId, "prefs.json"); + var info = new FileInfo(path); + if (!info.Exists) { _cache.TryRemove(path, out _); return Preferences.Default; } + if (_cache.TryGetValue(path, out var cached) && cached.Ticks == info.LastWriteTimeUtc.Ticks && cached.Length == info.Length) return cached.Value; + + var read = JsonSerializer.Deserialize(File.ReadAllText(path)) ?? Preferences.Default; + var value = new Preferences( + Pick(read.Theme, Preferences.Themes, "system"), + Pick(read.Language, Preferences.Languages, "system"), + Pick(read.OcrLanguage, Preferences.OcrLanguages, "auto"), + read.TourSeen); + _cache[path] = (info.LastWriteTimeUtc.Ticks, info.Length, value); + return value; + } + catch (Exception ex) when (ex is JsonException or IOException or NotSupportedException) + { + return Preferences.Default; + } + } + + public void Save(string userId, Preferences preferences) + { + if (!preferences.IsValid) throw new ArgumentException("Not an offered choice.", nameof(preferences)); + var path = stores.FileOf(userId, "prefs.json"); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + // Written beside and moved into place, so a read during a write (another tab) never sees half a file. + var partial = path + "." + Guid.NewGuid().ToString("N") + ".tmp"; + File.WriteAllText(partial, JsonSerializer.Serialize(preferences)); + File.Move(partial, path, overwrite: true); + _cache.TryRemove(path, out _); // the next read parses what was just written + } + + private static string Pick(string? value, string[] choices, string fallback) => value is not null && choices.Contains(value) ? value : fallback; +} diff --git a/Queueify.Web/Services/Prefs.cs b/Queueify.Web/Services/Prefs.cs new file mode 100644 index 0000000..d8a8d59 --- /dev/null +++ b/Queueify.Web/Services/Prefs.cs @@ -0,0 +1,42 @@ +namespace Queueify.Web.Services; + +/// Per-browser choices (language, theme) and the redirects around them; pure, so they are tested directly. +public static class Prefs +{ + public const string LanguageCookie = "qlang"; + public const string ThemeCookie = "qtheme"; + + /// The cookie if it names a translated language; otherwise Spanish when the browser asks for it first. + public static string Language(string? cookie, string? acceptLanguage) + { + if (cookie is "en" or "es") return cookie; + var first = (acceptLanguage ?? "").Split(',', 2)[0].Trim(); + 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. + public static string LocalReturn(string? url) + { + if (string.IsNullOrEmpty(url) || url[0] != '/' || url.Length > 1 && url[1] is '/' or '\\') return "/"; + // Browsers drop tabs and line breaks inside an address, so "//host" would become "//host". + return url.Any(char.IsControl) ? "/" : url; + } + + /// + /// Where to go after signing in with no page asked for: a phone is almost always opened to add an + /// album someone just recommended, so it lands on Add. Anywhere asked for wins. + /// + public static string AfterLogin(string? returnUrl, string? userAgent) + { + if (!string.IsNullOrEmpty(returnUrl)) return returnUrl; + return userAgent?.Contains("Mobi", StringComparison.OrdinalIgnoreCase) == true ? "add" : ""; + } +} diff --git a/Queueify.Web/Services/PrivateFile.cs b/Queueify.Web/Services/PrivateFile.cs new file mode 100644 index 0000000..de46056 --- /dev/null +++ b/Queueify.Web/Services/PrivateFile.cs @@ -0,0 +1,16 @@ +namespace Queueify.Web.Services; + +/// Files that hold one user's data in a shared folder such as the temp folder. +public static class PrivateFile +{ + /// + /// Creates a new file only its owner can read (0600 on Linux and macOS; Windows keeps the profile's own ACL, and + /// setting a Unix mode there throws). Fails if the name exists, so a pre-placed file or link is never reused. + /// + public static FileStream CreateNew(string path) + { + var options = new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write, Share = FileShare.None }; + if (!OperatingSystem.IsWindows()) options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite; + return new FileStream(path, options); + } +} diff --git a/Queueify.Web/Services/PublicUrl.cs b/Queueify.Web/Services/PublicUrl.cs new file mode 100644 index 0000000..eb29273 --- /dev/null +++ b/Queueify.Web/Services/PublicUrl.cs @@ -0,0 +1,17 @@ +namespace Queueify.Web.Services; + +/// +/// The address people reach this server at, from Queueify:PublicBaseUrl. Texts that leave the server (the connect +/// text a PC is given with a token) are built from it, never from the request's Host header, which a misconfigured +/// proxy would let anyone choose. +/// +public static class PublicUrl +{ + /// The configured origin (scheme, host, port), or null when none is set or it would not be safe to hand a token to. + public static string? Of(IConfiguration config) + { + if (!Uri.TryCreate(config["Queueify:PublicBaseUrl"], UriKind.Absolute, out var uri) || uri.UserInfo.Length > 0) return null; + var secure = uri.Scheme == Uri.UriSchemeHttps || (uri.Scheme == Uri.UriSchemeHttp && uri.IsLoopback); + return secure ? uri.GetLeftPart(UriPartial.Authority) : null; + } +} diff --git a/Queueify.Web/Services/QueueifyStorageExtensions.cs b/Queueify.Web/Services/QueueifyStorageExtensions.cs new file mode 100644 index 0000000..cd6585a --- /dev/null +++ b/Queueify.Web/Services/QueueifyStorageExtensions.cs @@ -0,0 +1,23 @@ +namespace Queueify.Web.Services; + +public static class QueueifyStorageExtensions +{ + /// + /// 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/Services/QueueifyUi.cs b/Queueify.Web/Services/QueueifyUi.cs new file mode 100644 index 0000000..eac9c09 --- /dev/null +++ b/Queueify.Web/Services/QueueifyUi.cs @@ -0,0 +1,149 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Components.Server.Circuits; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Identity; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.FluentUI.AspNetCore.Components; +using Queueify.Services; +using Queueify.Web.Data; +using Queueify.Web.Storage; + +namespace Queueify.Web.Services; + +/// Registration of the shell and the two core pages, kept out of Program.cs so the other tracks merge cleanly. +public static class QueueifyUi +{ + /// The first account is the owner; after that, only when the server's configuration opens registration. + public static bool RegistrationOpen(bool allowRegistration, bool anyUserExists) => !anyUserExists || allowRegistration; + + /// + /// Everything comes from this site, except album covers (any https host, as catalogs choose them). Styles allow + /// inline because Fluent's components set them; scripts do not. blob: images are the photo preview, made in the + /// browser from the file the user picked. + /// + public static string ContentSecurityPolicy(string? publicUrl) + { + // 'self' covers the circuit's WebSocket in current browsers; older Safari needs the ws origin spelled out. + var connect = publicUrl is not null && Uri.TryCreate(publicUrl, UriKind.Absolute, out var origin) + ? $"'self' {(origin.Scheme == Uri.UriSchemeHttps ? "wss" : "ws")}://{origin.Authority}" : "'self'"; + return $"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' https: data: blob:; " + + $"font-src 'self' data:; connect-src {connect}; 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 + c.DefaultRequestHeaders.UserAgent.ParseAdd("Queueify"); + }); + services.AddSingleton(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + + // No e-mail goes out from this server, so there is nothing for "confirm your account" to wait for. + services.Configure(o => o.SignIn.RequireConfirmedAccount = false); + services.Replace(ServiceDescriptor.Scoped()); + 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. + /// + /// False for static files and framework scripts, which carry no language or theme. + public static bool NeedsPreferences(PathString path) => + !path.StartsWithSegments("/_framework") && !path.StartsWithSegments("/_content") && !Path.HasExtension(path.Value); + + 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 + // through LocCircuitHandler. Loc keeps it per async flow, so two users never swap languages. + var csp = ContentSecurityPolicy(PublicUrl.Of(app.Configuration)); + app.Use(async (context, next) => + { + context.Response.OnStarting(() => + { + var headers = context.Response.Headers; + headers["Content-Security-Policy"] = csp; + headers["X-Content-Type-Options"] = "nosniff"; + headers["Referrer-Policy"] = "no-referrer"; + return Task.CompletedTask; + }); + var account = NeedsPreferences(context.Request.Path) && 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(); + }); + + // [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 || 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. + 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(); + + return app; + } +} + +/// The language the current circuit speaks; set from the page's cookie when the circuit starts. +public sealed class LanguageState +{ + public string Value { get; set; } = "en"; +} + +/// +/// Runs every call into the circuit (clicks, JS results, navigation) with the circuit's language, because +/// keeps its override per async flow and a circuit has no request to carry it. +/// +public sealed class LocCircuitHandler(LanguageState language) : CircuitHandler +{ + public override Func CreateInboundActivityHandler(Func next) => + async context => + { + using (Loc.Override(language.Value)) await next(context); + }; +} diff --git a/Queueify.Web/Services/RegistrationGate.cs b/Queueify.Web/Services/RegistrationGate.cs new file mode 100644 index 0000000..d2cbdea --- /dev/null +++ b/Queueify.Web/Services/RegistrationGate.cs @@ -0,0 +1,52 @@ +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. "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); + + 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) + { + await OneAtATime.WaitAsync(); + try + { + if (!await IsOpenAsync()) return false; + await create(); + if (await users.Users.AnyAsync()) Mark(); + return true; + } + finally { OneAtATime.Release(); } + } + + 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/Queueify.Web/Services/SettingsService.cs b/Queueify.Web/Services/SettingsService.cs new file mode 100644 index 0000000..a74c7ce --- /dev/null +++ b/Queueify.Web/Services/SettingsService.cs @@ -0,0 +1,107 @@ +using Queueify.Models; +using Queueify.Services; +using Queueify.Web.Storage; + +namespace Queueify.Web.Services; + +/// What the Settings page may know: whether a secret is set, never the secret. +public sealed record SettingsSnapshot(string SpotifyClientId, bool SpotifyConfigured, string TidalClientId, bool TidalConfigured, string PreferredService, string CountryCode); + +/// What the form posts back. An empty secret means "keep the saved one". +public sealed record SettingsEdit(string SpotifyClientId, string SpotifyClientSecret, string TidalClientId, string TidalClientSecret, string PreferredService, string CountryCode) +{ + public static SettingsEdit From(SettingsSnapshot s) => new(s.SpotifyClientId, "", s.TidalClientId, "", s.PreferredService, s.CountryCode); +} + +public enum KeyTestOutcome { Ok, Missing, Rejected, Failed, Unexpected } + +/// The catalog's own text for and . +public sealed record KeyTestResult(KeyTestOutcome Outcome, string? Message = null); + +/// Reads and writes a user's music settings with the same edit rules as the desktop dialog. +public sealed class SettingsService(UserStores stores, Func http) +{ + private const int MaxKeyLength = 300; + + public SettingsSnapshot Snapshot(string userId) + { + var s = stores.LoadSettings(userId).ForSettingsPage(); + return new(s.SpotifyClientId, s.SpotifyConfigured, s.TidalClientId, s.TidalConfigured, s.PreferredService, s.CountryCode); + } + + /// + /// Applies only what differs from (), on top of + /// what is stored now. True when something shared changed. + /// + public bool Save(string userId, SettingsSnapshot opened, SettingsEdit edit) + { + var edited = new AppSettings + { + SpotifyClientId = Clean(edit.SpotifyClientId), + SpotifyClientSecret = Clean(edit.SpotifyClientSecret), + TidalClientId = Clean(edit.TidalClientId), + TidalClientSecret = Clean(edit.TidalClientSecret), + PreferredService = edit.PreferredService, + CountryCode = edit.CountryCode, + }; + if (edited.PreferredService is not (nameof(MusicService.Tidal) or nameof(MusicService.Spotify))) + throw new ArgumentException("Not an offered service.", nameof(edit)); + if (!Countries.Codes.Contains(edited.CountryCode) && edited.CountryCode != opened.CountryCode) + throw new ArgumentException("Not an offered country.", nameof(edit)); + + // The secrets were never sent to the page, so the page's starting point has them empty. + var start = new AppSettings + { + SpotifyClientId = opened.SpotifyClientId, + TidalClientId = opened.TidalClientId, + PreferredService = opened.PreferredService, + CountryCode = opened.CountryCode, + }; + + var current = stores.LoadSettings(userId); + if (!current.ApplyEdits(start, edited)) return false; + current.SharedSettingsUpdatedAt = BacklogStore.Now(); + stores.SaveSettings(userId, current); + return true; + } + + public void RemoveKeys(string userId, MusicService service) + { + var current = stores.LoadSettings(userId); + if (service == MusicService.Spotify) (current.SpotifyClientId, current.SpotifyClientSecret) = ("", ""); + else (current.TidalClientId, current.TidalClientSecret) = ("", ""); + current.SharedSettingsUpdatedAt = BacklogStore.Now(); + stores.SaveSettings(userId, current); + } + + /// Searches the catalog once with the saved keys, so the user learns now whether they work. + public async Task TestAsync(string userId, MusicService service, CancellationToken ct) + { + var settings = stores.LoadSettings(userId); + if (!(service == MusicService.Spotify ? settings.SpotifyConfigured : settings.TidalConfigured)) + return new(KeyTestOutcome.Missing); + + try + { + using var client = http(); + _ = service == MusicService.Spotify + ? await new SpotifyCatalog(client, () => settings).SearchAsync("Abbey Road", ct) + : await new TidalCatalog(client, () => settings).SearchAsync("Abbey Road", ct); + return new(KeyTestOutcome.Ok); + } + catch (CatalogException ex) + { + return new(ex.KeysRejected ? KeyTestOutcome.Rejected : KeyTestOutcome.Failed, ex.Message); + } + catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or System.Text.Json.JsonException or KeyNotFoundException or InvalidOperationException) + { + return new(KeyTestOutcome.Unexpected); + } + } + + private static string Clean(string value) + { + var trimmed = value.Trim(); + return trimmed.Length <= MaxKeyLength ? trimmed : throw new ArgumentException("Too long to be a key.", nameof(value)); + } +} diff --git a/Queueify.Web/Services/Toasts.cs b/Queueify.Web/Services/Toasts.cs new file mode 100644 index 0000000..f87a3dc --- /dev/null +++ b/Queueify.Web/Services/Toasts.cs @@ -0,0 +1,25 @@ +namespace Queueify.Web.Services; + +/// One note at the bottom with an optional Undo (and a rating, right after "listened"), like the desktop app's InfoBar. +public sealed record Toast(string Message, string? ActionText = null, Action? Action = null, Action? Rate = null, bool Warning = false); + +/// The current note for one circuit; a newer note replaces an older one. +public sealed class Toasts +{ + public Toast? Current { get; private set; } + + public event Action? Changed; + + public void Show(Toast toast) + { + Current = toast; + Changed?.Invoke(); + } + + public void Dismiss() + { + if (Current == null) return; + Current = null; + Changed?.Invoke(); + } +} diff --git a/Queueify.Web/Services/TourService.cs b/Queueify.Web/Services/TourService.cs new file mode 100644 index 0000000..4e879a8 --- /dev/null +++ b/Queueify.Web/Services/TourService.cs @@ -0,0 +1,25 @@ +namespace Queueify.Web.Services; + +/// +/// Lets any page ask for the quick tour to run again. The tour component mounted in the layout (or, failing +/// that, on the Help page) listens; only one mounted component shows it, so two never overlap. +/// +public sealed class TourService +{ + private object? _owner; + + public event Action? Replayed; + + public void Replay() => Replayed?.Invoke(); + + /// True for the first component to attach until it detaches. + public bool TryAttach(object component) + { + lock (this) return _owner is null && (_owner = component) is not null; + } + + public void Detach(object component) + { + lock (this) if (ReferenceEquals(_owner, component)) _owner = null; + } +} diff --git a/Queueify.Web/Services/UploadResult.cs b/Queueify.Web/Services/UploadResult.cs new file mode 100644 index 0000000..f8150ca --- /dev/null +++ b/Queueify.Web/Services/UploadResult.cs @@ -0,0 +1,4 @@ +namespace Queueify.Web.Services; + +/// What the browser got back from an upload endpoint: its HTTP status (0 when the request never completed) and body text. +public sealed record UploadResult(int Status, string Body); diff --git a/Queueify.Web/Services/UserQueue.cs b/Queueify.Web/Services/UserQueue.cs new file mode 100644 index 0000000..29618dd --- /dev/null +++ b/Queueify.Web/Services/UserQueue.cs @@ -0,0 +1,186 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Components.Authorization; +using Queueify.Models; +using Queueify.Services; +using Queueify.Web.Storage; + +namespace Queueify.Web.Services; + +/// Who is signed in, as the folder name their data lives under. +public interface IUserContext +{ + Task UserIdAsync(); +} + +public sealed class AuthUserContext(AuthenticationStateProvider auth) : IUserContext +{ + public async Task UserIdAsync() + { + var user = (await auth.GetAuthenticationStateAsync()).User; + return user.Identity?.IsAuthenticated == true ? user.FindFirstValue(ClaimTypes.NameIdentifier) : null; + } +} + +/// +/// The signed-in user's queue for one circuit or request. Every change goes to that user's SQLite file +/// at once; undo re-reads the stored album first so a change made in another tab is never overwritten. +/// +public sealed class UserQueue(UserStores stores, IUserContext user) +{ + private string? _userId; + private BacklogStore? _store; + private List _all = []; + private readonly Dictionary _keys = []; // uid -> normalised search text, worked out once per album + private List? _pending, _heard; + + /// Raised after every change, so the navigation badges and open pages redraw. + public event Action? Changed; + + public IReadOnlyList All => _all; + public IReadOnlyList PendingItems => _pending ??= _all.Where(i => i.IsPending).ToList(); + public IReadOnlyList HeardItems => _heard ??= _all.Where(i => i.IsListened).ToList(); + public int Pending => PendingItems.Count; + public int Heard => HeardItems.Count; + + /// Bumped on every change, so a page can tell whether what it worked out last time is still true. + public int Version { get; private set; } + + /// + /// The albums whose artist, album, magazine or year contain what was typed, as would find them + /// (same normalisation), but from keys kept per album instead of normalising every album on every keystroke. + /// Listened or not and the order are still 's job. + /// + public IReadOnlyList Search(string typed) + { + var words = Matcher.Normalize(typed); + return words.Length == 0 ? _all : _all.Where(i => _keys.TryGetValue(i.Uid, out var key) && key.Contains(words)).ToList(); + } + public bool SignedIn => _userId != null; + + /// Re-reads the queue from the database; nobody signed in means an empty queue. + public async Task LoadAsync() + { + _userId = await user.UserIdAsync(); + _store = _userId == null ? null : stores.QueueOf(_userId); + Settings = _userId == null ? new AppSettings() : stores.LoadSettings(_userId); + Reload(); + } + + /// The user's settings; secrets stay on the server, so callers pass on only what they show. + public AppSettings Settings { get; private set; } = new(); + + /// Which app Play opens when an album is on both; each user chooses, so it is never a static. + public MusicService Preferred => Settings.PreferredService == nameof(MusicService.Spotify) ? MusicService.Spotify : MusicService.Tidal; + + public string? UserId => _userId; + + private BacklogStore Store => _store ?? throw new InvalidOperationException("Nobody is signed in."); + + private void Reload() + { + _all = _store?.LoadAll() ?? []; + _keys.Clear(); + foreach (var item in _all) _keys[item.Uid] = KeyOf(item); + Touch(); + } + + private static string KeyOf(BacklogItem i) => Matcher.Normalize($"{i.Artist} {i.Album} {i.Source} {i.Year}"); + + private void Touch() + { + Version++; + _pending = _heard = null; + Changed?.Invoke(); + } + + /// Shows the stored version of one album (or none, if it is gone), and tells the pages. + private void Show(string uid, BacklogItem? stored) + { + var at = _all.FindIndex(i => i.Uid == uid); + if (stored is null or { Deleted: true }) + { + if (at >= 0) _all.RemoveAt(at); + _keys.Remove(uid); + } + else + { + if (at >= 0) _all[at] = stored; else _all.Add(stored); + _keys[uid] = KeyOf(stored); + } + Touch(); + } + + public BacklogItem Add(BacklogItem item, string source) + { + var magazine = source.Trim(); + item.Source = magazine.Length > 0 ? magazine : null; + item.AddedAt = DateTime.Now; + Store.Insert(item); + + // Read fresh: the Settings page may have saved new keys since this circuit loaded. + var settings = stores.LoadSettings(_userId!); + if (settings.LastSource != magazine) + { + settings.LastSource = magazine; + stores.SaveSettings(_userId!, settings); + Settings = settings; + } + Show(item.Uid, item); + return item; + } + + /// Takes a freshly added album back out (the Undo on "Added …"). + public void Remove(BacklogItem item) + { + if (Store.FindByUid(item.Uid) is { Deleted: false } current) Store.Delete(current); + Show(item.Uid, null); + } + + // Every change starts from the stored album, not from the copy a page drew earlier: another tab may have + // deleted, rated or listened to it since, and writing the old copy back would undo that. Only that one album is + // updated in memory afterwards; reading the whole queue again is what LoadAsync is for. + public Action SetListened(BacklogItem item, bool listened) + { + if (Store.FindByUid(item.Uid) is not { Deleted: false } current || current.IsListened == listened) + { + Show(item.Uid, Store.FindByUid(item.Uid)); + return () => { }; + } + var before = current.ListenedAt; + var stamp = listened ? DateTime.Now : (DateTime?)null; + current.ListenedAt = stamp; + Store.Update(current); + Show(item.Uid, current); + return () => + { + if (Store.FindByUid(item.Uid) is not { Deleted: false } now || now.ListenedAt != stamp) return; + now.ListenedAt = before; + Store.Update(now); + Show(item.Uid, now); + }; + } + + public void Rate(BacklogItem item, double rating) + { + var current = Store.FindByUid(item.Uid); + if (current is { Deleted: false } && current.Rating != rating) + { + current.Rating = rating; + Store.Update(current); + } + Show(item.Uid, current); + } + + public Action Delete(BacklogItem item) + { + Store.Delete(Store.FindByUid(item.Uid) ?? item); + Show(item.Uid, null); + return () => + { + // The stored copy may be newer, or already gone after an upload (then it is created again). + var back = Store.FindByUid(item.Uid) ?? item; + Store.Restore(back); + Show(item.Uid, back); + }; + } +} diff --git a/Queueify.Web/Services/Validation.cs b/Queueify.Web/Services/Validation.cs new file mode 100644 index 0000000..0531b96 --- /dev/null +++ b/Queueify.Web/Services/Validation.cs @@ -0,0 +1,50 @@ +using System.ComponentModel.DataAnnotations; +using Microsoft.AspNetCore.Identity; +using Queueify.Services; + +namespace Queueify.Web.Services; + +// Form messages that DataAnnotations would write in English: the same rules, said in the user's language. + +public sealed class LocRequiredAttribute : RequiredAttribute +{ + public override string FormatErrorMessage(string name) => Loc.T("web.val.required"); +} + +public sealed class LocEmailAttribute : ValidationAttribute +{ + private static readonly EmailAddressAttribute Rule = new(); + public override bool IsValid(object? value) => Rule.IsValid(value); + public override string FormatErrorMessage(string name) => Loc.T("web.val.email"); +} + +public sealed class LocStringLengthAttribute(int maximum) : StringLengthAttribute(maximum) +{ + public override string FormatErrorMessage(string name) => Loc.F("web.val.length", MinimumLength, MaximumLength); +} + +public sealed class LocCompareAttribute(string other) : CompareAttribute(other) +{ + public override string FormatErrorMessage(string name) => Loc.T("web.val.match"); +} + +/// Identity's own error texts (password rules, duplicate email…) in the user's language. +public sealed class LocalizedIdentityErrors : IdentityErrorDescriber +{ + private static IdentityError E(string code, string key, params object[] args) => new() { Code = code, Description = Loc.F(key, args) }; + + public override IdentityError DefaultError() => E(nameof(DefaultError), "web.idn.default"); + public override IdentityError PasswordTooShort(int length) => E(nameof(PasswordTooShort), "web.idn.short", length); + public override IdentityError PasswordRequiresNonAlphanumeric() => E(nameof(PasswordRequiresNonAlphanumeric), "web.idn.symbol"); + public override IdentityError PasswordRequiresDigit() => E(nameof(PasswordRequiresDigit), "web.idn.digit"); + public override IdentityError PasswordRequiresLower() => E(nameof(PasswordRequiresLower), "web.idn.lower"); + public override IdentityError PasswordRequiresUpper() => E(nameof(PasswordRequiresUpper), "web.idn.upper"); + public override IdentityError PasswordRequiresUniqueChars(int uniqueChars) => E(nameof(PasswordRequiresUniqueChars), "web.idn.unique", uniqueChars); + public override IdentityError PasswordMismatch() => E(nameof(PasswordMismatch), "web.idn.mismatch"); + public override IdentityError DuplicateUserName(string userName) => E(nameof(DuplicateUserName), "web.idn.taken", userName); + public override IdentityError DuplicateEmail(string email) => E(nameof(DuplicateEmail), "web.idn.taken", email); + public override IdentityError InvalidEmail(string? email) => E(nameof(InvalidEmail), "web.idn.email"); + public override IdentityError InvalidUserName(string? userName) => E(nameof(InvalidUserName), "web.idn.email"); + public override IdentityError UserLockoutNotEnabled() => E(nameof(UserLockoutNotEnabled), "web.idn.default"); + public override IdentityError LoginAlreadyAssociated() => E(nameof(LoginAlreadyAssociated), "web.idn.linked"); +} diff --git a/Queueify.Web/Storage/UserStores.cs b/Queueify.Web/Storage/UserStores.cs new file mode 100644 index 0000000..13b9037 --- /dev/null +++ b/Queueify.Web/Storage/UserStores.cs @@ -0,0 +1,95 @@ +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. +/// 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) + { + // An allowlist: "." or a name the server keeps for itself must never become a user folder. + if (userId.Length is 0 or > 64 || userId.Any(c => !(char.IsAsciiLetterOrDigit(c) || c is '-' or '_')) + || userId.Equals("keys", StringComparison.OrdinalIgnoreCase)) + throw new ArgumentException("Not a valid user id.", nameof(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 string QueuePathOf(string userId) => Path.Combine(FolderOf(userId), "queueify.db"); + + public BacklogStore QueueOf(string userId) => new(QueuePathOf(userId)); + + 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) + { + // 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")); + } + + /// Removes everything stored for the user: queue, settings, secrets, preferences. + public void Delete(string userId) + { + var folder = FolderOf(userId); + if (Directory.Exists(folder)) Directory.Delete(folder, recursive: true); + } + + 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..c0ef2e4 --- /dev/null +++ b/Queueify.Web/Sync/PersonalAccessToken.cs @@ -0,0 +1,31 @@ +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; } + + /// 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 => + { + 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..1a102a2 --- /dev/null +++ b/Queueify.Web/Sync/PersonalAccessTokens.cs @@ -0,0 +1,87 @@ +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. +/// A short-lived context per call: in a Blazor circuit a scoped context would live for hours and pile up tracked rows. +public sealed class PersonalAccessTokens(IDbContextFactory contexts, 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, CancellationToken ct = default) + { + await using var db = await contexts.CreateDbContextAsync(ct); + name = name.Trim(); + if (name.Length > MaxNameLength) name = name[..MaxNameLength]; + 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, SecurityStamp = stamp, + }; + db.PersonalAccessTokens.Add(row); + await db.SaveChangesAsync(ct); + return new NewToken(row, token); + } + + public async Task> ListAsync(string userId, CancellationToken ct = default) + { + await using var db = await contexts.CreateDbContextAsync(ct); + return 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, CancellationToken ct = default) + { + await using var db = await contexts.CreateDbContextAsync(ct); + 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 (unknown, revoked, or older than the owner's last security-stamp change). + public async Task ValidateAsync(string token, CancellationToken ct = default) + { + await using var db = await contexts.CreateDbContextAsync(ct); + if (!LooksLikeToken(token)) return null; + var hash = Hash(token); + 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), ct); + } + return row.UserId; + } + + private static string Base64Url(byte[] bytes) => Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); +} 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/SyncEngine.cs b/Queueify.Web/Sync/SyncEngine.cs new file mode 100644 index 0000000..d7fb655 --- /dev/null +++ b/Queueify.Web/Sync/SyncEngine.cs @@ -0,0 +1,329 @@ +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 user's queue would hold more rows than the server allows. +public sealed class SyncQuotaException : Exception; + +/// +/// 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, int maxRowsPerUser = SyncEngine.DefaultMaxRowsPerUser) +{ + public const int DefaultMaxRowsPerUser = 50_000; + public const int MaxAlbums = 1000; + public const int MaxText = 500; + public static readonly TimeSpan TombstoneLifetime = TimeSpan.FromDays(90); + 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). A caller that gave up while waiting for its turn costs nothing. + public async Task RunAsync(string userId, SyncRequest request, CancellationToken ct = default) + { + var clean = Clean(request); + if (clean == null) return null; + + var gate = GateOf(userId); + await gate.WaitAsync(ct); + try { return await Task.Run(() => Apply(userId, clean), CancellationToken.None); } + finally { gate.Release(); } + } + + private SemaphoreSlim GateOf(string userId) => _gates.GetOrAdd(userId, _ => new SemaphoreSlim(1, 1)); + + /// + /// Removes everything stored for the user, once a running sync for them is finished, and forgets that their file was + /// prepared: the pages create a plain desktop-schema file again on the next visit, and the next sync must add the + /// server columns to that one. + /// + public async Task DeleteUserDataAsync(string userId, CancellationToken ct = default) + { + var gate = GateOf(userId); + await gate.WaitAsync(ct); + try + { + _prepared.TryRemove(stores.QueuePathOf(userId), out _); + stores.Delete(userId); + } + 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), AlbumYear.OrNull(a.Year), + 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; + + // A deletion is kept so the other PCs delete the album too; after this long every PC that syncs has had it. + // A PC that stayed offline longer may keep an album that was deleted elsewhere. + var cutoff = clock.GetUtcNow().UtcDateTime - TombstoneLifetime; + Execute(db, "DELETE FROM items WHERE deleted = 1 AND dirty = 0 AND server_time < $t AND updated_at < $u", + ("$t", cutoff.Ticks), ("$u", Stamp(cutoff))); + 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. (On an exact tie the PC keeps its own row, because + // BacklogStore.ApplyRemote only takes strictly newer ones; microsecond ties are rare.) + 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)); + } + + // Disposing the transaction without a commit undoes the whole request. + using (var count = db.CreateCommand()) + { + count.CommandText = "SELECT COUNT(*) FROM items"; + if ((long)count.ExecuteScalar()! > maxRowsPerUser) throw new SyncQuotaException(); + } + + 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..6fda3cf --- /dev/null +++ b/Queueify.Web/Sync/SyncExtensions.cs @@ -0,0 +1,152 @@ +using System.Security.Claims; +using System.Text.Json; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.Hosting; +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(Queueify.Web.Services.QueueifyStorageExtensions.DataRootOf( + sp.GetRequiredService(), sp.GetRequiredService()))); + + 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(sp => new SyncEngine(sp.GetRequiredService(), sp.GetRequiredService(), + sp.GetRequiredService().GetValue("Queueify:Sync:MaxAlbumsPerUser", SyncEngine.DefaultMaxRowsPerUser))); + services.AddSingleton(); + services.AddScoped(); + services.AddScoped(); + services.AddHostedService(); + services.AddTransient(); + + 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); + http.Response.Headers.CacheControl = "no-store"; + 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; + try + { + while ((read = await http.Request.Body.ReadAsync(buffer, http.RequestAborted)) > 0) + { + body.Write(buffer, 0, read); + if (body.Length > limits.MaxBodyBytes) return Results.StatusCode(StatusCodes.Status413PayloadTooLarge); + } + } + catch (BadHttpRequestException e) + { + // Kestrel enforces the cap itself on chunked bodies; its answer must not reach the error page. + return Results.StatusCode(e.StatusCode); + } + catch (OperationCanceledException) + { + return Results.StatusCode(499); // the client went away; nobody reads this answer + } + + 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); + + SyncResponse? response; + try { response = await engine.RunAsync(userId, request, http.RequestAborted); } + catch (SyncQuotaException) { return Results.StatusCode(StatusCodes.Status413PayloadTooLarge); } + catch (OperationCanceledException) { return Results.StatusCode(499); } + return response == null + ? Results.StatusCode(StatusCodes.Status400BadRequest) + : Results.Text(JsonSerializer.Serialize(response, SyncJson.Default.SyncResponse), "application/json"); + } +} + +/// +/// Trusts X-Forwarded-For/Proto only from the proxies listed in Queueify:Proxy:KnownProxies (addresses) and +/// Queueify:Proxy:KnownNetworks (CIDR), so the rate limit sees real client addresses behind a reverse proxy. +/// With neither set, the headers are not trusted at all. +/// +internal sealed class ProxyStartupFilter(IConfiguration configuration) : IStartupFilter +{ + public Action Configure(Action next) => app => + { + var section = configuration.GetSection("Queueify:Proxy"); + var proxies = section.GetSection("KnownProxies").Get() ?? []; + var networks = section.GetSection("KnownNetworks").Get() ?? []; + if (proxies.Length + networks.Length > 0) + { + var options = new Microsoft.AspNetCore.Builder.ForwardedHeadersOptions + { + ForwardedHeaders = Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedFor + | Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedProto, + ForwardLimit = section.GetValue("ForwardLimit", 1), + }; + options.KnownProxies.Clear(); + options.KnownIPNetworks.Clear(); + foreach (var p in proxies) options.KnownProxies.Add(System.Net.IPAddress.Parse(p)); + foreach (var n in networks) options.KnownIPNetworks.Add(System.Net.IPNetwork.Parse(n)); + app.UseForwardedHeaders(options); + } + next(app); + }; +} + +/// 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..1887453 --- /dev/null +++ b/Queueify.Web/Sync/TokenAuthentication.cs @@ -0,0 +1,83 @@ +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(), Context.RequestAborted); + 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); + if (Context.Items.ContainsKey(ThrottledKey)) + { + Response.StatusCode = StatusCodes.Status429TooManyRequests; + Response.Headers.RetryAfter = "60"; // the limiter's window is a minute + } + else + { + Response.StatusCode = StatusCodes.Status401Unauthorized; + Response.Headers.WWWAuthenticate = "Bearer"; + } + return Task.CompletedTask; + } + + protected override Task HandleForbiddenAsync(AuthenticationProperties properties) + { + SyncExtensions.Quiet(Context); + Response.StatusCode = StatusCodes.Status401Unauthorized; + Response.Headers.WWWAuthenticate = "Bearer"; + 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", 4 * 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/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..10f68b8 --- /dev/null +++ b/Queueify.Web/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/Queueify.Web/wwwroot/favicon.png b/Queueify.Web/wwwroot/favicon.png new file mode 100644 index 0000000..8422b59 Binary files /dev/null and b/Queueify.Web/wwwroot/favicon.png differ diff --git a/Queueify.Web/wwwroot/icons/apple-touch-icon.png b/Queueify.Web/wwwroot/icons/apple-touch-icon.png new file mode 100644 index 0000000..d5741b4 Binary files /dev/null and b/Queueify.Web/wwwroot/icons/apple-touch-icon.png differ diff --git a/Queueify.Web/wwwroot/icons/icon-192.png b/Queueify.Web/wwwroot/icons/icon-192.png new file mode 100644 index 0000000..c8291f1 Binary files /dev/null and b/Queueify.Web/wwwroot/icons/icon-192.png differ diff --git a/Queueify.Web/wwwroot/icons/icon-512.png b/Queueify.Web/wwwroot/icons/icon-512.png new file mode 100644 index 0000000..e29ded3 Binary files /dev/null and b/Queueify.Web/wwwroot/icons/icon-512.png differ diff --git a/Queueify.Web/wwwroot/icons/icon-maskable-512.png b/Queueify.Web/wwwroot/icons/icon-maskable-512.png new file mode 100644 index 0000000..6db56fa Binary files /dev/null and b/Queueify.Web/wwwroot/icons/icon-maskable-512.png differ diff --git a/Queueify.Web/wwwroot/icons/icon.svg b/Queueify.Web/wwwroot/icons/icon.svg new file mode 100644 index 0000000..08885ce --- /dev/null +++ b/Queueify.Web/wwwroot/icons/icon.svg @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Queueify.Web/wwwroot/js/queueify-upload.js b/Queueify.Web/wwwroot/js/queueify-upload.js new file mode 100644 index 0000000..85decc9 --- /dev/null +++ b/Queueify.Web/wwwroot/js/queueify-upload.js @@ -0,0 +1,62 @@ +// Sends a chosen, dropped or pasted file to one of the app's upload endpoints. The browser keeps the +// File; C# only learns its name, size and a local preview address, and asks for the upload by id. +const files = new Map(); +let counter = 0; + +export function watch(inputs, zone, dotnet) { + const take = (file) => { + if (!file) return; + files.clear(); + const id = String(++counter); + files.set(id, file); + const preview = file.type.startsWith('image/') ? URL.createObjectURL(file) : null; + dotnet.invokeMethodAsync('OnFileChosen', id, file.name, file.size, preview); + }; + + const onChange = (e) => { take(e.target.files[0]); e.target.value = ''; }; + for (const input of inputs) input.addEventListener('change', onChange); + + const onOver = (e) => { e.preventDefault(); }; + const onDrop = (e) => { e.preventDefault(); take(e.dataTransfer?.files?.[0]); }; + const onPaste = (e) => { + const item = [...(e.clipboardData?.items ?? [])].find((i) => i.type.startsWith('image/')); + if (item) take(item.getAsFile()); + }; + if (zone) { + zone.addEventListener('dragover', onOver); + zone.addEventListener('drop', onDrop); + document.addEventListener('paste', onPaste); + } + + return { + dispose() { + for (const input of inputs) input.removeEventListener('change', onChange); + if (zone) { + zone.removeEventListener('dragover', onOver); + zone.removeEventListener('drop', onDrop); + document.removeEventListener('paste', onPaste); + } + }, + }; +} + +export async function send(id, url, contentType) { + const file = files.get(id); + if (!file) return { status: 0, body: '' }; + try { + const response = await fetch(url, { + method: 'POST', + body: file, + credentials: 'same-origin', + headers: { 'Content-Type': contentType || (file.type.startsWith('image/') ? file.type : 'image/jpeg') }, + }); + return { status: response.status, body: await response.text() }; + } catch { + return { status: 0, body: '' }; + } +} + +export function release(id, previewUrl) { + files.delete(id); + if (previewUrl) URL.revokeObjectURL(previewUrl); +} 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..7dd42a9 --- /dev/null +++ b/Queueify.Web/wwwroot/offline.html @@ -0,0 +1,40 @@ + + + + + +Queueify + + + + +
+
Queueify
+
+

You're offline

+

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

+ +
+
+ + + \ No newline at end of file diff --git a/Queueify.Web/wwwroot/queueify.css b/Queueify.Web/wwwroot/queueify.css new file mode 100644 index 0000000..1b9e502 --- /dev/null +++ b/Queueify.Web/wwwroot/queueify.css @@ -0,0 +1,473 @@ +/* Queueify web: "liner notes". Palette and rules are explained in docs/WEB_DESIGN.md. */ + +:root { + color-scheme: light dark; + --q-paper: light-dark(#F7F4EF, #14111B); + --q-sleeve: light-dark(#FFFFFF, #1E1A28); + --q-sleeve-2: light-dark(#F1EDE6, #272235); + --q-ink: light-dark(#1B1724, #F2EFF8); + --q-muted: light-dark(#665F75, #A9A3B8); + --q-violet: light-dark(#6544E6, #6B4CF0); + --q-violet-hover: light-dark(#5030C4, #7B5CFF); + --q-violet-text: light-dark(#5030C4, #B5A2FF); + --q-violet-wash: light-dark(#EEE9FF, #2A2146); + --q-rose: light-dark(#D6336C, #E8467F); + --q-hair: light-dark(#E6E1D8, #2E2940); + --q-danger: light-dark(#B3261E, #FF8A80); + --q-ok: light-dark(#17692F, #7FE0A0); + --q-warn: light-dark(#8A5A00, #FFCB6B); + --q-radius: 8px; + --q-shadow: 0 1px 2px light-dark(rgb(40 30 20 / .08), rgb(0 0 0 / .4)), 0 6px 18px light-dark(rgb(40 30 20 / .06), rgb(0 0 0 / .3)); + --q-font: "Segoe UI Variable Text", "Segoe UI", system-ui, -apple-system, Roboto, "Helvetica Neue", sans-serif; + --q-font-display: "Segoe UI Variable Display", "Segoe UI Variable Text", "Segoe UI", system-ui, sans-serif; + --q-rail: 88px; + --q-gutter: 16px; + --q-tabs: 68px; + + /* The Fluent components read their own tokens; point the brand ones at the violet. */ + --colorBrandBackground: var(--q-violet); + --colorBrandBackgroundHover: var(--q-violet-hover); + --colorBrandBackgroundPressed: var(--q-violet-hover); + --colorBrandForeground1: var(--q-violet-text); + --colorBrandStroke1: var(--q-violet); + --colorCompoundBrandBackground: var(--q-violet); + --colorCompoundBrandBackgroundHover: var(--q-violet-hover); + --colorCompoundBrandStroke: var(--q-violet); +} + +:root[data-q-theme="light"] { color-scheme: light; } +:root[data-q-theme="dark"] { color-scheme: dark; } + +*, *::before, *::after { box-sizing: border-box; } + +html { -webkit-text-size-adjust: 100%; } + +html body { + margin: 0; + background: var(--q-paper); + color: var(--q-ink); + font: 400 14px/20px var(--q-font); + -webkit-font-smoothing: antialiased; + overflow: auto; + height: auto; +} + +h1, h2, h3 { margin: 0; font-weight: 600; } +h1 { font: 600 28px/34px var(--q-font-display); letter-spacing: -.01em; } +h2 { font: 600 18px/24px var(--q-font-display); } +h3 { font: 600 16px/22px var(--q-font); } +p { margin: 0; } +html body a { color: var(--q-violet-text); text-decoration: underline; text-underline-offset: 2px; } +html body a:hover { color: var(--q-violet-hover); } +img { max-width: 100%; } +button { font: inherit; color: inherit; } +hr { border: 0; border-top: 1px solid var(--q-hair); margin: 16px 0; opacity: 1; } +code, kbd { font-family: "Cascadia Mono", ui-monospace, Consolas, monospace; font-size: 12.5px; } + +:focus-visible { + outline: 2px solid var(--q-violet-text); + outline-offset: 2px; + border-radius: 4px; +} + +.q-sr { + position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; + clip-path: inset(50%); white-space: nowrap; border: 0; +} + +.q-skip { + position: fixed; left: 8px; top: -64px; z-index: 100; padding: 10px 14px; border-radius: var(--q-radius); + background: var(--q-violet); color: #fff; text-decoration: none; font-weight: 600; +} +.q-skip:focus { top: 8px; } + +/* ───────── Shell ───────── */ + +.q-shell { + display: grid; + grid-template-columns: var(--q-rail) minmax(0, 1fr); + min-height: 100dvh; +} + +.q-rail { + position: sticky; top: 0; height: 100dvh; + display: flex; flex-direction: column; align-items: stretch; gap: 4px; + padding: 14px 8px; + background: var(--q-sleeve); + border-inline-end: 1px solid var(--q-hair); + overflow-y: auto; +} + +.q-brand { display: flex; justify-content: center; padding: 4px 0 14px; } +.q-brand img { width: 40px; height: 40px; border-radius: 10px; display: block; } + +.q-navlist { display: flex; flex-direction: column; gap: 4px; margin: 0; padding: 0; list-style: none; } +.q-spacer { flex: 1; } + +.q-navitem { + position: relative; + display: flex; flex-direction: column; align-items: center; gap: 3px; + padding: 8px 4px 7px; + min-height: 56px; + border-radius: var(--q-radius); + color: var(--q-muted); + background: transparent; border: 0; + text-decoration: none; cursor: pointer; width: 100%; + font-size: 11.5px; line-height: 14px; text-align: center; + transition: background-color .12s ease, color .12s ease; +} +.q-navitem:hover { background: var(--q-sleeve-2); color: var(--q-ink); } +.q-navitem.active { color: var(--q-violet-text); background: var(--q-violet-wash); font-weight: 600; } +.q-navitem.active::before { + 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; } + +.q-badge { + position: absolute; top: -5px; inset-inline-start: 14px; + min-width: 20px; height: 20px; padding: 0 6px; + border-radius: 999px; + background: var(--q-rose); color: #fff; + font: 600 12px/20px var(--q-font); font-variant-numeric: tabular-nums; text-align: center; + box-shadow: 0 0 0 2px var(--q-sleeve); +} + +.q-main { min-width: 0; padding: 28px clamp(16px, 4vw, 40px) 56px; } +.q-page { max-width: 1040px; margin: 0 auto; } + +.q-tabs { display: none; } + +/* ───────── Page header and command bar ───────── */ + +.q-head { display: flex; align-items: center; gap: 14px; margin-bottom: 18px; } +.q-head-ico { + 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; } +.q-sub { color: var(--q-muted); margin-top: 2px; } + +.q-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin-bottom: 16px; } +.q-bar .q-grow { flex: 1 1 220px; min-width: 0; } + +.q-input, .q-select { + width: 100%; height: 40px; padding: 0 12px; + background: var(--q-sleeve); color: var(--q-ink); + border: 1px solid var(--q-hair); border-bottom-color: var(--q-muted); + border-radius: var(--q-radius); + font: inherit; +} +.q-input::placeholder { color: var(--q-muted); opacity: 1; } +.q-input:hover, .q-select:hover { border-color: var(--q-muted); } +.q-input:focus-visible, .q-select:focus-visible { outline: 2px solid var(--q-violet-text); outline-offset: 0; border-color: transparent; } +.q-select { width: auto; padding-inline-end: 8px; cursor: pointer; } +.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; color: var(--q-muted); pointer-events: none; +} + +/* Buttons: one shape, three weights. */ +.q-btn { + display: inline-flex; align-items: center; justify-content: center; gap: 8px; + min-height: 40px; padding: 0 16px; + border-radius: var(--q-radius); + border: 1px solid var(--q-hair); + background: var(--q-sleeve); color: var(--q-ink); + font: 600 14px/20px var(--q-font); + text-decoration: none; cursor: pointer; white-space: nowrap; + transition: background-color .12s ease, border-color .12s ease; +} +html body a.q-btn, html body a.q-navitem { text-decoration: none; } +html body a.q-btn { color: var(--q-ink); } +html body a.q-btn.primary { color: #fff; } +html body a.q-navitem { color: var(--q-muted); } +html body a.q-navitem.active { color: var(--q-violet-text); } +.q-btn:hover { background: var(--q-sleeve-2); } +.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); } +.q-btn.quiet { background: transparent; border-color: transparent; } +.q-btn.quiet:hover { background: var(--q-sleeve-2); } +.q-btn.wide { width: 100%; min-height: 48px; } +.q-btn.icon { padding: 0; width: 40px; } +.q-btn[disabled], .q-btn[aria-disabled="true"] { opacity: .55; cursor: not-allowed; } +.q-linkbtn { background: none; border: 0; padding: 0; color: var(--q-violet-text); text-decoration: underline; cursor: pointer; font: inherit; } + +.q-switch { display: inline-flex; align-items: center; gap: 8px; min-height: 40px; cursor: pointer; } + +/* ───────── Queue: list rows and cover tiles ───────── */ + +.q-list { display: flex; flex-direction: column; gap: 8px; margin: 0; padding: 0; list-style: none; } + +.q-row { + display: grid; grid-template-columns: 64px minmax(0, 1fr) auto; align-items: center; gap: 4px 14px; + padding: 10px 12px 10px 10px; + background: var(--q-sleeve); + border: 1px solid var(--q-hair); border-radius: var(--q-radius); + scroll-margin-top: 16px; +} +.q-row.picked { outline: 2px solid var(--q-violet); outline-offset: 2px; animation: q-pop .5s ease; } +.q-title { font: 600 16px/22px var(--q-font); overflow-wrap: anywhere; } +.q-meta { color: var(--q-muted); font-size: 12.5px; line-height: 18px; overflow-wrap: anywhere; } +.q-actions { display: flex; align-items: center; gap: 8px; } + +.q-cover { + position: relative; width: 64px; aspect-ratio: 1; border-radius: var(--q-radius); overflow: hidden; flex: none; + background: var(--q-sleeve-2); box-shadow: var(--q-shadow); +} +.q-cover img { width: 100%; height: 100%; object-fit: cover; display: block; } +.q-cover .q-sleeve-fallback { + position: absolute; inset: 0; display: grid; place-items: center; + font: 600 22px/1 var(--q-font-display); color: #fff; letter-spacing: .02em; + background: linear-gradient(135deg, hsl(var(--q-hue) 62% 42%), hsl(calc(var(--q-hue) + 40) 66% 52%)); +} + +.q-check { + display: grid; place-items: center; width: 44px; height: 44px; border-radius: 50%; + 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; } +.q-check.done { background: var(--q-violet); border-color: var(--q-violet); color: #fff; } + +.q-menu { position: relative; } +.q-menu > summary { list-style: none; cursor: pointer; } +.q-menu > summary::-webkit-details-marker { display: none; } +.q-menu[open] > summary { background: var(--q-sleeve-2); } +.q-menu-list { + position: absolute; inset-inline-end: 0; top: calc(100% + 4px); z-index: 20; min-width: 230px; + display: flex; flex-direction: column; padding: 6px; + background: var(--q-sleeve); border: 1px solid var(--q-hair); border-radius: var(--q-radius); box-shadow: var(--q-shadow); +} +.q-menu-list .q-btn { justify-content: flex-start; border-color: transparent; background: transparent; width: 100%; } +.q-menu-list .q-btn:hover { background: var(--q-sleeve-2); } + +.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; } +.q-star.on { color: var(--q-rose); } +.q-star:hover { color: var(--q-rose); } + +.q-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(156px, 1fr)); gap: 16px; margin: 0; padding: 0; list-style: none; } +.q-tile { display: flex; flex-direction: column; gap: 8px; padding: 10px; background: var(--q-sleeve); border: 1px solid var(--q-hair); border-radius: var(--q-radius); scroll-margin-top: 16px; } +.q-tile .q-cover { width: 100%; } +.q-tile .q-actions { margin-top: auto; } +.q-tile .q-actions .q-btn.primary { flex: 1; min-width: 0; padding: 0 8px; } +.q-tile.picked { outline: 2px solid var(--q-violet); outline-offset: 2px; animation: q-pop .5s ease; } + +.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; color: var(--q-violet-text); margin-bottom: 8px; } + +/* ───────── Add page ───────── */ + +.q-add { display: grid; gap: 14px; } +.q-field { display: grid; gap: 6px; } +.q-field > label, .q-label { font-weight: 600; font-size: 13px; } +.q-hint { color: var(--q-muted); font-size: 12.5px; } +.q-status { color: var(--q-muted); min-height: 20px; white-space: pre-line; } +.q-status.err { color: var(--q-danger); } + +.q-result { + display: grid; grid-template-columns: 64px minmax(0, 1fr); gap: 4px 14px; align-items: start; + padding: 10px; background: var(--q-sleeve); border: 1px solid var(--q-hair); border-radius: var(--q-radius); +} +.q-result.best { border-color: var(--q-violet); box-shadow: 0 0 0 1px var(--q-violet); } +.q-result .q-foot { grid-column: 1 / -1; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; } +.q-pills { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; flex: 1; } + +.q-pill { + display: inline-flex; align-items: center; gap: 6px; height: 24px; padding: 0 10px; border-radius: 999px; + border: 1px solid var(--q-hair); background: var(--q-sleeve-2); font-size: 12px; font-weight: 600; color: var(--q-ink); +} +.q-pill::before { content: ""; width: 8px; height: 8px; border-radius: 50%; background: currentColor; } +.q-pill.spotify::before { background: #1DB954; } +.q-pill.tidal::before { background: light-dark(#000, #fff); } +.q-pill.off { opacity: .45; text-decoration: line-through; } +.q-pill.score { background: var(--q-violet-wash); color: var(--q-violet-text); border-color: transparent; } +.q-pill.score::before { display: none; } +.q-pill.state { background: transparent; color: var(--q-muted); } +.q-pill.state::before { display: none; } + +.q-quick { background: var(--q-sleeve); border: 1px solid var(--q-hair); border-radius: var(--q-radius); padding: 0; } +.q-quick > summary { cursor: pointer; padding: 12px 14px; font-weight: 600; } +.q-quick-body { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 12px; padding: 0 14px 14px; align-items: end; } + +/* ───────── Messages ───────── */ + +.q-alert { + display: flex; gap: 10px; align-items: flex-start; + 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; color: var(--q-violet-text); margin-top: 1px; } +.q-alert.warn { border-inline-start-color: 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 { color: var(--q-danger); } +.q-alert.ok { border-inline-start-color: var(--q-ok); } +.q-alert.ok svg { color: var(--q-ok); } +.q-alert p + p { margin-top: 4px; } + +.q-snack { + position: fixed; inset-inline: 0; bottom: 20px; z-index: 60; + display: flex; justify-content: center; padding: 0 16px; pointer-events: none; +} +.q-snack-card { + pointer-events: auto; display: flex; align-items: center; gap: 12px; flex-wrap: wrap; + max-width: 640px; padding: 10px 10px 10px 16px; + background: light-dark(#1B1724, #F2EFF8); color: light-dark(#F2EFF8, #1B1724); + border-radius: var(--q-radius); box-shadow: var(--q-shadow); + animation: q-rise .18s ease; +} +.q-snack-card .q-btn { min-height: 36px; background: transparent; border-color: transparent; color: light-dark(#CBBBFF, #5030C4); } +.q-snack-card .q-btn:hover { background: light-dark(rgb(255 255 255 / .1), rgb(0 0 0 / .08)); } +.q-snack-card .q-star { color: light-dark(#B9B2C8, #6A6478); } +.q-snack-card .q-star.on, .q-snack-card .q-star:hover { color: #FF6E9C; } +.q-snack-card :focus-visible { outline-color: #CBBBFF; } +.q-snack-msg { flex: 1 1 200px; } + +/* ───────── Anonymous pages and Identity forms ───────── */ + +.q-bare { min-height: 100dvh; display: grid; place-items: center; padding: 24px 16px; } +.q-auth { width: min(440px, 100%); display: grid; gap: 18px; } +.q-auth-brand { display: flex; align-items: center; gap: 12px; } +.q-auth-brand img { width: 44px; height: 44px; border-radius: 12px; } +.q-card { background: var(--q-sleeve); border: 1px solid var(--q-hair); border-radius: var(--q-radius); padding: 20px; box-shadow: var(--q-shadow); } +.q-card.stack, .q-form { display: grid; gap: 14px; } +.q-form-row { display: grid; gap: 14px; } +.q-field-error { color: var(--q-danger); font-size: 12.5px; } +.validation-errors, .q-errors { color: var(--q-danger); margin: 0; padding-inline-start: 18px; } +.valid.modified:not([type=checkbox]) { border-bottom-color: var(--q-ok); } +.invalid { border-bottom-color: var(--q-danger) !important; } +.validation-message { color: var(--q-danger); font-size: 12.5px; } +.q-check-row { display: flex; align-items: center; gap: 10px; min-height: 40px; } +.q-check-row input { width: 20px; height: 20px; accent-color: var(--q-violet); } +.q-divider { display: flex; align-items: center; gap: 12px; color: var(--q-muted); font-size: 12.5px; } +.q-divider::before, .q-divider::after { content: ""; flex: 1; border-top: 1px solid var(--q-hair); } +.q-links { display: flex; flex-wrap: wrap; gap: 8px 18px; } +.q-table { width: 100%; border-collapse: collapse; } +.q-table th, .q-table td { text-align: start; padding: 8px 10px; border-bottom: 1px solid var(--q-hair); } + +.q-manage { display: grid; grid-template-columns: 220px minmax(0, 1fr); gap: 24px; align-items: start; } +.q-subnav { display: flex; flex-direction: column; gap: 2px; margin: 0; padding: 0; list-style: none; } +.q-subnav a { display: block; padding: 8px 12px; border-radius: var(--q-radius); color: var(--q-ink); text-decoration: none; } +.q-subnav a:hover { background: var(--q-sleeve-2); } +.q-subnav a.active { background: var(--q-violet-wash); color: var(--q-violet-text); font-weight: 600; } +.q-codes { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 6px; font-family: "Cascadia Mono", ui-monospace, Consolas, monospace; } + +.q-prefs { display: grid; gap: 6px; } +.q-seg { display: inline-flex; border: 1px solid var(--q-hair); border-radius: var(--q-radius); overflow: hidden; } +.q-seg button { border: 0; background: var(--q-sleeve); min-height: 36px; padding: 0 12px; cursor: pointer; } +.q-seg button + button { border-inline-start: 1px solid var(--q-hair); } +.q-seg button[aria-pressed="true"] { background: var(--q-violet-wash); color: var(--q-violet-text); font-weight: 600; } + +#blazor-error-ui { + display: none; position: fixed; inset-inline: 0; bottom: 0; z-index: 1000; padding: 12px 16px; + background: var(--q-danger); color: light-dark(#fff, #14111B); +} +#blazor-error-ui .dismiss { cursor: pointer; position: absolute; inset-inline-end: 12px; top: 10px; } +#blazor-error-ui a { color: inherit; } + +#components-reconnect-modal { + border: 1px solid var(--q-hair); border-radius: var(--q-radius); background: var(--q-sleeve); color: var(--q-ink); + box-shadow: var(--q-shadow); padding: 20px; max-width: 360px; +} +#components-reconnect-modal::backdrop { background: rgb(0 0 0 / .45); } +.components-reconnect-container { display: grid; gap: 10px; text-align: center; } +#components-reconnect-modal button { min-height: 40px; padding: 0 16px; border-radius: var(--q-radius); border: 1px solid var(--q-violet); background: var(--q-violet); color: #fff; font-weight: 600; cursor: pointer; } +#components-reconnect-modal p { margin: 0; } +.components-rejoining-animation { display: none; } + +/* ───────── Motion ───────── */ + +@keyframes q-pop { from { outline-offset: 10px; } to { outline-offset: 2px; } } +@keyframes q-rise { from { translate: 0 12px; opacity: 0; } to { translate: 0 0; opacity: 1; } } + +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { animation: none !important; transition: none !important; scroll-behavior: auto !important; } +} + +/* ───────── Phones ───────── */ + +@media (max-width: 759.98px) { + body { font-size: 15px; } + .q-shell { display: block; } + .q-rail { display: none; } + .q-main { padding: 16px var(--q-gutter) calc(var(--q-tabs) + 32px + env(safe-area-inset-bottom)); } + h1 { font-size: 24px; line-height: 30px; } + + .q-tabs { + display: grid; grid-template-columns: repeat(5, 1fr); align-items: end; + position: fixed; inset-inline: 0; bottom: 0; z-index: 50; + height: calc(var(--q-tabs) + env(safe-area-inset-bottom)); padding: 6px 4px env(safe-area-inset-bottom); + background: var(--q-sleeve); border-top: 1px solid var(--q-hair); + } + .q-tabs .q-navitem { min-height: 56px; padding: 4px 2px; } + .q-tabs .q-navitem.active::before { display: none; } + .q-tabs .q-navitem.add .q-ico { + width: 44px; height: 44px; margin-top: -18px; border-radius: 50%; + background: var(--q-violet); color: #fff; box-shadow: 0 4px 12px rgb(101 68 230 / .4); + } + .q-tabs .q-navitem.add .q-ico svg { width: 24px; height: 24px; } + .q-tabs .q-navitem.add.active { background: transparent; } + .q-tabs .q-more { position: static; } + .q-tabs .q-more > summary { list-style: none; } + .q-tabs .q-more > summary::-webkit-details-marker { display: none; } + .q-more-sheet { + position: fixed; inset-inline: 8px; bottom: calc(var(--q-tabs) + 12px + env(safe-area-inset-bottom)); z-index: 55; + display: grid; gap: 4px; padding: 10px; background: var(--q-sleeve); border: 1px solid var(--q-hair); + border-radius: 14px; box-shadow: var(--q-shadow); + } + .q-more-sheet .q-navitem { flex-direction: row; justify-content: flex-start; gap: 12px; min-height: 48px; padding: 8px 12px; font-size: 15px; text-align: start; } + .q-more-sheet .q-navitem.active::before { display: none; } + + .q-row { grid-template-columns: 56px minmax(0, 1fr); padding: 10px; } + .q-row .q-cover { width: 56px; } + .q-row .q-actions { grid-column: 1 / -1; } + .q-row .q-actions .q-btn.primary { flex: 1; min-height: 44px; } + .q-bar .q-btn, .q-bar .q-select { min-height: 44px; height: 44px; } + .q-input { height: 44px; font-size: 16px; } + .q-input.big { height: 54px; } + + .q-manage { grid-template-columns: 1fr; } + .q-snack { bottom: calc(var(--q-tabs) + 12px + env(safe-area-inset-bottom)); } +} + +@media (min-width: 760px) { + .q-more-sheet { display: none; } +} + +.q-star.on svg { fill: currentColor; } +.q-field > label { order: -1; } +.q-col { min-width: 0; } +.q-check-row input { flex: none; } + +h1[tabindex="-1"]:focus, h1[tabindex="-1"]:focus-visible { outline: none; } +.q-row .q-actions { justify-content: flex-end; } + +@media (pointer: coarse) { + .q-btn, .q-star, .q-check, .q-seg button, .q-switch { min-height: 44px; } + .q-btn.icon, .q-star, .q-check { min-width: 44px; } +} +#blazor-error-ui .dismiss { background: none; border: 0; color: inherit; font-size: 18px; min-width: 44px; min-height: 44px; top: 0; } +.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; } +} + + +.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; } + diff --git a/Queueify.Web/wwwroot/queueify.js b/Queueify.Web/wwwroot/queueify.js new file mode 100644 index 0000000..ec0c2f9 --- /dev/null +++ b/Queueify.Web/wwwroot/queueify.js @@ -0,0 +1,79 @@ +// 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); + }); + + // Menus built from
close when something else is clicked, or when a link inside them is used. + 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 || (e.target.classList && e.target.classList.contains('q-scrim'))) d.removeAttribute('open'); + }); + }); + document.addEventListener('keydown', function (e) { + if (e.key === 'Escape') document.querySelectorAll('details.q-more[open], details.q-menu[open]').forEach(function (d) { d.removeAttribute('open'); const s = d.querySelector('summary'); if (s) s.focus(); }); + }); + document.addEventListener('focusout', function (e) { + const d = e.target.closest && e.target.closest('details.q-more[open], details.q-menu[open]'); + if (d && e.relatedTarget && !d.contains(e.relatedTarget)) d.removeAttribute('open'); + }); + + 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); }, + theme: function () { return document.documentElement.dataset.qTheme || 'system'; }, + get: function (key) { try { return localStorage.getItem(key); } catch (_) { return null; } }, + getMany: function (keys) { return keys.map(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..20aa750 --- /dev/null +++ b/Queueify.Web/wwwroot/sw.js @@ -0,0 +1,31 @@ +// 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-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(); })); +}); + +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); })); + } +}); diff --git a/Queueify.slnx b/Queueify.slnx index a24df9e..33561dd 100644 --- a/Queueify.slnx +++ b/Queueify.slnx @@ -2,5 +2,7 @@ + + 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 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..bc148e4 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(ServerSync.CreateClient()); private readonly Updater _updater = new(Http, UpdateSource.For(Environment.GetEnvironmentVariable("QUEUEIFY_UPDATE_SERVER"))); private bool _updating; @@ -137,6 +138,8 @@ private static HttpClient CreateHttpClient() return http; } + private ISyncProvider Provider() => SyncProviders.For(_settings.ActiveSync, _cloud, _web); + // ───────────────────────── Window & layout ───────────────────────── private void UpdateSearchStatusPanel() => @@ -403,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"); } @@ -442,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) @@ -497,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; @@ -546,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")); } @@ -669,12 +646,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) { @@ -797,732 +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.CloudConfigured) return; - _syncDebounce.Stop(); - _syncDebounce.Start(); - } - - private Task? _syncTask; - private Task? _followUpSync; - - /// - /// 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.CloudConfigured) 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 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 - { - _settings.CloudLastServerTime = work.CloudLastServerTime; - // 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.CloudConfigured ? error : null; - UpdateSyncButton(); - return error; - } - - private static string DescribeSyncError(Exception ex) => ex switch - { - CatalogException => 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; - if (!_settings.CloudConfigured) - (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")); - - 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) - { - if (_settings.CloudConfigured) await ShowSyncConnectedAsync(); - else await ShowSyncSetupAsync(); - } - - /// 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 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); - - create.Checked += (_, _) => { createPanel.Visibility = Visibility.Visible; joinPanel.Visibility = Visibility.Collapsed; }; - join.Checked += (_, _) => { createPanel.Visibility = Visibility.Collapsed; joinPanel.Visibility = Visibility.Visible; }; - - 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(createPanel); - panel.Children.Add(joinPanel); - 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; - dialog.PrimaryButtonClick += async (d, args) => - { - var deferral = args.GetDeferral(); - try - { - string project, key; - joined = join.IsChecked == true; - 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(); - } - - // 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; - // 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; - - progress.Visibility = Visibility.Visible; - error.IsOpen = false; - d.IsPrimaryButtonEnabled = false; - string? problem = null; - 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(() => _cloud.SyncAsync(_store, trial, CancellationToken.None)); - } - catch (Exception ex) - { - problem = DescribeSyncError(ex); - } - progress.Visibility = Visibility.Collapsed; - d.IsPrimaryButtonEnabled = true; - - if (problem != 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.CloudConfigured) return; - - 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.CloudProjectId = _settings.CloudQueueKey = ""; - _settings.CloudLastServerTime = null; - _syncError = null; - AppData.SaveSettings(_settings); - UpdateSyncButton(); - ShowToast(Loc.T("sync.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() @@ -1534,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"] }; } diff --git a/Queueify/Queueify.csproj b/Queueify/Queueify.csproj index ab1fe7d..65f0684 100644 --- a/Queueify/Queueify.csproj +++ b/Queueify/Queueify.csproj @@ -15,8 +15,6 @@ true resources.pri - enable - enable app.manifest Assets\Queueify.ico 1.4.0 @@ -47,8 +45,8 @@ - - + + diff --git a/README.md b/README.md index c524be5..5e63e32 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,33 @@ 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. + +## Web app (from your phone) + +`Queueify.Web` is the same queue as a website you can host yourself: sign in with a password or a passkey, +add an album from your phone the moment someone recommends it, and see it on your PCs. On a phone the +**Add** page is the first thing you see after signing in, and the site installs to the home screen (PWA). +It has the same pages as the desktop app (To listen, Listened, Magazine photo, Help, Settings), English and +Rioplatense Spanish (chosen with the language button, otherwise by the browser), and light, dark or system +theme. The Spotify and Tidal keys stay on the server and are never sent to the browser. + +```powershell +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 `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). To host it (Docker, a home PC behind a tunnel, a free VM) see [docs/HOSTING.md](docs/HOSTING.md). + ## Magazine photos Take the photo with your phone, get it onto the PC (Phone Link, WhatsApp Web, OneDrive…) and drop it into @@ -87,6 +114,28 @@ Settings → *Text recognition*, which also installs English, Portuguese, French Windows asks for an administrator's permission. If anything goes wrong (permission declined, no internet, updates managed by an organization), Queueify says what happened and how to go on. +## Web version: photos, settings and your data + +The web app (`Queueify.Web`, see [ADR-0010](docs/adr/0010-web-app-and-shared-queue.md)) has the same Help, +Settings and Magazine photo pages. + +- **Magazine photo**: choose, take (phones open the camera), drop or paste a photo, then tap the artist and the + album; *Search* opens the Add page with them. Photos are read by Tesseract in Spanish and English, then + discarded: nothing is stored. Run the server with the `tesseract` program installed (`apt install + tesseract-ocr`, or the Windows installer; `Ocr:TesseractPath` if it isn't on the PATH). The models download + once, checked against a checksum; to manage them yourself set `Ocr:TessdataPath` + ([ADR-0011](docs/adr/0011-web-ocr.md)). Limits live in the `Ocr` section: `MaxBytes`, `MaxPixels`, + `Timeout`, `MaxConcurrent`. +- **Settings**: Spotify and Tidal keys are write-only (the page says *Configured* or *Not configured* and never shows + them again), with a *Test keys* button; Play app, country, theme, language, reading language, the link to + connect a PC, how to sign out everywhere, and *Delete my data*. +- **Your data**: download the queue as JSON or CSV; import the desktop's `queueify.db` (in + `%LOCALAPPDATA%\Queueify`) or an exported JSON. Albums keep their identity, so importing twice never duplicates + anything and an album you deleted on the web stays deleted. + +Test it: `dotnet test --project Queueify.Web.Tests`. The real-engine test runs when `QUEUEIFY_TESSERACT` and +`QUEUEIFY_TESSDATA` are set. + ## Privacy Queueify has no servers and no telemetry. It talks to Tidal and Spotify (searches, with your keys), to @@ -107,3 +156,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 f2ad104..4a46a07 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 | | --- | --- | --- | @@ -20,11 +21,44 @@ Queueify runs with the user's rights on their own PC. It has no servers of its o | The online queue (`queues/{key}` in the user's Firestore) | Others reading or changing it | The 40-hex-character key is the capability. The security rules give no way to list the queues (so keys can't be discovered), allow only albums and settings under a key, and limit their field names and sizes. | | The user's Firebase quota | Someone who knows the project ID creates junk under other keys | Known limit: the rules can't stop it without Firebase Auth or App Check. Documented in the README. | | JSON from Spotify, Tidal, Firebase | Malformed or hostile data crashing the app | Parsed defensively; failures become user-facing errors; text sizes are clipped before upload. | +| A Queueify web server the user connects to (`WebServerUrl`, `WebToken` in `settings.json`) | The token is read from the folder; a wrong or hostile server is connected; a hostile server sends bad data | The token is stored unencrypted, like the sync code, and can be revoked in the web app. The address must be https (http only on loopback) and is checked on every sync; redirects and answers from another host are refused; errors never contain the token, address or server text; requests time out after 20 s and answers are capped at 16 MB. | +| What a connected web server can do | Read the shared Spotify/Tidal keys, replace them, change or delete any album | By design the server is trusted as the user's own: the shared keys go to it (the connect panel says so) and its answers win over older local data. Downloaded text is cut to 500 characters, album ids and years are checked, and change times more than 5 minutes ahead are taken as now, which only guards against wrong clocks and absurd values: a hostile server can still win any comparison. Connect only to a server you run or trust. | | Elevated OCR install (`Add-WindowsCapability`) | Injection into a script that runs as administrator | Only allow-listed language tags reach it; the log path (from the user's profile) is passed Base64-encoded; tests run the script through PowerShell's parser. | | 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. 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. | -| 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. | +| Network | Exfiltration | Only Spotify, Tidal, the user's own Firebase project or the Queueify web server they connected, 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. | + +### Web app: uploads and secrets + +| Asset / boundary | Threat | Mitigation | +| --- | --- | --- | +| Spotify and Tidal client secrets on the server | Read from disk, a backup, a response or the page | Encrypted in `secrets.dat` with ASP.NET Data Protection, bound to the user, and never written to `settings.json`. Limit, stated plainly: the key ring sits in the data folder (`keys/`, not encrypted itself), so this protects against `settings.json` or a single file leaking, not against someone who copies the whole data folder; keep backups of that folder private, or protect the ring with a certificate or the OS key store when deploying. A lost ring only means re-entering the secrets. The Settings page learns "configured or not", never the value; its secret fields are empty password fields; exports hold no settings; tests assert no response carries a saved secret. | +| Photo upload (`POST /api/photo`) | Decompression bombs, non-images (HTML, SVG), metadata leaks, floods, a stored copy | Signed-in users only; the declared type must be `image/*` (a cross-site form can't send it and no CORS is configured) but the bytes are sniffed (JPEG, PNG, WebP); 12 MB cap on the length and while reading; the pixel count is read from the header (60 MP) before decoding; the result is a fresh PNG without EXIF/ICC/XMP; nothing is written to disk and the clean image's buffer is wiped after reading (the upload's own buffer is only released to the garbage collector); an upload is read into memory only after admission (one photo per user and two per server at a time, the rest get 429); 40 s timeout that kills the child process (the decode itself can't be interrupted, so its slot is kept until it ends). | +| The `tesseract` child process | Argument injection, a hung or crashing engine | Arguments are an array (no shell); the language is one of three fixed choices; the models are checksummed; the process is killed on timeout or cancel and its output is capped. | +| Import (`POST /api/import`) of `queueify.db` or JSON | A crafted SQLite file (views, triggers, huge values, corruption) or oversized JSON | 25 MB cap, one import per user at a time; the file is copied to a private temp name (created with mode 0600 on Linux, so other local accounts cannot read it), opened read-only and immutable, with `trusted_schema` off and only a real `items` table accepted (a view, a virtual table or a table with a generated column is refused: generated columns run on every read and a few bytes of file can ask for gigabytes); rows are read with every text cut to 500 characters and every number range-checked, at most 20,000 rows; it is never attached to a live database; what remains is inserted through `BacklogStore`; the copy is deleted afterwards. Cover addresses must be `https`. | +| Export (CSV) | Formula injection when opened in a spreadsheet | Cells starting with `=`, `+`, `-`, `@`, tab or return get a leading apostrophe. | +| Upload and import endpoints | CSRF | Cookies are `SameSite=Lax`; the endpoints take only picture, `application/octet-stream` or `application/json` bodies, which a cross-site form cannot send. | +| Per-user folders | One user reaching another's data | The user id comes from the sign-in claim only and is validated as one plain folder name by `UserStores`. | 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 | +| --- | --- | --- | +| 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` 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; the page may talk only to its own origin (`connect-src 'self'`, plus the `wss:` address of `Queueify:PublicBaseUrl` when set, for older Safari), picture previews made in the browser (`blob:`) are allowed, no inline script is used; album covers may come from any HTTPS host and are fetched without a referrer), `X-Content-Type-Options: nosniff` and `Referrer-Policy: no-referrer`. | +| Host header | A proxy that forwards any `Host` makes the connect text (which carries a fresh token) point at an attacker | Set `Queueify:PublicBaseUrl` (https, or http on loopback): the connect text is built from it, never from the request. Set `AllowedHosts` (default `*`) to your host name so other Host headers get a 400. | +| 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 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 428b54e..d3619bb 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)] ``` @@ -30,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. | @@ -42,16 +44,39 @@ 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. | +| `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). | | `Countries` | The countries where both services work, named in the app language. | | `Updater` | The latest GitHub release: whether it's newer, downloading and checking its exe, swapping it in ([ADR-0009](adr/0009-update-from-github-releases.md)). | +## Web app (`Queueify.Web`) + +A Blazor Web App (.NET 10): static server rendering for the account pages, Interactive Server for the rest, +referencing `Queueify.Core` for matching, catalogs, `BacklogStore`, `QueueText` and the string tables +([ADR-0010](adr/0010-web-app-and-shared-queue.md), look and layout in [WEB_DESIGN.md](WEB_DESIGN.md)). + +| Part | Responsibility | +| --- | --- | +| `Services/QueueifyUi` | `AddQueueifyUi()` and `MapQueueifyUi()`: the only lines `Program.cs` needs. Registers the services, the 20 s catalog `HttpClient`, the per-request language and the `/prefs` form endpoint. | +| `Services/UserQueue` | The signed-in user's queue for one circuit: every change is written at once to that user's `queueify.db` (`UserStores`), undo re-reads the stored album, `Changed` redraws the nav badges. A change updates only that album in memory (`LoadAsync` is the full refresh) and keeps a normalised search key per album, so filtering a queue of tens of thousands does not normalise every album per keystroke; the queue pages debounce the filter and draw 100 albums at a time. | +| `Services/AlbumSearch`, `HttpCatalogs` | Both catalogs at once with the user's own keys, the year retry, errors as readable messages; one catalog object per user so tokens are reused but never shared. | +| `Services/Prefs` | Language (cookie, then `Accept-Language`), theme, same-site return paths, where a phone lands after sign-in. | +| `LocCircuitHandler` | `Loc` keeps its language per async flow; each call into a circuit runs with the circuit's language, so two users never swap languages. | +| `Components/Layout` | `NavMenu` is one list of every page drawn as the left rail and the phone tab bar; `MainLayout` is the shell, or a bare centred card when signed out. | +| `Components/Shared`, `Pages` | `QueueBrowser` (To listen and Listened), `Add`, `Cover`, `Stars`, `Snackbar`. Decisions live in Core: `QueueView` (filter, order, the "Artist - Album" split, already-saved check) and `PlayLinks` (`spotify:` / `tidal:` with an https fallback; the desktop `ExternalLinks` uses it, and `MainWindow` can call `QueueView` instead of its own copy of the filter and order). | +| `Components/Account` | The ASP.NET Core Identity pages, restyled; registration follows `RegistrationGate`. | + +Sign-in is required for every page except the account pages; the user id (never anything the browser sends) +picks the data folder. + ## Data Everything lives in `%LOCALAPPDATA%\Queueify`: `queueify.db`, `settings.json`, `ui.json` and, after a crash, @@ -60,7 +85,32 @@ 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`. + +## 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 for 90 days, then each sync purges them. Behind a reverse proxy, `Queueify:Proxy:KnownProxies` / `KnownNetworks` say whose `X-Forwarded-For` to trust, so the rate limit sees client addresses. 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 @@ -68,3 +118,23 @@ Sync: each PC keeps its own database. Online, a queue is `queues/{key}` in the u `PrimaryLanguageOverride`), then creates `MainWindow`, which restores the window, loads settings and the queue, applies the theme, and syncs once it's loaded. A language change restarts the app, because XAML reads its texts while it loads. + +## Web app: Settings, Help, Photo and data + +`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`; 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 | +| --- | --- | +| `Core: IOcr`, `WindowsOcr`, `OcrService.CleanLine` | The reader contract (plain boxes, no Windows types); the desktop adapter; the line cleanup both builds share. | +| `Ocr/` | `ImageGuard` (sniff, pixel budget, upright, scale, re-encode), `TesseractOcr` (child process, TSV), `TessdataFetcher` (pinned, checksummed models), `OcrGate` (one per user), `PhotoReader`, `POST /api/photo` ([ADR-0011](adr/0011-web-ocr.md)). | +| `Services/SettingsService`, `PreferencesStore` | Music settings with the desktop's edit rules (`AppSettings.ApplyEdits`), the key test through the catalogs, and per-user theme, language, reading language and tour state. | +| `Services/DataTransfer`, `DataEndpoints` | JSON and CSV export; import of the desktop's `queueify.db` (read through a read-only, immutable connection with the schema distrusted, never attached) or an exported JSON, through `BacklogStore`, so rows keep their `uid`. | +| `Components/Pages/Settings, Help, Photo` and `Components/Shared/Settings*, HelpTour` | The pages. Secrets are write-only: the page only ever learns "configured". `` is the first-run tour; the layout should mount it once, and Help mounts one as a fallback (only one shows). | +| `wwwroot/js/queueify-upload.js` | Chosen, dropped or pasted files stay in the browser; C# asks it to upload one by id. | + +The pages style themselves with Fluent design tokens (`--colorNeutral…`, with fallbacks) in scoped CSS, so they +look right inside the Fluent UI Blazor shell without depending on its components. diff --git a/docs/HOSTING.md b/docs/HOSTING.md new file mode 100644 index 0000000..7020584 --- /dev/null +++ b/docs/HOSTING.md @@ -0,0 +1,89 @@ +# Hosting Queueify.Web + +`Queueify.Web` is one ASP.NET Core process with its data in one folder. This page covers three ways to run it +and the settings that matter for every one of them. Design background: [ADR-0010](adr/0010-web-app-and-shared-queue.md). + +## What every host needs + +- **HTTPS in front of it.** Outside Development the server treats every request as https and marks its cookies + `Secure`, so TLS must end at a reverse proxy, tunnel or load balancer. A server kept on plain http on purpose + (a home network) sets `Queueify__AllowInsecureCookies=true`, and browsers will still refuse its cookies on + anything but `localhost`. +- **One data folder, backed up whole.** `Queueify__DataDir` holds the account database (`identity.db`), one + folder per user, the Data Protection keys (`keys/`), the OCR models and the `owner-exists` marker. The keys and + the encrypted Spotify/Tidal secrets are in the same folder, so a copy of it opens them: keep backups private. + Back up the whole folder, or none of it is consistent. Stop the server, or copy a snapshot, for a clean copy. +- **Tesseract** (with the Spanish and English models) on the machine, for photos. The Docker image has it. + +## Settings (environment variables) + +ASP.NET Core reads `Section__Key` from the environment (or `appsettings.Production.json`). + +| Variable | Meaning | +| --- | --- | +| `Queueify__DataDir` | The data folder. Default `App_Data` beside the app. In Docker: `/data`. | +| `Queueify__PublicBaseUrl` | The address people reach the site at, e.g. `https://queue.example.org`. The connect text for the Windows app is built from it, and the CSP names its websocket. Set it: without it the text uses the request's Host header. | +| `AllowedHosts` | Host names the server answers to, e.g. `queue.example.org`; default `*`. Separate names with `;`. Keep `localhost` in the list: the Docker image's health check calls the server by that name. | +| `Queueify__AllowRegistration` | `true` lets anyone register. Default: the first account owns the server, then registration closes (deleting that account does not reopen it; see SECURITY.md). | +| `Queueify__Proxy__KnownProxies` | Addresses of your reverse proxy (comma-free: `Queueify__Proxy__KnownProxies__0=10.0.0.5`). Only those may set `X-Forwarded-For/Proto`. `Queueify__Proxy__KnownNetworks__0=172.16.0.0/12` takes CIDR ranges. Without it the rate limit sees the proxy's address for everybody. | +| `Queueify__AllowInsecureCookies` | `true` only for a plain-http server (see above). | +| `Ocr__TesseractPath`, `Ocr__TessdataPath` | The tesseract program and a folder of models; empty `TessdataPath` downloads the two models once into the data folder. | +| `ConnectionStrings__DefaultConnection` | Moves the account database; leave it to keep `identity.db` in the data folder. | + +The first account: register it yourself before exposing the site, because whoever registers first owns it. +Check `/healthz` (answers `ok`) for monitoring. + +## Docker (any host with Docker) + +```sh +docker build -t queueify-web . +docker run -d --name queueify --restart unless-stopped -p 127.0.0.1:8080:8080 -v queueify-data:/data \ + -e Queueify__PublicBaseUrl=https://queue.example.org -e "AllowedHosts=queue.example.org;localhost" \ + -e Queueify__Proxy__KnownProxies__0=172.17.0.1 queueify-web +``` + +The image runs as a non-root user, keeps everything in the `/data` volume, includes tesseract with Spanish and +English, and has a `HEALTHCHECK` on `/healthz`. Put a reverse proxy (Caddy, nginx, Traefik) in front for TLS +and set `KnownProxies` to the address the proxy connects from (check the container network; `172.17.0.1` is the +usual bridge gateway when the proxy runs on the host). Back up with `docker run --rm -v queueify-data:/data -v "$PWD":/b busybox tar czf /b/queueify.tgz /data` +after stopping the container. (The Dockerfile has not been built in the repository's CI; build it once before relying on it.) + +## At home, behind a Cloudflare Tunnel + +Good for a PC or small server that is always on, without opening a port on the router. + +1. Install the .NET 10 runtime and tesseract (Windows installer, or `apt install tesseract-ocr tesseract-ocr-spa tesseract-ocr-eng`), or use Docker as above. +2. Publish and run: `dotnet publish Queueify.Web -c Release -o `, then + `Queueify__DataDir= ASPNETCORE_URLS=http://127.0.0.1:8080 dotnet Queueify.Web.dll` (as a service: systemd or Task Scheduler). +3. Install `cloudflared`, create a tunnel and point a public host name at `http://127.0.0.1:8080`. The tunnel + connects from the same machine, so set `Queueify__Proxy__KnownProxies__0=127.0.0.1`. +4. Set `Queueify__PublicBaseUrl` and `AllowedHosts` to the tunnel's host name; register your account. + +Cloudflare terminates TLS, so cookies stay `Secure` end to end. Mind that a home PC that sleeps or loses power is +a server that is down; keep the data folder on a disk you back up. + +## A free-tier cloud VM (for example Oracle Cloud Always Free) + +A small Linux VM runs this fine (the app is light; reading a very large photo can briefly use around a gigabyte, so keep `Ocr__MaxPixels` modest on a small VM). +Offers and limits change: **check the provider's current free-tier terms and what it does with idle or +unverified accounts before depending on it.** Steps, in short: + +1. Create an Ubuntu VM (ARM or x86; the image builds on both) and open ports 80 and 443 in the cloud firewall + and the VM's own firewall. +2. Install Docker and run the container as above, bound to `127.0.0.1:8080`. +3. Run Caddy or nginx on the VM for TLS (Let's Encrypt) in front of it, with your domain pointing at the VM. +4. Set the variables from the table, and take regular copies of the volume off the VM. + +## Why not Vercel (or other serverless hosts) + +Queueify.Web is a long-running .NET process: its Blazor circuits hold a WebSocket open per browser, it writes +SQLite files and encryption keys to a local disk that must persist, and it starts the `tesseract` program. +Serverless and static hosts have no .NET server runtime, no persistent local disk and no way to run that program, so +none of those three can work there. Use a VM, a container host with a persistent volume, or your own machine. + +## Upgrading from an early build + +Early builds kept the account database at `Data/app.db` beside the app. The server now uses `/identity.db`, +and a fresh one has no accounts, so before the first start of a new version move the old file there +(`Data/app.db` to `/identity.db`), or the first visitor becomes the owner of an empty server. Or set +`ConnectionStrings__DefaultConnection` to the old path. diff --git a/docs/TESTING.md b/docs/TESTING.md index be0c89f..09cdbb8 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -5,8 +5,10 @@ | 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 scripted answers over a fake `HttpMessageHandler`: round trips, pagination (a full page means more), 401, timeout, redirects, size limit, 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 | +| Web (`Queueify.Web.Tests`) | The sync server and tokens through `WebApplicationFactory`: auth, user isolation, conflicts, limits, secrets on disk, and `ServerSyncEndToEndTests`, which runs the real `ServerSync` client against the real `SyncEngine` in process (two PCs and the web, conflicts, deletions, pages over 1,000, revoked token) | `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 +57,15 @@ 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 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. + +## Build rules + +`Directory.Build.props` holds the settings every project shares (nullable, implicit usings) and, when `CI=true` +(GitHub sets it), turns nullable warnings and NuGet audit findings (known vulnerable packages) into errors; set +`CI=true` locally to see what CI will see. `Directory.Packages.props` holds every package version (central package +management): projects reference packages without a `Version`. The app version stays in `Queueify\Queueify.csproj` +and `Queueify.Core\Queueify.Core.csproj`, where `tools\package.ps1` and `release.yml` read it. CI also publishes +`Queueify.Web` as a smoke step, because the tests do not notice a publish that no longer works. diff --git a/docs/WEB_DESIGN.md b/docs/WEB_DESIGN.md new file mode 100644 index 0000000..79d7a01 --- /dev/null +++ b/docs/WEB_DESIGN.md @@ -0,0 +1,104 @@ +# Web design: "liner notes" + +The brief is the desktop app: [`MainWindow.xaml`](../Queueify/MainWindow.xaml) with its compact left +navigation, round count badges, 8 px cards and violet accent, and the same promise as UniGetUI: easy to use +as f*ck. The web app must feel like the same product, and must be fastest on the one job a phone does: +somebody says "listen to X", and it is in the queue ten seconds later. + +Rejected on purpose: a generic dashboard (cards of statistics, gradient hero, left tree menu), Bootstrap +chrome, and a blue Fluent default. What is kept instead is a small, specific idea: a queue of **record +sleeves on magazine paper**. Warm paper in light, record black in dark, one violet, and covers as the only +decoration (an album with no cover gets a deterministic tinted sleeve with its initials, so a list of +albums typed by hand still looks intentional). + +## Palette (6 names, defined once in `wwwroot/queueify.css`) + +| Name | Light | Dark | Used for | +| --- | --- | --- | --- | +| Paper | `#F7F4EF` | `#14111B` | page background (the dark one is the logo's record black) | +| Sleeve | `#FFFFFF` | `#1E1A28` | cards, inputs, the rail | +| Ink | `#1B1724` | `#F2EFF8` | text; muted `#665F75` / `#A9A3B8` (>= 4.5:1 on Paper and Sleeve) | +| Violet | `#6544E6` fill, `#5030C4` text | `#6B4CF0` fill, `#B5A2FF` text | the accent: primary buttons, current page, focus ring (the desktop's `#7B5CFF` family) | +| Rose | `#D6336C` | `#E8467F` | the round count badges and rating stars, nothing else | +| Hairline | `#E6E1D8` | `#2E2940` | borders and dividers | + +Colour never carries meaning alone: state is also text or an icon (Listened has a check and the word, +"In your queue" is a label, errors say "Error"). + +## Type + +System UI stack with Segoe UI Variable first, as the desktop app: `"Segoe UI Variable Text", "Segoe UI", +system-ui, sans-serif`. Roles: **Display** 28/34 semibold with slight negative tracking (page title), +**Title** 16/22 semibold (album), **Body** 14/20, **Meta** 12.5/18 muted (artist line, year, magazine, +dates), **Badge** 12 semibold with tabular numerals. Only two weights (400, 600). + +## Layout + +Phone (the primary device for adding), under 760 px: + +``` ++--------------------------------+ +| Add albums EN | title row, language/theme in "More" +|--------------------------------| +| [magazine: Pelo v] | remembered from the last add +| [ Artist - Album 1999 (Q)] | one big search box, autofocus +| | +| +----+ Clics Modernos | +| |cov | Charly Garcia - 1983 | result: cover, title, artist, year +| +----+ [Spotify][Tidal] Best | pills, "Best match" label +| [ Add ] | one big button, 48 px +| ... | +|--------------------------------| +| (1)Queue (+)Add Listened ...| bottom tab bar: the 4 pages you use +| [12] big [40] More| + More (Help, Settings, Connect, Sign out) ++--------------------------------+ +``` + +Desktop, 760 px and wider (the same destinations as the WinUI `NavigationView`, left compact): + +``` ++------+---------------------------------------------------------------+ +| logo | (queue icon) To listen | +| | 12 albums waiting - 2 added this week | +| (12) | [Filter (Ctrl+F) ] [Order v] [x] Covers [Surprise me] | +| Queue| +----------------------------------------------------------+ | +| | | cover Album [> Tidal] (o) (...) | | +| Add | | Artist | | +| | | 1983 - Pelo - added 3 Oct | | +| (40) | +----------------------------------------------------------+ | +| Done | ... | +| Photo| | +| Help | | +| Sett.| | +| Conn.| | +| EN | | +| Exit | | ++------+---------------------------------------------------------------+ +``` + +## Behaviour + +- The rail and the tab bar are one component listing **every** page (Queue, Add, Listened, Photo, Help, + Settings, Connect, Sign out), so tracks that add pages only fill the routes. +- Round badges are the number of albums waiting and listened; they update when an album moves. +- "Mark as listened" shows a note at the bottom with Undo and five stars, so rating takes one tap and + can be skipped. Delete also offers Undo. Nothing asks "are you sure". +- Play opens the installed app (`spotify:` / `tidal:`) and falls back to the web player after a second. +- Theme (system, light, dark) and language (English, Rioplatense Spanish) are cookies set by a plain form + POST to `/prefs`, so they apply to the first paint and work without scripts. The language otherwise + follows the browser's. +- Keyboard: `Ctrl+F` filter (or the search box on Add), `Ctrl+K` Add, `F1` Help, `Esc` clears the box. + +## Floor (checked in review) + +Responsive from 320 px; visible `:focus-visible` ring on everything; `prefers-reduced-motion` removes all +motion; text contrast 4.5:1 or more; every icon-only button has an `aria-label` and a `title`; touch +targets are 44 px or larger on phones; an `Escape`/keyboard path exists for every pointer action; a skip +link jumps to the main content. + +## Why not more Fluent components + +Fluent UI Blazor v5 is used for buttons, the switch, icons and the counter semantics. The text inputs and +the forms of the Identity pages are native elements styled with the same tokens, because those pages are +static server-rendered forms (no circuit), where a native `` is the only thing that posts +reliably, with or without scripts, and what password managers and passkeys understand. diff --git a/docs/WEB_PORT.md b/docs/WEB_PORT.md new file mode 100644 index 0000000..9c152a3 --- /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, `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. | + +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..e622ed3 --- /dev/null +++ b/docs/adr/0010-web-app-and-shared-queue.md @@ -0,0 +1,68 @@ +# 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; years outside 1000-3000 are dropped on both sides (`AlbumYear`), and a service id that is not letters and digits (at most 64) is dropped by the client; at most 1,000 albums per request, and the client +repeats until the response is empty or short (a page of 1,000 albums means "maybe more", even when nothing on it was new to the PC); 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. +- 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. diff --git a/docs/adr/0011-web-ocr.md b/docs/adr/0011-web-ocr.md new file mode 100644 index 0000000..2708bad --- /dev/null +++ b/docs/adr/0011-web-ocr.md @@ -0,0 +1,50 @@ +# ADR-0011: Tesseract, run as a child process, reads photos on the web + +- Status: Accepted +- Date: 2026-10-14 + +## Context + +The web app can't use Windows OCR ([ADR-0004](0004-windows-ocr.md)): the server may run Linux, and users send +photos from phones. It needs free, offline text recognition for Spanish and English that works on Windows and +Linux x64 hosts, with photo uploads treated as untrusted input ([ADR-0010](0010-web-app-and-shared-queue.md)). + +## Decision + +- **Tesseract 5 with the `spa` and `eng` models**, behind `IOcr` (Core, both target frameworks). The desktop + keeps `WindowsOcr`, an adapter over the existing `OcrService`. `OcrService.CleanLine` (year and + heading cleanup) moved to a file both builds compile. +- **The `tesseract` program, started as a child process**, not an in-process NuGet binding. The picture goes + in through stdin and TSV (one row per word, with boxes) comes out of stdout, so nothing is written to + disk. Why not `Tesseract` (charlesw) or `TesseractOCR` (Sicos1977): both ship native libraries for Windows only, + so Linux would need hand-built `.so` files and exact symlinks. The program is one `apt install + tesseract-ocr` on Linux (or an installer on Windows), a hung or crashing engine can be killed on a timeout + without touching the web process, and the TSV parser is plain tested code. `Ocr:TesseractPath` points at it. +- **Models**: downloaded once from `tessdata_fast` at a pinned release (4.1.0) into `/tessdata`, accepted only when the + 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 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. +- **Limits**: 12 MB per upload (checked on the length and again while reading), 40 s per photo, one photo at a + time per user and two across the server (the rest get 429), at most 300 lines of 300 characters back. +- **Languages** offered are `auto` (Spanish + English), `es` and `en`; only those reach the command line. + +## Consequences + +- Deploying needs the `tesseract` program (the Dockerfile installs it); without it Photo says the reader isn't + available, and the rest of the app works. +- Quality on real magazine photos is below Windows OCR on hard layouts; the user taps the lines they want, so + the engine only has to read. A cloud reader can be added behind `IOcr` later. +- Tests: logic against a fake `IOcr`; a golden-image test on the desktop's magazine page runs only when + `QUEUEIFY_TESSERACT` and `QUEUEIFY_TESSDATA` point at a program and models (it is skipped otherwise). + +## Alternatives considered + +- **In-process bindings**: faster per call, but native-library handling per OS, and a crash takes the server down. +- **Azure AI Vision / Google Vision**: better quality, paid and online; photos would leave the server. +- **Browser-side `tesseract.js`**: no server work, but a large download per phone and slow on low-end devices. diff --git a/docs/adr/README.md b/docs/adr/README.md index b8c7e1d..2c4249d 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -14,3 +14,5 @@ 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 | +| [0011](0011-web-ocr.md) | Tesseract, run as a child process, reads photos on the web | Accepted | diff --git a/tools/Pack/Pack.csproj b/tools/Pack/Pack.csproj index 6b449f3..2966058 100644 --- a/tools/Pack/Pack.csproj +++ b/tools/Pack/Pack.csproj @@ -4,8 +4,6 @@ Exe net10.0 win-x64 - enable - enable