diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 64a19103..45ec656d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -26,6 +26,7 @@ jobs: run: | dotnet test tests/PKForge.Domain.Tests/PKForge.Domain.Tests.csproj --no-restore --configuration Release dotnet test tests/PKForge.Engine.Tests/PKForge.Engine.Tests.csproj --no-restore --configuration Release + dotnet test tests/PKForge.Sync.Tests/PKForge.Sync.Tests.csproj --no-restore --configuration Release - name: Decode permanent release signing key if: github.ref_type == 'tag' env: diff --git a/.gitmodules b/.gitmodules index f6a34dfc..ab3e97f7 100644 --- a/.gitmodules +++ b/.gitmodules @@ -4,3 +4,6 @@ [submodule "external/PKHeX-Plugins"] path = external/PKHeX-Plugins url = https://github.com/santacrab2/PKHeX-Plugins.git +[submodule "external/pkforge-sync-server"] + path = external/pkforge-sync-server + url = https://github.com/YoruDev-Ryland/pkforge-sync-server.git diff --git a/PKForge.sln b/PKForge.sln index 90dae749..d173e07a 100644 --- a/PKForge.sln +++ b/PKForge.sln @@ -23,6 +23,12 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tools", "tools", "{07C2787E EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ChromePreview", "tools\ChromePreview\ChromePreview.csproj", "{8D502784-4EC5-4B72-A0A7-4AF7DF5038A9}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PKForge.Sync", "src\PKForge.Sync\PKForge.Sync.csproj", "{5219D9E3-D3C1-45A3-8416-F8BE1A062BB5}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0AB3BF05-4346-4AA6-1389-037BE0695223}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PKForge.Sync.Tests", "tests\PKForge.Sync.Tests\PKForge.Sync.Tests.csproj", "{D1F7EFBE-DD10-4720-B7A4-CCB48E7C8A6B}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -117,6 +123,30 @@ Global {8D502784-4EC5-4B72-A0A7-4AF7DF5038A9}.Release|x64.Build.0 = Release|Any CPU {8D502784-4EC5-4B72-A0A7-4AF7DF5038A9}.Release|x86.ActiveCfg = Release|Any CPU {8D502784-4EC5-4B72-A0A7-4AF7DF5038A9}.Release|x86.Build.0 = Release|Any CPU + {5219D9E3-D3C1-45A3-8416-F8BE1A062BB5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5219D9E3-D3C1-45A3-8416-F8BE1A062BB5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5219D9E3-D3C1-45A3-8416-F8BE1A062BB5}.Debug|x64.ActiveCfg = Debug|Any CPU + {5219D9E3-D3C1-45A3-8416-F8BE1A062BB5}.Debug|x64.Build.0 = Debug|Any CPU + {5219D9E3-D3C1-45A3-8416-F8BE1A062BB5}.Debug|x86.ActiveCfg = Debug|Any CPU + {5219D9E3-D3C1-45A3-8416-F8BE1A062BB5}.Debug|x86.Build.0 = Debug|Any CPU + {5219D9E3-D3C1-45A3-8416-F8BE1A062BB5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5219D9E3-D3C1-45A3-8416-F8BE1A062BB5}.Release|Any CPU.Build.0 = Release|Any CPU + {5219D9E3-D3C1-45A3-8416-F8BE1A062BB5}.Release|x64.ActiveCfg = Release|Any CPU + {5219D9E3-D3C1-45A3-8416-F8BE1A062BB5}.Release|x64.Build.0 = Release|Any CPU + {5219D9E3-D3C1-45A3-8416-F8BE1A062BB5}.Release|x86.ActiveCfg = Release|Any CPU + {5219D9E3-D3C1-45A3-8416-F8BE1A062BB5}.Release|x86.Build.0 = Release|Any CPU + {D1F7EFBE-DD10-4720-B7A4-CCB48E7C8A6B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D1F7EFBE-DD10-4720-B7A4-CCB48E7C8A6B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D1F7EFBE-DD10-4720-B7A4-CCB48E7C8A6B}.Debug|x64.ActiveCfg = Debug|Any CPU + {D1F7EFBE-DD10-4720-B7A4-CCB48E7C8A6B}.Debug|x64.Build.0 = Debug|Any CPU + {D1F7EFBE-DD10-4720-B7A4-CCB48E7C8A6B}.Debug|x86.ActiveCfg = Debug|Any CPU + {D1F7EFBE-DD10-4720-B7A4-CCB48E7C8A6B}.Debug|x86.Build.0 = Debug|Any CPU + {D1F7EFBE-DD10-4720-B7A4-CCB48E7C8A6B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D1F7EFBE-DD10-4720-B7A4-CCB48E7C8A6B}.Release|Any CPU.Build.0 = Release|Any CPU + {D1F7EFBE-DD10-4720-B7A4-CCB48E7C8A6B}.Release|x64.ActiveCfg = Release|Any CPU + {D1F7EFBE-DD10-4720-B7A4-CCB48E7C8A6B}.Release|x64.Build.0 = Release|Any CPU + {D1F7EFBE-DD10-4720-B7A4-CCB48E7C8A6B}.Release|x86.ActiveCfg = Release|Any CPU + {D1F7EFBE-DD10-4720-B7A4-CCB48E7C8A6B}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -124,5 +154,7 @@ Global GlobalSection(NestedProjects) = preSolution {59362056-D892-4D4D-A404-C344D7A25EEF} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {8D502784-4EC5-4B72-A0A7-4AF7DF5038A9} = {07C2787E-EAC7-C090-1BA3-A61EC2A24D84} + {5219D9E3-D3C1-45A3-8416-F8BE1A062BB5} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + {D1F7EFBE-DD10-4720-B7A4-CCB48E7C8A6B} = {0AB3BF05-4346-4AA6-1389-037BE0695223} EndGlobalSection EndGlobal diff --git a/README.md b/README.md index 7af6a7a5..250246ef 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,10 @@ Not affiliated with Nintendo, Game Freak, or The Pokémon Company. - **A Bank like Pokémon Home.** Store your whole collection in a cross-game Bank with as many themed boxes as you need. Organize with the gamepad, keep living dexes, and pull anything back out into any save whenever you need it. +- **Bank Sync (optional).** Keep one Bank on all your devices through a + [PKForge Sync server](https://github.com/YoruDev-Ryland/pkforge-sync-server) you run with Docker. + Every device keeps working offline, and changes made on two devices are shown to you, never + silently lost. - **Track your collection.** The Living Dex tracker follows all 1025 Pokémon across every generation, including shiny variants, so you always know what you still need. - **Living Dex Autopilot.** Builds a living dex from the Pokémon you already own across @@ -185,6 +189,7 @@ Join for updates, support, bug reports, feature requests, or just to chat about git submodule update --init --recursive dotnet test tests/PKForge.Domain.Tests/PKForge.Domain.Tests.csproj dotnet test tests/PKForge.Engine.Tests/PKForge.Engine.Tests.csproj +dotnet test tests/PKForge.Sync.Tests/PKForge.Sync.Tests.csproj dotnet build src/PKForge.App/PKForge.App.csproj -f net10.0-android ``` @@ -197,6 +202,7 @@ src/PKForge.Domain contracts and DTOs, no engine or Android dependencie src/PKForge.Engine adapters over pinned PKHeX.Core src/PKForge.AutoMod compiles the Auto Legality Mod against our Core src/PKForge.Infrastructure bank, backups, atomic save writer +src/PKForge.Sync Bank sync with a PKForge Sync server (offline-first, conflict-aware) src/PKForge.App MAUI app, SkiaSharp UI, gamepad and second screen src/PKForge.Chrome the design system: tokens and painters, pure Skia tools/ChromePreview renders the design system off-device diff --git a/external/pkforge-sync-server b/external/pkforge-sync-server new file mode 160000 index 00000000..40b1ae8e --- /dev/null +++ b/external/pkforge-sync-server @@ -0,0 +1 @@ +Subproject commit 40b1ae8e20ae175d3845c4f42e0e996440aebc3b diff --git a/src/PKForge.App/App.cs b/src/PKForge.App/App.cs index 4c33ef25..ab551407 100644 --- a/src/PKForge.App/App.cs +++ b/src/PKForge.App/App.cs @@ -5,13 +5,24 @@ public sealed class App : Application /// Raised when Android resumes the app (including after the install-permission screen). public static event Action? Resumed; public static event Action? Suspended; + + /// Android can stop the activity and recreate it without an OnResume; see . + private static readonly Domain.AppForeground Foreground = new(); + protected override void OnSleep() { - Suspended?.Invoke(); - Music?.PauseForBackground(); + if (Foreground.EnterBackground()) + { + Suspended?.Invoke(); + Music?.PauseForBackground(); + Sync?.Suspend(); + } base.OnSleep(); } + private static PKForge.Sync.SyncCoordinator? Sync => + IPlatformApplication.Current?.Services.GetService(); + private static Platforms.Android.MusicPlayer? Music => IPlatformApplication.Current?.Services.GetService() as Platforms.Android.MusicPlayer; @@ -20,13 +31,38 @@ protected override void OnStart() { base.OnStart(); Music?.MaybeAutostart(); + // Bank Sync: a first sync now, and another whenever the network comes back. + Connectivity.Current.ConnectivityChanged += (_, args) => + { + if (args.NetworkAccess != NetworkAccess.None) Sync?.NetworkAvailable(); + }; + Sync?.RequestSync(); } protected override void OnResume() { base.OnResume(); + BackInFront(); + } + + /// + /// A recreated activity (a configuration change, or Android reclaiming it while the process + /// lives) only activates its new window and never calls OnResume, which left Bank Sync paused + /// until the app restarted. Activation finishes the return in that case. + /// + private static void OnWindowActivated(object? sender, EventArgs args) + { + if (BackInFront()) Services.AppLog.Info("app", "Back in front without OnResume (the activity was recreated)"); + } + + /// Undoes OnSleep, once per return. False when the app never left. + private static bool BackInFront() + { + if (!Foreground.EnterForeground()) return false; Music?.ResumeFromBackground(); + Sync?.Resume(); Resumed?.Invoke(); + return true; } public App() @@ -36,6 +72,9 @@ public App() // Every page reads its chrome colors when it is built, so the scheme comes first. Services.ColorThemeSetting.ApplyStored(); + // Bank Sync: the living dex start box now lives with the Bank; move it before anything touches boxes. + Services.LivingDexAutopilot.MoveLegacyStartBox(); + // Warm both Skia faces off the ctor: the party view paints before the first // save opens, and its cached nickname font must never pin the placeholder. _ = Views.PixelFont.WarmAsync(); @@ -100,7 +139,9 @@ protected override Window CreateWindow(IActivationState? activationState) { var services = IPlatformApplication.Current?.Services ?? throw new InvalidOperationException("MAUI services are unavailable."); - return new Window(CreateRoot(services)); + var window = new Window(CreateRoot(services)); + window.Activated += OnWindowActivated; + return window; } catch (Exception error) { diff --git a/src/PKForge.App/MauiProgram.cs b/src/PKForge.App/MauiProgram.cs index bd386409..0f602eda 100644 --- a/src/PKForge.App/MauiProgram.cs +++ b/src/PKForge.App/MauiProgram.cs @@ -6,6 +6,7 @@ using PKForge.Domain; using PKForge.Engine; using PKForge.Infrastructure; +using PKForge.Sync; using SkiaSharp.Views.Maui.Controls.Hosting; namespace PKForge.App; @@ -40,9 +41,28 @@ public static MauiApp CreateMauiApp() builder.Services.AddSingleton(); builder.Services.AddSingleton(_ => new FileBackupService(Path.Combine(FileSystem.AppDataDirectory, "backups"))); + var bankRoot = Path.Combine(FileSystem.AppDataDirectory, "bank"); + builder.Services.AddSingleton(_ => new FileBankService(bankRoot)); + builder.Services.AddSingleton(_ => BankBoxDecor.Decor); + builder.Services.AddSingleton(_ => new SyncStateStore(Path.Combine(FileSystem.AppDataDirectory, "sync"))); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(sp => new SyncConnection( + sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService().For)); + builder.Services.AddSingleton(sp => new SyncedBankService( + sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService())); + builder.Services.AddSingleton(_ => new FileBankSnapshots(bankRoot, Path.Combine(FileSystem.AppDataDirectory, "bank-snapshots"))); + builder.Services.AddSingleton(sp => new SyncCoordinator( + sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), + sp.GetRequiredService()) + { + Trace = message => Services.AppLog.Info("sync", message), + }); + builder.Services.AddSingleton(); builder.Services.AddSingleton(sp => { - var bank = new FileBankService(Path.Combine(FileSystem.AppDataDirectory, "bank")); + var bank = new BankServiceSwitch( + sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService()); // One-time index migration, off the UI thread: legacy entries get their exact format // (only when provable) and sprite traits recorded, then the index is marked so no // entry is read again on later launches. Concurrent bank edits are never undone. @@ -103,6 +123,7 @@ public static MauiApp CreateMauiApp() builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); + builder.Services.AddTransient(); App.Trace("builder.Build()"); return builder.Build(); } diff --git a/src/PKForge.App/PKForge.App.csproj b/src/PKForge.App/PKForge.App.csproj index 721f7e9c..0fc76e73 100644 --- a/src/PKForge.App/PKForge.App.csproj +++ b/src/PKForge.App/PKForge.App.csproj @@ -90,5 +90,7 @@ + + diff --git a/src/PKForge.App/Platforms/Android/AndroidManifest.xml b/src/PKForge.App/Platforms/Android/AndroidManifest.xml index d0167391..ed2cd5db 100644 --- a/src/PKForge.App/Platforms/Android/AndroidManifest.xml +++ b/src/PKForge.App/Platforms/Android/AndroidManifest.xml @@ -1,5 +1,14 @@ - + + + + + + + + + diff --git a/src/PKForge.App/Platforms/Android/linker.xml b/src/PKForge.App/Platforms/Android/linker.xml index 677ae6c2..05c48d94 100644 --- a/src/PKForge.App/Platforms/Android/linker.xml +++ b/src/PKForge.App/Platforms/Android/linker.xml @@ -6,4 +6,7 @@ Preserve both engine assemblies completely. --> + + + diff --git a/src/PKForge.App/Services/BankBoxDecor.cs b/src/PKForge.App/Services/BankBoxDecor.cs index eeca70ef..3c1f7b36 100644 --- a/src/PKForge.App/Services/BankBoxDecor.cs +++ b/src/PKForge.App/Services/BankBoxDecor.cs @@ -2,17 +2,17 @@ namespace PKForge.App.Services; -/// The Bank's box names and wallpapers, stored beside its index. +/// +/// The Bank's box names, wallpapers and settings, stored beside its index. One instance for the whole +/// app (sync applies another device's decor through the same objects the pages read). +/// public static class BankBoxDecor { - private static readonly Lazy LazyNames = new(() => new BankBoxNames(Root)); - private static readonly Lazy LazyWallpapers = new(() => new BankBoxWallpapers(Root)); + private static readonly Lazy LazyDecor = new(() => new BankDecor(Path.Combine(FileSystem.AppDataDirectory, "bank"))); - private static string Root => Path.Combine(FileSystem.AppDataDirectory, "bank"); - - public static BankBoxNames Names => LazyNames.Value; - - public static BankBoxWallpapers Wallpapers => LazyWallpapers.Value; + public static BankDecor Decor => LazyDecor.Value; + public static BankBoxNames Names => Decor.Names; + public static BankBoxWallpapers Wallpapers => Decor.Wallpapers; /// The box's name, or "Box 07" when it has none. public static string Label(int box) => Names.Get(box) ?? $"Box {box + 1:00}"; diff --git a/src/PKForge.App/Services/BankRestorePoints.cs b/src/PKForge.App/Services/BankRestorePoints.cs new file mode 100644 index 00000000..47957741 --- /dev/null +++ b/src/PKForge.App/Services/BankRestorePoints.cs @@ -0,0 +1,39 @@ +using PKForge.Domain; +using PKForge.Infrastructure; +using PKForge.Sync; + +namespace PKForge.App.Services; + +/// +/// The Bank's own restore points (copies taken before Bank Sync replaced the whole Bank), listed beside the +/// save restore points. Restoring stops Bank Sync first: otherwise the old Bank would go out as new edits. +/// +public sealed class BankRestorePoints(FileBankSnapshots snapshots, FileBankService bank, BankDecor decor, SyncCoordinator sync) +{ + private const string IdPrefix = "bank:"; + + public static bool IsBank(BackupInfo point) => point.BackupId.StartsWith(IdPrefix, StringComparison.Ordinal); + + public bool SyncIsOn => sync.Connection.IsConnected; + + public IReadOnlyList List() => + [.. snapshots.List().Select(s => new BackupInfo(IdPrefix + s.Id, s.CreatedUtc, "", "PKForge Bank", "Bank", 0, s.SizeBytes, + s.PokemonCount is { } count ? $"{s.Reason} {count} Pokémon." : s.Reason))]; + + /// Puts the Bank back as it was in ; the current Bank becomes a restore point first. + public async Task RestoreAsync(BackupInfo point) + { + if (!IsBank(point)) throw new ArgumentException("Not a Bank restore point.", nameof(point)); + if (sync.Connection.IsConnected) + { + sync.SignOut(); + await sync.WhenIdleAsync(); + } + await Task.Run(() => + { + snapshots.Restore(point.BackupId[IdPrefix.Length..], $"Before restoring the Bank from {point.CreatedUtc:yyyy-MM-dd HH:mm} UTC."); + bank.Reload(); + decor.Reload(); + }); + } +} diff --git a/src/PKForge.App/Services/BankServiceSwitch.cs b/src/PKForge.App/Services/BankServiceSwitch.cs new file mode 100644 index 00000000..79ee3597 --- /dev/null +++ b/src/PKForge.App/Services/BankServiceSwitch.cs @@ -0,0 +1,32 @@ +using PKForge.Domain; +using PKForge.Infrastructure; +using PKForge.Sync; + +namespace PKForge.App.Services; + +/// +/// The Bank the app uses: the plain in Local mode, the +/// over the same files while this device is connected to a sync server. +/// Both wrap one Bank, so switching never moves or copies anything. +/// +public sealed class BankServiceSwitch(FileBankService local, SyncedBankService synced, SyncConnection connection) : IBankService +{ + private IBankService Current => connection.IsConnected ? synced : local; + + public IReadOnlyList GetAll() => Current.GetAll(); + public int BoxCount => Current.BoxCount; + public BankEntry Add(byte[] data, BankEntryInfo info) => Current.Add(data, info); + public IReadOnlyList AddMany(IReadOnlyList deposits) => Current.AddMany(deposits); + public byte[] GetData(Guid id) => Current.GetData(id); + public void Move(Guid id, int box, int slot) => Current.Move(id, box, slot); + public void Remove(Guid id) => Current.Remove(id); + public int RemoveMany(IReadOnlyList ids) => Current.RemoveMany(ids); + public void Replace(Guid id, byte[] data, BankEntryInfo info) => Current.Replace(id, data, info); + public void AddBox() => Current.AddBox(); + public void RemapBoxes(BankBoxRemap remap) => Current.RemapBoxes(remap); + public int UpdateInfo(IReadOnlyList<(Guid Id, BankEntryInfo Info)> updates) => Current.UpdateInfo(updates); + public int MigrationVersion => Current.MigrationVersion; + public int CompleteMigration(int version, IReadOnlyList<(Guid Id, BankEntryInfo Expected, BankEntryInfo Info)> updates) => + Current.CompleteMigration(version, updates); + public int Place(IReadOnlyList<(Guid Id, int Box, int Slot)> placements) => Current.Place(placements); +} diff --git a/src/PKForge.App/Services/LivingDexAutopilot.cs b/src/PKForge.App/Services/LivingDexAutopilot.cs index ba6b337e..9a11e091 100644 --- a/src/PKForge.App/Services/LivingDexAutopilot.cs +++ b/src/PKForge.App/Services/LivingDexAutopilot.cs @@ -48,17 +48,37 @@ public static class LivingDexAutopilot { private const string BankStartKey = "livingdex_bank_start_box"; - /// The Bank's living dex region, once a run created it (kept so later runs fill the same boxes). + /// + /// The Bank's living dex region, once a run created it (kept so later runs fill the same boxes). + /// Stored in the Bank's settings so it follows the Bank to every synced device. + /// public static int? BankStartBox { - get => Preferences.Default.Get(BankStartKey, -1) is var box and >= 0 ? box : null; + get + { + MoveLegacyStartBox(); + return BankBoxDecor.Decor.Settings.LivingDexStartBox; + } set { - if (value is { } box) Preferences.Default.Set(BankStartKey, box); - else Preferences.Default.Remove(BankStartKey); + MoveLegacyStartBox(); + BankBoxDecor.Decor.Settings.LivingDexStartBox = value; } } + /// + /// Older versions kept the start box in device preferences: moved once, value kept. Runs at app start, + /// before anything can rearrange boxes; the new copy is written before the old one is removed. + /// + public static void MoveLegacyStartBox() + { + if (!Preferences.Default.ContainsKey(BankStartKey)) return; + var legacy = Preferences.Default.Get(BankStartKey, -1); + if (legacy >= 0 && BankBoxDecor.Decor.Settings.LivingDexStartBox is null) + BankBoxDecor.Decor.Settings.LivingDexStartBox = legacy; + Preferences.Default.Remove(BankStartKey); + } + public static async Task ReadShelfAsync(IProgress? progress, CancellationToken cancellationToken) { var services = IPlatformApplication.Current?.Services ?? throw new InvalidOperationException("No services."); diff --git a/src/PKForge.App/Services/QrEntityService.cs b/src/PKForge.App/Services/QrEntityService.cs index 90dd18d8..7cf4c7e4 100644 --- a/src/PKForge.App/Services/QrEntityService.cs +++ b/src/PKForge.App/Services/QrEntityService.cs @@ -98,7 +98,11 @@ private static string OriginalTrainerOf(ISaveEngine engine, byte[] entityBytes, } /// Reads one QR's raw bytes out of an image; null when it holds no QR. - private static byte[]? TryDecodeQr(byte[] imageBytes) + private static byte[]? TryDecodeQr(byte[] imageBytes) => + TryDecodeText(imageBytes) is { } text ? Encoding.Latin1.GetBytes(text) : null; + + /// Reads one QR code's text out of an image; null when it holds no QR. + public static string? TryDecodeText(byte[] imageBytes) { try { @@ -121,7 +125,7 @@ private static string OriginalTrainerOf(ISaveEngine engine, byte[] entityBytes, }; var result = reader.Decode(new RGBLuminanceSource( rgba, scaled.Width, scaled.Height, RGBLuminanceSource.BitmapFormat.RGBA32)); - return result is null ? null : Encoding.Latin1.GetBytes(result.Text); + return result?.Text; } catch (Exception) { diff --git a/src/PKForge.App/Services/SyncPlatform.cs b/src/PKForge.App/Services/SyncPlatform.cs new file mode 100644 index 00000000..46322a60 --- /dev/null +++ b/src/PKForge.App/Services/SyncPlatform.cs @@ -0,0 +1,78 @@ +using System.Net.Http.Headers; +using PKForge.Sync; + +namespace PKForge.App.Services; + +/// Where the Bank Sync device key lives: Android's secure storage, read once. +public sealed class SecureSyncSecrets : ISyncSecrets +{ + private const string Key = "pkforge.sync.device-key.v1"; + private readonly Lock _gate = new(); + private bool _loaded; + private string? _value; + + public string? DeviceKey + { + get + { + lock (_gate) + { + if (!_loaded) + { + try { _value = SecureStorage.Default.GetAsync(Key).GetAwaiter().GetResult(); } + catch (Exception error) { AppLog.Warn("sync", $"Secure storage unreadable: {error.GetType().Name}"); _value = null; } + _loaded = true; + } + return _value; + } + } + set + { + lock (_gate) + { + _value = value; + _loaded = true; + if (value is null) SecureStorage.Default.Remove(Key); + else SecureStorage.Default.SetAsync(Key, value).GetAwaiter().GetResult(); + } + } + } +} + +/// One HttpClient per sync server address, reused for the life of the app. +public sealed class SyncHttp +{ + private readonly Lock _gate = new(); + private readonly Dictionary _clients = []; + + public HttpClient For(Uri server) + { + lock (_gate) + { + if (_clients.TryGetValue(server, out var client)) return client; + client = new HttpClient(new SocketsHttpHandler { ConnectTimeout = TimeSpan.FromSeconds(15), PooledConnectionLifetime = TimeSpan.FromMinutes(5) }) + { + BaseAddress = server, + Timeout = TimeSpan.FromSeconds(100), + }; + client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("PKForge", AppInfo.Current.VersionString)); + _clients[server] = client; + return client; + } + } +} + +public static class SyncPlatform +{ + /// How this device appears in the Devices list. + public static string DeviceName + { + get + { + var name = DeviceInfo.Current.Name?.Trim(); + if (!string.IsNullOrEmpty(name)) return name.Length > 100 ? name[..100] : name; + var model = $"{DeviceInfo.Current.Manufacturer} {DeviceInfo.Current.Model}".Trim(); + return model.Length > 0 ? model : "PKForge device"; + } + } +} diff --git a/src/PKForge.App/ViewModels/BackupHistoryViewModel.cs b/src/PKForge.App/ViewModels/BackupHistoryViewModel.cs index 7489437d..e3baa3e6 100644 --- a/src/PKForge.App/ViewModels/BackupHistoryViewModel.cs +++ b/src/PKForge.App/ViewModels/BackupHistoryViewModel.cs @@ -14,10 +14,12 @@ public partial class BackupHistoryViewModel : ObservableObject private readonly BoxBrowserViewModel _boxBrowser; private readonly ISaveEngine _engine; private readonly IBankService _bank; + private readonly BankRestorePoints _bankPoints; public BackupHistoryViewModel(IBackupService backups, ISaveSessionService sessions, ISafeSaveWriter writer, BoxBrowserViewModel boxBrowser, - ISaveEngine engine, IBankService bank) + ISaveEngine engine, IBankService bank, BankRestorePoints bankPoints) { + _bankPoints = bankPoints; _engine = engine; _bank = bank; _backups = backups; @@ -39,9 +41,10 @@ private async Task LoadAsync() Backups.Clear(); // With a save open, only its own restore points are listed: restoring writes into it. var open = _sessions.Current; - foreach (var info in await _backups.ListAsync()) - if (open is null || info.BelongsTo(open.Document.DocumentId, open.Snapshot)) - Backups.Add(info); + var saves = (await _backups.ListAsync()).Where(info => open is null || info.BelongsTo(open.Document.DocumentId, open.Snapshot)); + // The Bank's own restore points are listed whatever save is open: they restore the Bank, not a save. + foreach (var info in saves.Concat(_bankPoints.List()).OrderByDescending(info => info.CreatedUtc)) + Backups.Add(info); Status = Backups.Count == 0 ? "No backups yet. One is created automatically before every write." : CanRestore @@ -71,9 +74,18 @@ private async Task LoadAsync() } } + /// Whether restoring would stop Bank Sync first. + public bool RestoreStopsSync(BackupInfo backup) => BankRestorePoints.IsBank(backup) && _bankPoints.SyncIsOn; + /// Writes the backup's bytes into the open document; the current state is itself backed up first. public async Task RestoreAsync(BackupInfo backup) { + if (BankRestorePoints.IsBank(backup)) + { + await RestoreBankAsync(backup); + return; + } + var session = _sessions.Current; if (session is null) { @@ -115,4 +127,25 @@ public async Task RestoreAsync(BackupInfo backup) IsBusy = false; } } + + private async Task RestoreBankAsync(BackupInfo backup) + { + if (IsBusy) return; + try + { + IsBusy = true; + Status = "Restoring the Bank…"; + await _bankPoints.RestoreAsync(backup); + await LoadAsync(); + Status = "Bank restored. The Bank as it was just before is kept as a restore point."; + } + catch (Exception error) + { + Status = $"Restore aborted: {error.Message}"; + } + finally + { + IsBusy = false; + } + } } diff --git a/src/PKForge.App/Views/BackupHistoryPage.cs b/src/PKForge.App/Views/BackupHistoryPage.cs index 9214743f..c66e93a9 100644 --- a/src/PKForge.App/Views/BackupHistoryPage.cs +++ b/src/PKForge.App/Views/BackupHistoryPage.cs @@ -191,6 +191,16 @@ private async void OnSelected(object? sender, SelectionChangedEventArgs args) private async Task ConfirmRestoreAsync(BackupInfo backup) { + if (BankRestorePoints.IsBank(backup)) + { + var message = $"Put the Bank back as it was at {backup.CreatedUtc:yyyy-MM-dd HH:mm} UTC? The Bank as it is now is kept as a restore point first."; + if (_viewModel.RestoreStopsSync(backup)) + message += " Bank Sync is turned off first, so the old Bank isn't sent to your other devices. Turn it back on to choose whether to keep both Banks or use the server's."; + if (await PadMenu.ConfirmAsync(_hostGrid, "Restore the Bank?", message, "Restore")) + await _viewModel.RestoreAsync(backup); + return; + } + if (!_viewModel.CanRestore) { await PadMenu.ShowAsync(_hostGrid, "Restore", "Connect to a save first - restoring writes into the connected save.", "OK"); diff --git a/src/PKForge.App/Views/BankPage.cs b/src/PKForge.App/Views/BankPage.cs index f31c63ca..bc702f92 100644 --- a/src/PKForge.App/Views/BankPage.cs +++ b/src/PKForge.App/Views/BankPage.cs @@ -139,6 +139,9 @@ Button Tool(string text, Action action) ("-", HasSecondScreen ? "Page" : "Summary", () => OnPadButton(PadButton.Select)), ("+", "Menu", () => _ = OpenCursorMenuAsync())); + // The strip's word follows Bank Sync ("Open" while this Bank is local). + var strip = DsChrome.StatusStrip("Bank", out var flags, SyncFlag(Sync?.Status)); + _syncFlag = flags[0]; var root = new Grid { RowDefinitions = @@ -146,7 +149,7 @@ Button Tool(string text, Action action) new(GridLength.Auto), new(GridLength.Auto), new(GridLength.Star), new(GridLength.Auto), new(GridLength.Auto), ], - Children = { DsChrome.TitleBar(), DsChrome.StatusStrip("Bank", "Open"), bodyHost, statusHost, footer }, + Children = { DsChrome.TitleBar(), strip, bodyHost, statusHost, footer }, }; Grid.SetRow((View)root.Children[1], 1); Grid.SetRow(bodyHost, 2); @@ -172,11 +175,19 @@ protected override void OnAppearing() UpdatePreview(); UpdateStatus(); StartFactRotation(); + if (Sync is { } sync) + { + sync.StatusChanged += OnSyncStatus; + _syncFlag.Text = SyncFlag(sync.Status); + } + if (Synced is { } synced) synced.RemoteChangesApplied += OnRemoteChanges; } protected override void OnDisappearing() { base.OnDisappearing(); + if (Sync is { } sync) sync.StatusChanged -= OnSyncStatus; + if (Synced is { } synced) synced.RemoteChangesApplied -= OnRemoteChanges; _factTimer?.Stop(); IPlatformApplication.Current?.Services.GetService()?.Remove(this); _inspectCancel?.Cancel(); @@ -189,6 +200,34 @@ protected override void OnDisappearing() _ = Task.Run(facts.FlushHeldItemBackfill); } + private Label _syncFlag = null!; + + private static PKForge.Sync.SyncCoordinator? Sync => + IPlatformApplication.Current?.Services.GetService(); + + private static PKForge.Sync.SyncedBankService? Synced => + IPlatformApplication.Current?.Services.GetService(); + + /// The Bank's word in the status strip: "Open" while local, the sync state while connected. + private static string SyncFlag(PKForge.Sync.SyncStatus? status) => status?.Phase switch + { + null or PKForge.Sync.SyncPhase.NotConnected => "Open", + PKForge.Sync.SyncPhase.Syncing => "Syncing", + PKForge.Sync.SyncPhase.Offline => "Offline", + PKForge.Sync.SyncPhase.Idle when status.WritesDisabled => "Read-only", + PKForge.Sync.SyncPhase.Idle when status.Conflicts > 0 => status.Conflicts == 1 ? "1 conflict" : $"{status.Conflicts} conflicts", + PKForge.Sync.SyncPhase.Idle when status.PendingChanges => "Sync pending", + PKForge.Sync.SyncPhase.Idle => "Synced", + PKForge.Sync.SyncPhase.NeedsJoin => "Sync setup", + _ => "Sync paused", + }; + + private void OnSyncStatus(object? sender, PKForge.Sync.SyncStatus status) => + MainThread.BeginInvokeOnMainThread(() => _syncFlag.Text = SyncFlag(status)); + + /// Another device changed the Bank: show it without leaving the page. + private void OnRemoteChanges(object? sender, EventArgs args) => MainThread.BeginInvokeOnMainThread(() => ChangeBox(0)); + private SecondScreenClaim? _secondClaim; private async Task OpenLivingDexAsync() @@ -1115,10 +1154,8 @@ public bool ApplyBoxRemap(BankBoxRemap remap) _boxViewModel.Status = error.Message; return false; } - BankBoxDecor.Names.Remap(remap); - BankBoxDecor.Wallpapers.Remap(remap); - if (LivingDexAutopilot.BankStartBox is { } start) - LivingDexAutopilot.BankStartBox = remap.Map(start); + // Names, wallpapers and the living dex region follow their boxes together. + BankBoxDecor.Decor.Remap(remap); var marks = _marked.Where(m => remap.Map(m.Box) is not null).Select(m => (remap.Map(m.Box)!.Value, m.Slot)).ToList(); _marked.Clear(); _marked.UnionWith(marks); diff --git a/src/PKForge.App/Views/BankSyncPage.cs b/src/PKForge.App/Views/BankSyncPage.cs new file mode 100644 index 00000000..e4c811ef --- /dev/null +++ b/src/PKForge.App/Views/BankSyncPage.cs @@ -0,0 +1,644 @@ +using System.Text.Json; +using PKForge.App.Services; +using PKForge.App.Theme; +using PKForge.Sync; +using PKForge.Sync.Protocol; + +namespace PKForge.App.Views; + +/// +/// Bank Sync: connects this device's Bank to a PKForge Sync server +/// and holds everything about that link: syncing now, conflicts, devices, pairing, signing out. +/// +public sealed class BankSyncPage : ContentPage, IPadHandler +{ + private sealed record SyncAction(string Title, string Detail, string Icon, Func Run); + + private readonly SyncCoordinator _sync; + private readonly Grid _hostGrid; + private readonly Label _status; + private readonly VerticalStackLayout _rows = new() { Spacing = 4 }; + private readonly ScrollView _scroll; + private readonly List<(Border Row, SyncAction Action)> _actions = []; + private int _index; + private bool _busy; + + public BankSyncPage(SyncCoordinator sync) + { + _sync = sync; + Title = "Bank Sync"; + BackgroundColor = UiTokens.Housing; + NavigationPage.SetHasNavigationBar(this, false); + + var back = Kit.MiniCapsule("Back", UiTokens.Ink0); + back.WidthRequest = 72; + back.Clicked += async (_, _) => await Navigation.PopAsync(); + var header = Kit.HeaderBar("Bank Sync"); + header.VerticalOptions = LayoutOptions.Center; + var titleRow = new Grid + { + ColumnSpacing = 10, + ColumnDefinitions = [new(GridLength.Auto), new(GridLength.Star)], + Children = { back, header }, + }; + Grid.SetColumn(header, 1); + + _status = new Label + { + TextColor = UiTokens.InkSoft, + FontFamily = DsChrome.PixelFont, + FontSize = UiTokens.TextBody, + LineBreakMode = LineBreakMode.WordWrap, + }; + _scroll = new ScrollView { Content = _rows }; + var terminal = new Grid + { + RowSpacing = 10, + RowDefinitions = [new(GridLength.Auto), new(GridLength.Star)], + Children = { Kit.Well(_status, padding: 8), _scroll }, + }; + Grid.SetRow(_scroll, 1); + + var panel = Kit.DevicePanel(terminal); + var root = new Grid + { + Padding = new Thickness(14, 10), + RowSpacing = 10, + RowDefinitions = [new(GridLength.Auto), new(GridLength.Star)], + Children = { titleRow, panel }, + }; + Grid.SetRow(panel, 1); + _hostGrid = new Grid { Children = { DsChrome.GridBackground(), root } }; + Content = _hostGrid; + } + + protected override void OnAppearing() + { + base.OnAppearing(); + IPlatformApplication.Current?.Services.GetService()?.Push(this); + _sync.StatusChanged += OnStatus; + Rebuild(); + } + + protected override void OnDisappearing() + { + base.OnDisappearing(); + _sync.StatusChanged -= OnStatus; + IPlatformApplication.Current?.Services.GetService()?.Remove(this); + } + + private void OnStatus(object? sender, SyncStatus status) => MainThread.BeginInvokeOnMainThread(() => + { + if (!_busy) Rebuild(); + }); + + public bool OnPadButton(PadButton button) + { + switch (button) + { + case PadButton.Up: Focus(_index - 1); return true; + case PadButton.Down: Focus(_index + 1); return true; + case PadButton.A: + if (_index >= 0 && _index < _actions.Count) _ = RunAsync(_actions[_index].Action); + return true; + case PadButton.B: _ = Navigation.PopAsync(); return true; + default: return true; // own the pad while this page is up + } + } + + private void Focus(int index) + { + if (_actions.Count == 0) return; + _index = Math.Clamp(index, 0, _actions.Count - 1); + for (var i = 0; i < _actions.Count; i++) Kit.SetRowFocus(_actions[i].Row, i == _index, shaded: true); + ScrollIntoView(_actions[_index].Row); + } + + /// + /// More actions than fit on a handheld: the list rides along with the cursor (same as + /// PadMenu / BoxLayoutEditor) or the cursor walks off the bottom edge. Rebuild makes + /// new rows that have no bounds yet, so those scroll once they are laid out. + /// + private void ScrollIntoView(Border row) + { + if (row.Height > 0) + { + ScrollTo(row); + return; + } + void OnSized(object? sender, EventArgs e) + { + row.SizeChanged -= OnSized; + Dispatcher.Dispatch(() => ScrollTo(row)); + } + row.SizeChanged += OnSized; + } + + /// + /// Only while the row is still the focused one in the list: a status change rebuilds the rows, + /// and scrolling to a removed row throws ("element does not belong to this ScrollView"). + /// + private void ScrollTo(Border row) + { + if (row.Parent != _rows || _index >= _actions.Count || !ReferenceEquals(_actions[_index].Row, row)) return; + _ = _scroll.ScrollToAsync(row, ScrollToPosition.MakeVisible, false); + } + + private void Rebuild() + { + _status.Text = StatusText(_sync.Status); + _rows.Children.Clear(); + _actions.Clear(); + foreach (var action in Actions()) + { + var title = new Label { Text = action.Title, TextColor = UiTokens.Ink0, FontFamily = DsChrome.PixelFont, FontSize = 15 }; + var detail = new Label + { + Text = action.Detail, + TextColor = UiTokens.InkSoft, + FontFamily = DsChrome.PixelFont, + FontSize = UiTokens.TextSmall, + LineBreakMode = LineBreakMode.WordWrap, + }; + var icon = PksmIcons.Icon(action.Icon, 22); + var text = new VerticalStackLayout { Spacing = 2, Children = { title, detail } }; + var content = new Grid + { + ColumnSpacing = 10, + ColumnDefinitions = [new(GridLength.Auto), new(GridLength.Star)], + Children = { icon, text }, + }; + Grid.SetColumn(text, 1); + var row = Kit.Row(content, shaded: true, new Thickness(10, 8)); + var tap = new TapGestureRecognizer(); + var captured = action; + tap.Tapped += (_, _) => _ = RunAsync(captured); + row.GestureRecognizers.Add(tap); + _rows.Children.Add(row); + _actions.Add((row, action)); + } + Focus(_index); + } + + private async Task RunAsync(SyncAction action) + { + if (_busy) return; + _busy = true; + try { await action.Run(); } + catch (Exception error) + { + AppLog.Error("sync", $"{action.Title} failed", error); + await PadMenu.ShowAsync(_hostGrid, action.Title, $"Something went wrong: {error.Message}", "OK"); + } + finally + { + _busy = false; + Rebuild(); + } + } + + private IEnumerable Actions() + { + var status = _sync.Status; + if (status.Phase == SyncPhase.NotConnected) + { + var camera = HasCamera(); + var withCode = new SyncAction("Connect with a code", "Type the server and code another device shows under Add a device.", "key", ConnectWithCodeAsync); + if (!camera) yield return withCode; + yield return camera + ? new("Connect with a QR code", "Photograph the code another device shows under Bank Sync, Add a device.", "qr", ConnectWithQrAsync) + : new("Connect with a QR code picture", "Pick a screenshot or photo of the code another device shows.", "qr", ConnectWithQrAsync); + if (camera) yield return withCode; + yield return new("Connect to a server", "Type the address of a PKForge Sync server.", "link", ConnectToServerAsync); + yield break; + } + if (status.Phase == SyncPhase.SignedOut) + { + if (_sync.Store.Read(s => s.ServerUrl) is { } url) + yield return new("Sign in again", "Connect this device to the same server again. Its Bank is merged back in.", "key", () => ConnectToAsync(new Uri(url))); + yield return new("Stop syncing on this device", "Sign out. This device keeps its Bank as it is now.", "unlink", SignOutAsync); + yield break; + } + if (status.Phase == SyncPhase.NeedsJoin) + { + yield return new("Finish setting up", "Bring this device's Bank and the server's Bank together.", "confirm", JoinAsync); + } + else + { + yield return new("Sync now", "Send this device's changes and get the others'.", "refresh", SyncNowAsync); + if (status.Conflicts > 0) + yield return new($"Conflicts ({status.Conflicts})", "Changes made on two devices that need your choice.", "warning", ConflictsAsync); + yield return new("Add a device", "Show a code and QR code to connect another device to this Bank.", "qr", AddDeviceAsync); + yield return new("Devices", "See or remove the devices that sync this Bank.", "profile", DevicesAsync); + yield return new("Activity", "What sync did on its own, such as moving a Pokémon to a free slot.", "history", ActivityAsync); + if (status.Phase == SyncPhase.EmailNotVerified) + yield return new("Resend confirmation email", "Syncing starts once you open the link in it.", "send", ResendConfirmationAsync); + yield return new("Change password", "For the account this Bank belongs to.", "padlock", ChangePasswordAsync); + } + yield return new("Stop syncing on this device", "Sign out. This device keeps its Bank as it is now.", "unlink", SignOutAsync); + } + + private string StatusText(SyncStatus status) + { + if (status.Phase == SyncPhase.NotConnected) + return "Local: this Bank lives on this device only. Connect to a PKForge Sync server to keep one Bank on all your devices."; + var (url, name) = _sync.Store.Read(s => (s.ServerUrl, s.ServerName)); + var host = url is not null ? new Uri(url).Authority : "the server"; + var state = status.Phase switch + { + SyncPhase.NeedsJoin => "Connected. Finish setting up to start syncing.", + SyncPhase.Syncing => "Syncing…", + SyncPhase.Idle when status.PendingChanges => "Some changes are still waiting to sync.", + SyncPhase.Idle => "Up to date.", + _ => status.Message ?? "Sync is paused.", + }; + var server = name is null ? host : $"{name} ({host})"; + var lines = new List { status.Phase == SyncPhase.SignedOut ? $"Server: {server}" : $"Connected to {server}", state }; + if (status.LastSynced is { } last) lines.Add($"Last synced: {last.ToLocalTime():yyyy-MM-dd HH:mm}"); + if (status.Conflicts > 0) lines.Add(status.Conflicts == 1 ? "1 change needs your choice." : $"{status.Conflicts} changes need your choice."); + if (status.WritesDisabledMessage is { } reason) lines.Add(WritesDisabledText(reason)); + return string.Join("\n", lines); + } + + // ---- Connecting ---- + + private async Task ConnectToServerAsync() + { + var typed = await TextPopup.ShowLineAsync(_hostGrid, "Server address", "192.168.1.10:8080 or https://sync.example.com", keyboard: Keyboard.Url); + if (string.IsNullOrWhiteSpace(typed)) return; + if (!ServerAddress.TryParse(typed, out var server, out var error)) + { + await PadMenu.ShowAsync(_hostGrid, "Server address", error, "OK"); + return; + } + await ConnectToAsync(server); + } + + private async Task ConnectToAsync(Uri server) + { + var info = await WithLoadingAsync("Connecting", server.Authority, ct => _sync.Connection.ProbeAsync(server, ct)); + if (info is null) return; + var options = new List { new("Sign in", IconPath: "key", Detail: "Use the account you already have on this server.") }; + if (info.RegistrationOpen) options.Add(new("Create an account", IconPath: "profile", Detail: "Start a new Bank account on this server.")); + options.Add(new("Enter a code", IconPath: "qr", Detail: "The code another of your devices shows under Add a device.")); + var choice = await PadMenu.ShowAsync(_hostGrid, server.Authority, ServerBlurb(info), [.. options]); + switch (choice) + { + case "Sign in": await SignInAsync(server, create: false); break; + case "Create an account": await SignInAsync(server, create: true); break; + case "Enter a code": await PairWithTypedCodeAsync(server); break; + } + } + + /// How a refused push reads: the server's own reason, then what it means for this device. + private static string WritesDisabledText(string reason) => + $"This server isn't accepting changes for your account: {reason.Trim().TrimEnd('.')}. Your Bank stays on this device."; + + private static string ServerBlurb(ServerInfo info) => + (string.IsNullOrWhiteSpace(info.Name) ? "A PKForge Sync server." : $"{info.Name.Trim()}: a PKForge Sync server.") + + (info.EmailEnabled ? "" : " It can't send email, so a forgotten password is reset by whoever runs it."); + + private async Task SignInAsync(Uri server, bool create) + { + var title = create ? "Create an account" : "Sign in"; + var email = await TextPopup.ShowLineAsync(_hostGrid, title, "Email address", keyboard: Keyboard.Email); + if (string.IsNullOrWhiteSpace(email)) return; + var password = await TextPopup.ShowLineAsync(_hostGrid, "Password", create ? "At least 8 characters" : "Password", password: true); + if (string.IsNullOrEmpty(password)) return; + if (create) + { + var again = await TextPopup.ShowLineAsync(_hostGrid, "Password again", "The same password", password: true); + if (again != password) + { + await PadMenu.ShowAsync(_hostGrid, title, "The passwords don't match.", "OK"); + return; + } + } + var done = await WithLoadingAsync(create ? "Creating your account" : "Signing in", server.Authority, async ct => + { + if (create) await _sync.Connection.SignUpAsync(server, email, password, SyncPlatform.DeviceName, ct); + else await _sync.Connection.SignInAsync(server, email, password, SyncPlatform.DeviceName, ct); + return true; + }); + if (done) await AfterConnectingAsync(); + } + + private static bool HasCamera() + { + try { return MediaPicker.Default.IsCaptureSupported; } + catch (Exception error) when (error is FeatureNotSupportedException or NotImplementedException) { return false; } + } + + private async Task ConnectWithQrAsync() + { + byte[]? image = null; + try + { + var photo = HasCamera() + ? await MediaPicker.Default.CapturePhotoAsync(new MediaPickerOptions { Title = "Photograph the pairing QR code" }) + : await FilePicker.Default.PickAsync(new PickOptions { PickerTitle = "Pick a photo of the pairing QR code", FileTypes = FilePickerFileType.Images }); + if (photo is null) return; + await using var stream = await photo.OpenReadAsync(); + using var buffer = new MemoryStream(); + await stream.CopyToAsync(buffer); + image = buffer.ToArray(); + } + catch (Exception error) when (error is PermissionException or FeatureNotSupportedException) + { + await PadMenu.ShowAsync(_hostGrid, "QR code", "The camera isn't available. Use Connect with a code and type it instead.", "OK"); + return; + } + var text = await Task.Run(() => QrEntityService.TryDecodeText(image)); + if (!PairingLink.TryParse(text, out var server, out var code)) + { + await PadMenu.ShowAsync(_hostGrid, "QR code", "No PKForge Sync code found in that picture. Try again closer, or type the code.", "OK"); + return; + } + await ConfirmAndPairAsync(server, code); + } + + /// A code names its server: say which one before this Bank is shared with it. + private async Task ConfirmAndPairAsync(Uri server, string code) + { + if (!await PadMenu.ConfirmAsync(_hostGrid, $"Connect to {server.Authority}?", + $"This device's Bank will sync with the Bank at {server.Authority}. Only continue if the code came from one of your own devices.", "Connect")) + return; + await PairAsync(server, code); + } + + /// For devices without a camera: type the line another device shows under Add a device. + private async Task ConnectWithCodeAsync() + { + const string Title = "Server and code"; + var typed = ""; + Uri? server; + string code; + while (true) + { + var entry = await TextPopup.ShowLineAsync(_hostGrid, Title, "e.g. sync.example.com K7QM-4XTP", typed, keyboard: Keyboard.Url); + if (string.IsNullOrWhiteSpace(entry)) return; + typed = entry.Trim(); + if (PairingEntry.TryParse(typed, out server, out code, out var error)) break; + if (await PadMenu.ShowAsync(_hostGrid, Title, error, "Try again", "Cancel") != "Try again") return; + } + if (server is null) + { + var remembered = _sync.Store.Read(s => s.ServerUrl) is { } url && Uri.TryCreate(url, UriKind.Absolute, out var last) + ? PairingEntry.FormatServer(last) + : ""; + while (server is null) + { + var address = await TextPopup.ShowLineAsync(_hostGrid, "Server address", "The server your other device uses, e.g. sync.example.com", remembered, keyboard: Keyboard.Url); + if (string.IsNullOrWhiteSpace(address)) return; + remembered = address.Trim(); + if (ServerAddress.TryParse(remembered, out var parsed, out var error)) server = parsed; + else if (await PadMenu.ShowAsync(_hostGrid, "Server address", error, "Try again", "Cancel") != "Try again") return; + } + } + await ConfirmAndPairAsync(server, code); + } + + private async Task PairWithTypedCodeAsync(Uri server) + { + var code = await TextPopup.ShowLineAsync(_hostGrid, "Code from your other device", "8 letters and digits"); + if (string.IsNullOrWhiteSpace(code)) return; + await PairAsync(server, code); + } + + private async Task PairAsync(Uri server, string code) + { + var done = await WithLoadingAsync("Adding this device", server.Authority, async ct => + { + await _sync.Connection.PairAsync(server, code, SyncPlatform.DeviceName, ct); + return true; + }); + if (done) await AfterConnectingAsync(); + } + + private async Task AfterConnectingAsync() + { + _sync.Refresh(); + await JoinAsync(); + } + + private async Task JoinAsync() + { + var serverHas = await WithLoadingAsync("Looking at the server's Bank", "", async ct => await _sync.ServerHasPokemonAsync(ct)); + if (serverHas is null) return; + var mode = JoinMode.Merge; + if (serverHas == true && _sync.LocalPokemonCount > 0) + { + const string Both = "Keep both"; + const string Server = "Use the server's Bank"; + var choice = await PadMenu.ShowAsync(_hostGrid, "Two Banks", + $"This device has {_sync.LocalPokemonCount} Pokémon, and the server's Bank has Pokémon too.", + new PadOption(Both, IconPath: "confirm", Detail: "Every Pokémon from both Banks ends up in the one Bank. Nothing is lost."), + new PadOption(Server, IconPath: "download", Detail: "This device's Bank is replaced by the server's. A copy of it is kept first.")); + if (choice is null) return; + mode = choice == Server ? JoinMode.UseServer : JoinMode.Merge; + } + var report = await WithLoadingAsync("Syncing", "The first sync of a big Bank can take a while.", ct => _sync.JoinAsync(mode, ct)); + if (report is not null) await ReportAsync("Bank Sync is on", report); + else if (_sync.Status.Message is { } why) await PadMenu.ShowAsync(_hostGrid, "Not set up yet", $"{why}\nUse Finish setting up to try again.", "OK"); + } + + // ---- While connected ---- + + private async Task SyncNowAsync() + { + var report = await WithLoadingAsync("Syncing", "", ct => _sync.SyncNowAsync(ct)); + if (report is not null && (report.NewConflicts > 0 || report.Relocated > 0)) await ReportAsync("Synced", report); + } + + private async Task ReportAsync(string title, SyncReport report) + { + var lines = new List { $"Sent {report.Uploaded} and received {report.Downloaded} changes." }; + if (report.Relocated > 0) lines.Add($"{report.Relocated} Pokémon moved to free slots because another device used theirs (see Activity)."); + if (report.NewConflicts > 0) lines.Add($"{report.NewConflicts} changes need your choice: open Conflicts."); + if (report.WritesDisabled) lines.Add(WritesDisabledText(report.WritesDisabledMessage ?? "it refused them")); + await PadMenu.ShowAsync(_hostGrid, title, string.Join("\n", lines), "OK"); + } + + private async Task ConflictsAsync() + { + while (_sync.Store.Read(s => s.Conflicts.ToList()) is { Count: > 0 } conflicts) + { + var items = conflicts.Select((c, i) => new PickItem(i, Headline(c), Detail: Kind(c.Kind))).ToList(); + var picked = await PickerMenu.ShowAsync(_hostGrid, "Conflicts", items); + if (picked is null) return; + await ResolveAsync(conflicts[picked.Id]); + } + } + + private async Task ResolveAsync(SyncConflict conflict) + { + var (message, options) = conflict.Kind switch + { + ConflictKind.BothEdited => ( + $"Changed on this device: {Describe(conflict.Local)}.\nChanged on another device: {Describe(conflict.Server.Value)}.", + new[] { ("Keep both", ConflictChoice.KeepBoth), ("Keep this device's", ConflictChoice.KeepThisDevice), ("Keep the other device's", ConflictChoice.KeepOtherDevice) }), + ConflictKind.EditedHereReleasedThere => ( + $"You changed {Describe(conflict.Local)} here, but it was released on another device.", + new[] { ("Keep the edited copy", ConflictChoice.KeepThisDevice), ("Let it go", ConflictChoice.KeepOtherDevice) }), + ConflictKind.ReleasedHereEditedThere => ( + $"You released it here, but it was changed on another device: {Describe(conflict.Server.Value)}.", + new[] { ("Bring it back", ConflictChoice.KeepOtherDevice), ("Let it go", ConflictChoice.KeepThisDevice) }), + ConflictKind.Boxes => ( + "The box layout (names, wallpapers or order) changed on two devices. The Pokémon stay safe either way.", + new[] { ("Keep this device's layout", ConflictChoice.KeepThisDevice), ("Use the other device's layout", ConflictChoice.KeepOtherDevice) }), + _ => ( + "Bank settings (such as where the living dex starts) changed on two devices.", + new[] { ("Keep this device's", ConflictChoice.KeepThisDevice), ("Use the other device's", ConflictChoice.KeepOtherDevice) }), + }; + var picked = await PadMenu.ShowAsync(_hostGrid, Headline(conflict), message, options.Select(o => o.Item1).ToArray()); + if (picked is null) return; + var choice = options.First(o => o.Item1 == picked).Item2; + await WithLoadingAsync("Saving your choice", "", async ct => + { + await _sync.ResolveAsync(conflict.Id, choice, ct); + return true; + }); + } + + private static string Headline(SyncConflict conflict) => conflict.Kind switch + { + ConflictKind.Boxes => "Box layout", + ConflictKind.Settings => "Bank settings", + _ => Name(conflict.Local) ?? Name(conflict.Server.Value) ?? "A Pokémon", + }; + + private static string Kind(ConflictKind kind) => kind switch + { + ConflictKind.BothEdited => "Changed on two devices", + ConflictKind.EditedHereReleasedThere => "Changed here, released elsewhere", + ConflictKind.ReleasedHereEditedThere => "Released here, changed elsewhere", + ConflictKind.Boxes => "Box names, wallpapers or order", + _ => "Bank settings", + }; + + private static string? Name(JsonElement? value) + { + if (value is not { } mon) return null; + try { return SyncValues.ToEntry(Guid.Empty, SyncValues.ReadMon(mon)).Info.Nickname; } + catch (Exception error) when (error is JsonException or InvalidDataException) { return null; } + } + + private static string Describe(JsonElement? value) + { + if (value is not { } mon) return "released"; + try + { + var read = SyncValues.ReadMon(mon); + var info = SyncValues.ToEntry(Guid.Empty, read).Info; + return $"{info.Nickname}, Lv. {info.Level}, box {read.Box + 1} slot {read.Slot + 1}"; + } + catch (Exception error) when (error is JsonException or InvalidDataException) { return "a Pokémon"; } + } + + private async Task AddDeviceAsync() + { + var code = await WithLoadingAsync("Making a code", "", ct => _sync.Connection.CreateClient().CreatePairingCodeAsync(ct)); + if (code is null) return; + // The same server and code as a line to type on a device without a camera (Connect with a code). + var server = PairingLink.TryParse(code.QrPayload, out var linked, out _) ? linked + : _sync.Store.Read(s => s.ServerUrl) is { } url ? new Uri(url) : null; + var typeable = server is null ? null : $"No camera? Use Connect with a code and type:\n{PairingEntry.Format(server, code.Code)}"; + await QrPopup.ShowAsync(_hostGrid, $"Code {code.Code[..4]}-{code.Code[4..]} · 5 minutes", code.QrPayload, typeable); + } + + private async Task DevicesAsync() + { + var devices = await WithLoadingAsync("Getting devices", "", async ct => await _sync.Connection.CreateClient().GetDevicesAsync(ct)); + if (devices is null) return; + var items = devices.Select((d, i) => new PickItem(i, d.IsCurrent ? $"{d.Name} (this device)" : d.Name, + Detail: d.LastSyncUtc is { } at ? $"Last synced {at.ToLocalTime():yyyy-MM-dd HH:mm}" : "Not synced yet")).ToList(); + var picked = await PickerMenu.ShowAsync(_hostGrid, "Devices", items); + if (picked is null) return; + var device = devices[picked.Id]; + if (device.IsCurrent) + { + await PadMenu.ShowAsync(_hostGrid, device.Name, "This is this device. To sign it out, use Stop syncing on this device.", "OK"); + return; + } + if (!await PadMenu.ConfirmAsync(_hostGrid, $"Remove {device.Name}?", "It stops syncing at once and keeps its own copy of the Bank. It can be added again later.", "Remove")) + return; + await WithLoadingAsync("Removing", device.Name, async ct => + { + await _sync.Connection.CreateClient().RemoveDeviceAsync(device.Id, ct); + return true; + }); + } + + private async Task ActivityAsync() + { + var entries = _sync.Store.Read(s => s.Activity.AsEnumerable().Reverse().Take(50).ToList()); + if (entries.Count == 0) + { + await PadMenu.ShowAsync(_hostGrid, "Activity", "Nothing yet. Sync notes here anything it did on its own.", "OK"); + return; + } + await PickerMenu.ShowAsync(_hostGrid, "Activity", + entries.Select((e, i) => new PickItem(i, e.Message, Detail: e.Utc.ToLocalTime().ToString("yyyy-MM-dd HH:mm"))).ToList()); + } + + private async Task ResendConfirmationAsync() + { + if (await WithLoadingAsync("Sending", "", async ct => { await _sync.Connection.CreateClient().ResendVerificationAsync(ct); return true; })) + await PadMenu.ShowAsync(_hostGrid, "Confirmation email", "Sent. Open the link in it, then sync again.", "OK"); + } + + private async Task ChangePasswordAsync() + { + var current = await TextPopup.ShowLineAsync(_hostGrid, "Current password", "Password", password: true); + if (string.IsNullOrEmpty(current)) return; + var next = await TextPopup.ShowLineAsync(_hostGrid, "New password", "At least 8 characters", password: true); + if (string.IsNullOrEmpty(next)) return; + const string SignOut = "Sign them out"; + var others = await PadMenu.ShowAsync(_hostGrid, "Other devices", "Keep your other devices signed in?", "Keep them signed in", SignOut); + if (others is null) return; + if (await WithLoadingAsync("Changing password", "", async ct => + { + await _sync.Connection.CreateClient().ChangePasswordAsync(new ChangePasswordRequest(current, next, others == SignOut), ct); + return true; + })) + await PadMenu.ShowAsync(_hostGrid, "Password", "Changed.", "OK"); + } + + private async Task SignOutAsync() + { + if (!await PadMenu.ConfirmAsync(_hostGrid, "Stop syncing on this device?", + "This device keeps its Bank exactly as it is now. Changes made elsewhere no longer arrive here, and changes made here stay here.", + "Stop syncing")) + return; + _sync.SignOut(); + } + + /// Runs server work behind a loading window; explains failures and returns default for them. + private async Task WithLoadingAsync(string title, string subtitle, Func> work) + { + var loading = LoadingOverlay.Show(_hostGrid, title, subtitle); + string? problem = null; + try + { + return await Task.Run(() => work(loading.Cancellation.Token)); + } + catch (SyncApiException error) + { + problem = error.Message; + } + catch (OperationCanceledException) when (loading.Cancellation.IsCancellationRequested) + { + return default; + } + catch (Exception error) when (error is HttpRequestException or TaskCanceledException or IOException) + { + problem = "The server can't be reached. Check the address, and that this device is on the same network as the server."; + } + finally + { + loading.Close(); + } + await PadMenu.ShowAsync(_hostGrid, title, problem, "OK"); + return default; + } +} diff --git a/src/PKForge.App/Views/DsKit.cs b/src/PKForge.App/Views/DsKit.cs index 7e2b8c9a..63ac775d 100644 --- a/src/PKForge.App/Views/DsKit.cs +++ b/src/PKForge.App/Views/DsKit.cs @@ -416,15 +416,22 @@ public static View TitleBar(string title = "PKForge") } /// Dark status strip: a title on the left, status words + a battery on the right. - public static View StatusStrip(string left, params string[] flags) + public static View StatusStrip(string left, params string[] flags) => StatusStrip(left, out _, flags); + + /// The same strip, handing back its flag labels so a page can keep them current. + public static View StatusStrip(string left, out IReadOnlyList