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