diff --git a/README.md b/README.md index fda9f54..2293009 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ A Windows client for running several FourFold accounts side by side, each in its - **Community plugins**: open the plugin list (the wrench) and choose **Plugin hub** to search and install plugins made by the community. Every plugin is reviewed before it is listed, runs in a sandbox, and updates itself. To make one, see [PLUGIN_AUTHORS.md](PLUGIN_AUTHORS.md). - **Overlays**: drag XP/hr, stats, XP calculator and timer cards anywhere over the game. - **Second monitor**: pop the tools panel into its own window, or float individual cards on any screen. -- **Shared XP leaderboard**: daily, weekly and monthly XP gains across opted-in players. +- **XP leaderboard**: daily, weekly and monthly XP gains, read from [ffdb.info](https://ffdb.info). - **Store blocking**: optionally stop the in-game store and gold buttons from opening (Settings → Display). ## Shortcuts @@ -57,7 +57,7 @@ dotnet run --project src/FourFoldAccountManager.Desktop/FourFoldAccountManager.D
Leaderboard service (maintainers) -The desktop uses `https://fourfold-shared-xp-leaderboard.onrender.com`; override it with `FOURFOLD_LEADERBOARD_URL`. Local XP tracking works without it. The server reads public profiles itself and never accepts XP values from the client. +The desktop reads rankings from `https://ffdb.info/api/leaderboards`; override the host with `FOURFOLD_LEADERBOARD_URL`. It sends nothing, so it needs no server of ours. The service below is no longer used by the desktop. **Backup:** use PostgreSQL 16+ tools against Neon's direct TLS endpoint, with credentials in `PG*` environment variables. Dumps contain profile IDs and XP data, so keep them private. diff --git a/src/FourFoldAccountManager.Core.Tests/Panel/PanelLayoutPolicyTests.cs b/src/FourFoldAccountManager.Core.Tests/Panel/PanelLayoutPolicyTests.cs index 9fac040..d3483e1 100644 --- a/src/FourFoldAccountManager.Core.Tests/Panel/PanelLayoutPolicyTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Panel/PanelLayoutPolicyTests.cs @@ -6,24 +6,6 @@ namespace FourFoldAccountManager.Core.Tests.Panel; public sealed class PanelLayoutPolicyTests { - [Fact] - public void SettingsTransformsPreserveLeaderboardSharingPreference() - { - var accountId = Guid.NewGuid(); - var settings = PanelSettings.Default with - { - ShareLinkedAccounts = true, - SlotAccountIds = [accountId, null, null, null, null] - }; - - Assert.True(PanelLayoutPolicy.WithLayout(settings, PanelLayout.OneByTwo).ShareLinkedAccounts); - Assert.True(PanelLayoutPolicy.Assign(settings, 1, Guid.NewGuid()).ShareLinkedAccounts); - Assert.True(PanelLayoutPolicy.ClearAccount(settings, accountId).ShareLinkedAccounts); - Assert.True(PanelLayoutPolicy.WithSplitState(settings, - new PanelSplitState("2x2.rows", [0.7, 0.3])).ShareLinkedAccounts); - Assert.True(PanelLayoutPolicy.ResetSplitStates(settings).ShareLinkedAccounts); - } - [Fact] public void SettingsTransformsPreserveOverlayCardsAndClearAccountRemovesTheAccountsCards() { diff --git a/src/FourFoldAccountManager.Core/Data/SettingsStore.cs b/src/FourFoldAccountManager.Core/Data/SettingsStore.cs index 895f93a..56754d7 100644 --- a/src/FourFoldAccountManager.Core/Data/SettingsStore.cs +++ b/src/FourFoldAccountManager.Core/Data/SettingsStore.cs @@ -20,11 +20,7 @@ public async Task LoadAsync(CancellationToken cancellationToken = { if (!File.Exists(_paths.SettingsFilePath)) { - // An existing account file may predate the sharing setting. Keep that installation private. - return Validate(PanelSettings.Default with - { - ShareLinkedAccounts = !File.Exists(_paths.AccountsFilePath) - }); + return Validate(PanelSettings.Default); } try diff --git a/src/FourFoldAccountManager.Core/Models/PanelSettings.cs b/src/FourFoldAccountManager.Core/Models/PanelSettings.cs index 2905aa0..850c372 100644 --- a/src/FourFoldAccountManager.Core/Models/PanelSettings.cs +++ b/src/FourFoldAccountManager.Core/Models/PanelSettings.cs @@ -19,8 +19,6 @@ public PanelSettings(PanelLayout layout, IReadOnlyList slotAccountIds) public bool FillGameToPanel { get; init; } = false; - public bool ShareLinkedAccounts { get; init; } = false; - public bool ShowFullScreenExitButton { get; init; } = true; // Whether the plugin panel is open beside the strip. The name and JSON key predate the strip, so existing settings @@ -106,8 +104,5 @@ public PanelSettings(PanelLayout layout, IReadOnlyList slotAccountIds) [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public IReadOnlyDictionary? LegacyXpOverlayBoundsByAccount { get; init; } - public static PanelSettings Default => new(PanelLayout.TwoByTwo, new Guid?[5]) - { - ShareLinkedAccounts = true - }; + public static PanelSettings Default => new(PanelLayout.TwoByTwo, new Guid?[5]); } diff --git a/src/FourFoldAccountManager.Desktop.Tests/Leaderboard/LeaderboardCoordinatorTests.cs b/src/FourFoldAccountManager.Desktop.Tests/Leaderboard/LeaderboardCoordinatorTests.cs index 35f37e8..cdc7459 100644 --- a/src/FourFoldAccountManager.Desktop.Tests/Leaderboard/LeaderboardCoordinatorTests.cs +++ b/src/FourFoldAccountManager.Desktop.Tests/Leaderboard/LeaderboardCoordinatorTests.cs @@ -1,8 +1,6 @@ using System.Net; using System.Net.Http; using System.IO; -using System.Text.Json; -using System.Text.Json.Nodes; using FourFoldAccountManager.Core.Data; using FourFoldAccountManager.Core.Leaderboard; using FourFoldAccountManager.Desktop.Services; @@ -13,119 +11,64 @@ namespace FourFoldAccountManager.Desktop.Tests.Leaderboard; public sealed class LeaderboardCoordinatorTests { [Fact] - public async Task OldSettingsDefaultToPrivateAndOptInSurvivesRestart() - { - using var temp = new TempDirectory(); - var paths = new LocalDataPaths(temp.Path); - var settings = new SettingsStore(paths); - await settings.SaveAsync(await settings.LoadAsync()); - var oldJson = JsonNode.Parse(await File.ReadAllTextAsync(paths.SettingsFilePath))!.AsObject(); - oldJson.Remove("shareLinkedAccounts"); - await File.WriteAllTextAsync(paths.SettingsFilePath, oldJson.ToJsonString()); - Assert.False((await settings.LoadAsync()).ShareLinkedAccounts); - await settings.SaveAsync((await settings.LoadAsync()) with { ShareLinkedAccounts = true }); - Assert.True((await settings.LoadAsync()).ShareLinkedAccounts); - } - - [Fact] - public async Task InstallationIdPersistsAndWireRequestContainsOnlyPublicIdentity() + public async Task ReadsAnFfdbPageAndKeepsItAcrossRestarts() { using var temp = new TempDirectory(); var handler = new RecordingHandler(); - await using var first = CreateCoordinator(temp.Path, handler, sharing: true); - await first.InitializeAsync(); - await first.SyncParticipationAsync([new LeaderboardProfile(42, "Player")], [42], CancellationToken.None); - await first.FlushPendingAsync(); - var firstRequest = handler.Bodies.Single(); - using var json = JsonDocument.Parse(firstRequest); - var id = json.RootElement.GetProperty("installationId").GetGuid(); - Assert.NotEqual(Guid.Empty, id); - Assert.Equal(42, json.RootElement.GetProperty("activePlayerIds")[0].GetInt32()); - Assert.DoesNotContain("accountId", firstRequest, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("label", firstRequest, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain("password", firstRequest, StringComparison.OrdinalIgnoreCase); - await using var second = CreateCoordinator(temp.Path, new RecordingHandler(), sharing: true); - await second.InitializeAsync(); - Assert.Equal(id, second.InstallationId); - } + await using (var coordinator = CreateCoordinator(temp.Path, handler)) + { + var page = await coordinator.RefreshPageAsync(LeaderboardPeriod.Weekly, 2, 25, CancellationToken.None); + Assert.NotNull(page); + Assert.Equal(26, Assert.Single(page.Entries).Rank); + Assert.Equal("pinkmilk", page.Entries[0].Username); + Assert.Equal(41, page.TotalEntries); + } + Assert.Equal("https://ffdb.info/api/leaderboards?period=weekly&page=2", + Assert.Single(handler.Requests).ToString()); - [Fact] - public async Task OptOutPersistsLocallyBeforeRequestAndRetriesEmptyHeartbeat() - { - using var temp = new TempDirectory(); - var settings = new SettingsStore(new LocalDataPaths(temp.Path)); - await settings.SaveAsync((await settings.LoadAsync()) with { ShareLinkedAccounts = true }); - var handler = new RecordingHandler { Fail = true }; - await using var coordinator = CreateCoordinator(temp.Path, handler, sharing: true, - async (enabled, ct) => await settings.SaveAsync((await settings.LoadAsync(ct)) with { ShareLinkedAccounts = enabled }, ct)); - await coordinator.InitializeAsync(); - await coordinator.SetSharingEnabledAsync(false, CancellationToken.None); - Assert.False((await settings.LoadAsync()).ShareLinkedAccounts); - await coordinator.FlushPendingAsync(); - Assert.True(coordinator.HasPendingParticipation); - handler.Fail = false; - await coordinator.FlushPendingAsync(); - Assert.False(coordinator.HasPendingParticipation); - using var json = JsonDocument.Parse(handler.Bodies.Last()); - Assert.False(json.RootElement.GetProperty("sharingEnabled").GetBoolean()); - Assert.Empty(json.RootElement.GetProperty("activePlayerIds").EnumerateArray()); + await using var restarted = CreateCoordinator(temp.Path, new RecordingHandler { Fail = true }); + var cached = await restarted.GetCachedPageAsync(LeaderboardPeriod.Weekly, 2, 25, CancellationToken.None); + Assert.Equal("pinkmilk", Assert.Single(cached!.Entries).Username); + Assert.Null(await restarted.RefreshPageAsync(LeaderboardPeriod.Weekly, 2, 25, CancellationToken.None, + scheduleRetry: false)); } [Fact] - public async Task DefaultPrivateStateNeverContactsParticipationEndpoint() + public async Task OldStateFileWithParticipationFieldsStillLoadsItsCache() { using var temp = new TempDirectory(); - var handler = new RecordingHandler(); - await using var coordinator = CreateCoordinator(temp.Path, handler, sharing: false); - await coordinator.InitializeAsync(); - await coordinator.SyncParticipationAsync([new LeaderboardProfile(42, "Player")], [42], CancellationToken.None); - await coordinator.FlushPendingAsync(); - Assert.Empty(handler.Bodies); - } + var paths = new LocalDataPaths(temp.Path); + await using (var coordinator = CreateCoordinator(temp.Path, new RecordingHandler())) + await coordinator.RefreshPageAsync(LeaderboardPeriod.Weekly, 2, 25, CancellationToken.None); + var json = await File.ReadAllTextAsync(paths.LeaderboardStateFilePath); + await File.WriteAllTextAsync(paths.LeaderboardStateFilePath, json.Insert(1, + "\"installationId\":\"3f2c1e9a-0000-4000-8000-000000000001\",\"pendingParticipation\":null,")); - [Fact] - public async Task FailingLeaderboardDoesNotPreventLocalTrackerStart() - { - using var temp = new TempDirectory(); - await using var coordinator = CreateCoordinator(temp.Path, new RecordingHandler { Fail = true }, sharing: true); - await coordinator.InitializeAsync(); - await coordinator.SyncParticipationAsync([new LeaderboardProfile(42, "Player")], [42], CancellationToken.None); - await coordinator.FlushPendingAsync(); - await using var tracker = new XpTrackerCoordinator(new LocalDataPaths(temp.Path), _ => Task.CompletedTask); - var accountId = Guid.NewGuid(); - tracker.Start(accountId, "Player", 42); - Assert.Equal(accountId, Assert.Single(tracker.GetStates()).AccountId); - Assert.Equal(42, Assert.Single(tracker.GetActiveLeaderboardProfiles()).PlayerId); - Assert.True(coordinator.HasPendingParticipation); + var state = await new LeaderboardClientStateStore(paths).LoadAsync(); + Assert.Single(state.CachedPages); } - private static LeaderboardCoordinator CreateCoordinator(string path, RecordingHandler handler, bool sharing, - Func? persist = null) + private static LeaderboardCoordinator CreateCoordinator(string path, RecordingHandler handler) { - var client = new LeaderboardApiClient(new HttpClient(handler), - new LeaderboardApiOptions(new Uri("https://leaderboard.example/"))); - return new LeaderboardCoordinator(new LeaderboardClientStateStore(new LocalDataPaths(path)), - client, sharing, persist ?? ((_, _) => Task.CompletedTask)); + var client = new LeaderboardApiClient(new HttpClient(handler), LeaderboardApiOptions.FromEnvironment()!); + return new LeaderboardCoordinator(new LeaderboardClientStateStore(new LocalDataPaths(path)), client); } private sealed class RecordingHandler : HttpMessageHandler { - public List Bodies { get; } = []; + public List Requests { get; } = []; public bool Fail { get; set; } - public bool BadJson { get; set; } - public int GetRequests { get; private set; } - protected override async Task SendAsync(HttpRequestMessage request, CancellationToken ct) + protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) { - if (request.Content is not null) Bodies.Add(await request.Content.ReadAsStringAsync(ct)); - if (request.Method == HttpMethod.Get) GetRequests++; + Requests.Add(request.RequestUri!); if (Fail) throw new HttpRequestException("offline"); - if (request.Method == HttpMethod.Put) return new HttpResponseMessage(HttpStatusCode.NoContent); - var page = request.RequestUri!.Query.Contains("page=2&", StringComparison.Ordinal) ? 2 : 1; - var body = BadJson ? "{broken" : $$""" - {"period":0,"periodStartUtc":"2026-09-23T00:00:00Z","periodEndUtc":"2026-09-24T00:00:00Z","page":{{page}},"pageSize":50,"totalEntries":2,"generatedAtUtc":"2026-09-23T12:00:00Z","entries":[{"rank":{{page}},"playerId":{{41 + page}},"username":"Player {{page}}","xpGained":100,"lastSampledAtUtc":"2026-09-23T12:00:00Z","isStale":false}]} + var (start, end) = LeaderboardPeriodWindow.GetCurrent(LeaderboardPeriod.Weekly, DateTimeOffset.UtcNow); + // Shape copied from a live ffdb.info weekly page 2 response. + var body = $$""" + {"trackingGeneration":"fourfolddb-xp-2026-10-25","source":"fourfolddb","period":1,"periodStartUtc":"{{start:O}}","periodEndUtc":"{{end:O}}","pageSize":25,"totalEntries":41,"generatedAtUtc":"2026-11-04T19:03:58.900Z","trackingStartedAtUtc":"2026-10-25T22:31:55.062Z","lastCollectedAtUtc":"2026-11-04T19:03:58.805Z","initialPassComplete":true,"trackedPlayers":260,"page":2,"fetchedAtUtc":"2026-11-04T19:04:24.677Z","sourceUnavailable":false,"entries":[{"rank":26,"playerId":235,"username":"pinkmilk","xpGained":197839,"lastSampledAtUtc":"2026-11-04T19:03:58.805Z","isStale":false}]} """; - return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(body) }; + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(body) }); } } diff --git a/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs b/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs index 8d32b33..0befa83 100644 --- a/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs +++ b/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs @@ -92,11 +92,7 @@ public MainWindow() _browserSessions = new AccountBrowserSessionService(paths, () => _panelSettings.BlockStorePages); _xpTracker = new XpTrackerCoordinator(paths); _playerProfileService = _xpTracker.ProfileService; - _xpTracker.Changed += (_, _) => - { - RefreshTrackerRows(); - _ = SyncLeaderboardParticipationAsync(); - }; + _xpTracker.Changed += (_, _) => RefreshTrackerRows(); FullscreenOverlayTray.EditRequested += (_, _) => SetOverlayEditing(true); FullscreenOverlayTray.DoneRequested += (_, _) => SetOverlayEditing(false); FullscreenOverlayTray.CardToggleRequested += FullscreenOverlayTray_CardToggleRequested; @@ -308,21 +304,15 @@ private async void MainWindow_Loaded(object sender, RoutedEventArgs e) var apiOptions = LeaderboardApiOptions.FromEnvironment(); var apiClient = apiOptions is null ? null : new LeaderboardApiClient(new HttpClient(), apiOptions, ownsClient: true); - _leaderboard = new LeaderboardCoordinator(new LeaderboardClientStateStore(_dataPaths), - apiClient, _panelSettings.ShareLinkedAccounts, - async (enabled, _) => - { - await UpdateSettingsAsync(settings => settings with { ShareLinkedAccounts = enabled }); - }); + _leaderboard = new LeaderboardCoordinator(new LeaderboardClientStateStore(_dataPaths), apiClient); await _leaderboard.InitializeAsync(); - _ = SyncLeaderboardParticipationAsync(); } catch { // An unavailable leaderboard must not prevent local account management. _leaderboard = null; } - LeaderboardPanelView.Configure(_leaderboard, enabled => SetLeaderboardSharingAsync(enabled)); + LeaderboardPanelView.Configure(_leaderboard); _shortcuts?.Initialize(_panelSettings); UpdateTimerHotkeys(); RefreshPlainKeyBindings(); @@ -1985,7 +1975,6 @@ private async Task StartAssignedAccountAsync(PanelSl _xpTracker.Start(accountId, rankingUsername, profile?.RankingPlayerId); RefreshTrackerRows(); AttachBrowserView(slot, accountId, view); - _ = SyncLeaderboardParticipationAsync(); var loginPageResult = await _browserSessions.NavigateAndWaitAsync(accountId, FourFoldDestination.LoginUri); if (loginPageResult != BrowserNavigationResult.Navigated) @@ -3160,7 +3149,6 @@ private async Task CloseAccountViewAsync(Guid accountId, bool preserveFailure = } _xpTracker.Stop(accountId); RefreshTrackerRows(); - _ = SyncLeaderboardParticipationAsync(); UpdateAllSlotPresentations(); UpdateManageSlotsButton(); } @@ -3182,7 +3170,6 @@ private async Task CloseAllOpenViewsAsync() foreach (var accountId in _xpTracker.GetStates().Select(state => state.AccountId).ToArray()) _xpTracker.Stop(accountId); RefreshTrackerRows(); - _ = SyncLeaderboardParticipationAsync(); foreach (var slot in _slotCards) { slot.View = null; @@ -3217,42 +3204,6 @@ private static void DetachSlotEventHandlers(PanelSlotCard slot) private async Task SaveAccountsAsync() { await _accountStore.SaveAsync(_accounts.OrderBy(account => account.SortOrder).ToArray()); - _ = SyncLeaderboardParticipationAsync(); - } - - internal async Task SetLeaderboardSharingAsync(bool enabled, CancellationToken ct = default) - { - if (_leaderboard is not { } leaderboard) return; - await leaderboard.SetSharingEnabledAsync(enabled, ct); - await SyncLeaderboardParticipationAsync(); - } - - private async Task SyncLeaderboardParticipationAsync() - { - if (_leaderboard is not { } leaderboard) return; - try - { - var activeProfiles = _xpTracker.GetActiveLeaderboardProfiles() - .Where(profile => _openAccountIds.Contains(profile.AccountId)) - .ToDictionary(profile => profile.AccountId); - var profiles = _accounts.Select(account => - { - if (activeProfiles.TryGetValue(account.Id, out var active)) - return new LeaderboardProfile(active.PlayerId, active.Username); - - return new LeaderboardProfile(account.RankingPlayerId ?? 0, - account.RankingUsername?.Trim() ?? string.Empty); - }).Where(profile => profile.PlayerId > 0 && !string.IsNullOrWhiteSpace(profile.Username)) - .DistinctBy(profile => profile.PlayerId).ToArray(); - var linkedIds = profiles.Select(profile => profile.PlayerId).ToHashSet(); - var activeIds = activeProfiles.Values.Select(profile => profile.PlayerId) - .Where(linkedIds.Contains).Distinct().ToArray(); - await leaderboard.SyncParticipationAsync(profiles, activeIds, CancellationToken.None); - } - catch - { - // Participation is optional and must never interrupt view launch or local XP tracking. - } } private Task UpdateSettingsAsync(Func update) => @@ -3472,14 +3423,7 @@ await UpdateSettingsAsync(settings => { await CloseAllOpenViewsAsync(); await _xpTracker.DisposeAsync(); - if (_leaderboard is { } leaderboard) - { - await SyncLeaderboardParticipationAsync(); - using var goodbyeTimeout = new CancellationTokenSource(TimeSpan.FromSeconds(2)); - try { await leaderboard.FlushPendingAsync(goodbyeTimeout.Token); } - catch { /* The saved empty heartbeat is retried on next launch. */ } - await leaderboard.DisposeAsync(); - } + if (_leaderboard is { } leaderboard) await leaderboard.DisposeAsync(); } finally { diff --git a/src/FourFoldAccountManager.Desktop/Services/LeaderboardApiClient.cs b/src/FourFoldAccountManager.Desktop/Services/LeaderboardApiClient.cs index f0d6c82..6e36dc1 100644 --- a/src/FourFoldAccountManager.Desktop/Services/LeaderboardApiClient.cs +++ b/src/FourFoldAccountManager.Desktop/Services/LeaderboardApiClient.cs @@ -22,18 +22,6 @@ public LeaderboardApiClient(HttpClient httpClient, LeaderboardApiOptions options _ownsClient = ownsClient; } - public async Task SendHeartbeatAsync(ParticipationHeartbeat heartbeat, CancellationToken ct) - { - using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); - timeout.CancelAfter(TimeSpan.FromSeconds(75)); - using var request = new HttpRequestMessage(HttpMethod.Put, new Uri(_baseAddress, "v1/participation")) - { - Content = JsonContent.Create(heartbeat, options: JsonOptions) - }; - using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeout.Token); - response.EnsureSuccessStatusCode(); - } - public async Task GetPageAsync(LeaderboardPeriod period, int page, int pageSize, CancellationToken ct) { if (!Enum.IsDefined(period) || page < 1 || pageSize is < 1 or > 100) @@ -41,7 +29,8 @@ public async Task GetPageAsync(LeaderboardPeriod period, int pa using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); timeout.CancelAfter(TimeSpan.FromSeconds(75)); var periodText = period.ToString().ToLowerInvariant(); - var uri = new Uri(_baseAddress, $"v1/leaderboards/{periodText}?page={page}&pageSize={pageSize}"); + // ffdb.info always serves 25 a page; IsValidPage rejects any other size. + var uri = new Uri(_baseAddress, $"api/leaderboards?period={periodText}&page={page}"); using var response = await _httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, timeout.Token); response.EnsureSuccessStatusCode(); var result = await response.Content.ReadFromJsonAsync(JsonOptions, timeout.Token); diff --git a/src/FourFoldAccountManager.Desktop/Services/LeaderboardApiOptions.cs b/src/FourFoldAccountManager.Desktop/Services/LeaderboardApiOptions.cs index 08cf924..f342461 100644 --- a/src/FourFoldAccountManager.Desktop/Services/LeaderboardApiOptions.cs +++ b/src/FourFoldAccountManager.Desktop/Services/LeaderboardApiOptions.cs @@ -2,7 +2,7 @@ namespace FourFoldAccountManager.Desktop.Services; public sealed record LeaderboardApiOptions(Uri BaseAddress) { - private const string DefaultServiceUrl = "https://fourfold-shared-xp-leaderboard.onrender.com"; + private const string DefaultServiceUrl = "https://ffdb.info"; public static LeaderboardApiOptions? FromConfiguredUrl(string? configured) { diff --git a/src/FourFoldAccountManager.Desktop/Services/LeaderboardClientStateStore.cs b/src/FourFoldAccountManager.Desktop/Services/LeaderboardClientStateStore.cs index 9ece556..a35603b 100644 --- a/src/FourFoldAccountManager.Desktop/Services/LeaderboardClientStateStore.cs +++ b/src/FourFoldAccountManager.Desktop/Services/LeaderboardClientStateStore.cs @@ -5,10 +5,7 @@ namespace FourFoldAccountManager.Desktop.Services; -public sealed record LeaderboardClientState( - Guid InstallationId, - IReadOnlyList CachedPages, - ParticipationHeartbeat? PendingParticipation); +public sealed record LeaderboardClientState(IReadOnlyList CachedPages); public sealed class LeaderboardClientStateStore { @@ -19,26 +16,22 @@ public sealed class LeaderboardClientStateStore public async Task LoadAsync(CancellationToken ct = default) { if (!File.Exists(_paths.LeaderboardStateFilePath)) - return new LeaderboardClientState(Guid.NewGuid(), [], null); + return new LeaderboardClientState([]); try { await using var stream = File.OpenRead(_paths.LeaderboardStateFilePath); var value = await JsonSerializer.DeserializeAsync(stream, AtomicJsonFile.Options, ct); - if (value is null || value.InstallationId == Guid.Empty) throw new InvalidDataException(); - return new LeaderboardClientState(value.InstallationId, + if (value is null) throw new InvalidDataException(); + return new LeaderboardClientState( (value.CachedPages ?? []).Where(page => page is not null && - LeaderboardApiClient.IsValidPage(page, page.Period, page.Page, page.PageSize)).ToArray(), - value.PendingParticipation); + LeaderboardApiClient.IsValidPage(page, page.Period, page.Page, page.PageSize)).ToArray()); } catch (Exception ex) when (ex is JsonException or InvalidDataException or IOException) { - return new LeaderboardClientState(Guid.NewGuid(), [], null); + return new LeaderboardClientState([]); } } - public async Task SaveAsync(LeaderboardClientState state, CancellationToken ct = default) - { - if (state.InstallationId == Guid.Empty) throw new ArgumentException("Installation ID is required.", nameof(state)); - await AtomicJsonFile.WriteAsync(_paths.LeaderboardStateFilePath, state, ct); - } + public Task SaveAsync(LeaderboardClientState state, CancellationToken ct = default) => + AtomicJsonFile.WriteAsync(_paths.LeaderboardStateFilePath, state, ct); } diff --git a/src/FourFoldAccountManager.Desktop/Services/LeaderboardCoordinator.cs b/src/FourFoldAccountManager.Desktop/Services/LeaderboardCoordinator.cs index 5ed404d..d98945a 100644 --- a/src/FourFoldAccountManager.Desktop/Services/LeaderboardCoordinator.cs +++ b/src/FourFoldAccountManager.Desktop/Services/LeaderboardCoordinator.cs @@ -11,157 +11,26 @@ public sealed class LeaderboardCoordinator : IAsyncDisposable { private readonly LeaderboardClientStateStore _store; private readonly LeaderboardApiClient? _client; - private readonly Func _persistSharing; private readonly SemaphoreSlim _stateGate = new(1, 1); - private readonly SemaphoreSlim _requestGate = new(1, 1); private readonly CancellationTokenSource _lifetime = new(); private readonly HashSet<(LeaderboardPeriod Period, int Page, int PageSize)> _pageRetries = []; private LeaderboardClientState? _state; - private IReadOnlyList _linkedProfiles = []; - private IReadOnlyList _activePlayerIds = []; - private Task? _renewalTask; - private Task? _retryTask; - private bool _sharingEnabled; - private bool _hasSynced; private bool _disposed; - public LeaderboardCoordinator(LeaderboardClientStateStore store, LeaderboardApiClient? client, - bool sharingEnabled, Func persistSharing) + public LeaderboardCoordinator(LeaderboardClientStateStore store, LeaderboardApiClient? client) { _store = store; _client = client; - _sharingEnabled = sharingEnabled; - _persistSharing = persistSharing; } public event EventHandler? StatusChanged; - public Guid InstallationId => _state?.InstallationId ?? Guid.Empty; public bool IsConfigured => _client is not null; - public bool SharingEnabled => _sharingEnabled; - public bool HasPendingParticipation => _state?.PendingParticipation is not null; public async Task InitializeAsync(CancellationToken ct = default) { await _stateGate.WaitAsync(ct); - try - { - if (_state is not null) return; - _state = await _store.LoadAsync(ct); - if (_state.PendingParticipation is { } pending) - { - var safePending = !_sharingEnabled - ? DisabledHeartbeat(_state.InstallationId) - : pending with { ActivePlayerIds = [] }; - _state = _state with { PendingParticipation = safePending }; - } - await _store.SaveAsync(_state, ct); - } - finally { _stateGate.Release(); } - if (HasPendingParticipation) StartRetryLoop(); - } - - public async Task SetSharingEnabledAsync(bool enabled, CancellationToken ct) - { - // The opt-out is durable before the first network request is attempted. - await _persistSharing(enabled, ct); - _sharingEnabled = enabled; - await QueueParticipationAsync(ct); - } - - public async Task SyncParticipationAsync(IReadOnlyList linkedProfiles, - IReadOnlyCollection activePlayerIds, CancellationToken ct) - { - ArgumentNullException.ThrowIfNull(linkedProfiles); - ArgumentNullException.ThrowIfNull(activePlayerIds); - var nextLinkedProfiles = linkedProfiles.Where(profile => profile.PlayerId > 0 && - !string.IsNullOrWhiteSpace(profile.Username)) - .GroupBy(profile => profile.PlayerId) - .Select(group => group.First()).Take(1000).ToArray(); - var linkedIds = nextLinkedProfiles.Select(profile => profile.PlayerId).ToHashSet(); - var nextActivePlayerIds = activePlayerIds.Where(linkedIds.Contains).Distinct().Take(5).ToArray(); - var changed = !_hasSynced || !_linkedProfiles.SequenceEqual(nextLinkedProfiles) || - !_activePlayerIds.SequenceEqual(nextActivePlayerIds); - _linkedProfiles = nextLinkedProfiles; - _activePlayerIds = nextActivePlayerIds; - _hasSynced = true; - if (changed && (_sharingEnabled || HasPendingParticipation)) - await QueueParticipationAsync(ct); - if (_sharingEnabled && _activePlayerIds.Count > 0 && _renewalTask is null) - _renewalTask = RunRenewalLoopAsync(_lifetime.Token); - } - - private async Task QueueParticipationAsync(CancellationToken ct) - { - await EnsureInitializedAsync(ct); - await _stateGate.WaitAsync(ct); - try - { - var heartbeat = _sharingEnabled - ? new ParticipationHeartbeat(_state!.InstallationId, true, _linkedProfiles, _activePlayerIds) - : DisabledHeartbeat(_state!.InstallationId); - _state = _state with { PendingParticipation = heartbeat }; - await _store.SaveAsync(_state, ct); - } + try { _state ??= await _store.LoadAsync(ct); } finally { _stateGate.Release(); } - _ = FlushPendingAsync(_lifetime.Token); - StartRetryLoop(); - } - - private void StartRetryLoop() - { - if (_client is null || _retryTask is { IsCompleted: false } || _disposed) return; - _retryTask = RunRetryLoopAsync(_lifetime.Token); - } - - private async Task RunRetryLoopAsync(CancellationToken ct) - { - var delaySeconds = 15; - try - { - while (HasPendingParticipation && !ct.IsCancellationRequested) - { - await Task.Delay(TimeSpan.FromSeconds(delaySeconds), ct); - await FlushPendingAsync(ct); - delaySeconds = Math.Min(delaySeconds * 2, 120); - } - } - catch (OperationCanceledException) when (ct.IsCancellationRequested) { } - } - - private static ParticipationHeartbeat DisabledHeartbeat(Guid id) => new(id, false, [], []); - - public async Task FlushPendingAsync(CancellationToken ct = default) - { - if (_client is null || _disposed) return; - var acquired = false; - try - { - await _requestGate.WaitAsync(ct); - acquired = true; - var pending = _state?.PendingParticipation; - if (pending is null) return; - try - { - await _client.SendHeartbeatAsync(pending, ct); - await _stateGate.WaitAsync(ct); - try - { - if (ReferenceEquals(_state?.PendingParticipation, pending)) - { - _state = _state with { PendingParticipation = null }; - await _store.SaveAsync(_state, ct); - } - } - finally { _stateGate.Release(); } - StatusChanged?.Invoke(this, new LeaderboardStatus(true, false, DateTimeOffset.UtcNow)); - } - catch (Exception ex) when (ex is HttpRequestException or InvalidDataException or OperationCanceledException or IOException) - { - StatusChanged?.Invoke(this, new LeaderboardStatus(false, true, null)); - } - } - catch (OperationCanceledException) when (ct.IsCancellationRequested) { } - finally { if (acquired) _requestGate.Release(); } } public async Task GetCachedPageAsync(LeaderboardPeriod period, int page, int pageSize, @@ -176,7 +45,7 @@ public async Task FlushPendingAsync(CancellationToken ct = default) public async Task GetPageAsync(LeaderboardPeriod period, int page, int pageSize, CancellationToken ct) { - await EnsureInitializedAsync(ct); + await InitializeAsync(ct); var cached = _state!.CachedPages.FirstOrDefault(candidate => candidate.Period == period && candidate.Page == page && candidate.PageSize == pageSize); if (cached is not null) @@ -250,36 +119,13 @@ private async Task RetryPageAsync((LeaderboardPeriod Period, int Page, int PageS } } - private async Task RunRenewalLoopAsync(CancellationToken ct) - { - using var timer = new PeriodicTimer(TimeSpan.FromMinutes(1)); - try - { - while (await timer.WaitForNextTickAsync(ct)) - { - try - { - if (_sharingEnabled && _activePlayerIds.Count > 0) - await QueueParticipationAsync(ct); - else if (HasPendingParticipation) - await FlushPendingAsync(ct); - } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { } - } - } - catch (OperationCanceledException) when (ct.IsCancellationRequested) { } - } - - private Task EnsureInitializedAsync(CancellationToken ct) => _state is null ? InitializeAsync(ct) : Task.CompletedTask; - - public async ValueTask DisposeAsync() + public ValueTask DisposeAsync() { - if (_disposed) return; + if (_disposed) return ValueTask.CompletedTask; _disposed = true; _lifetime.Cancel(); - if (_renewalTask is not null) await _renewalTask; - if (_retryTask is not null) await _retryTask; _client?.Dispose(); _lifetime.Dispose(); + return ValueTask.CompletedTask; } } diff --git a/src/FourFoldAccountManager.Desktop/Views/LeaderboardPanel.xaml b/src/FourFoldAccountManager.Desktop/Views/LeaderboardPanel.xaml index f140d5a..0f622c2 100644 --- a/src/FourFoldAccountManager.Desktop/Views/LeaderboardPanel.xaml +++ b/src/FourFoldAccountManager.Desktop/Views/LeaderboardPanel.xaml @@ -96,10 +96,7 @@ - - diff --git a/src/FourFoldAccountManager.Desktop/Views/LeaderboardPanel.xaml.cs b/src/FourFoldAccountManager.Desktop/Views/LeaderboardPanel.xaml.cs index 82dcf13..a527790 100644 --- a/src/FourFoldAccountManager.Desktop/Views/LeaderboardPanel.xaml.cs +++ b/src/FourFoldAccountManager.Desktop/Views/LeaderboardPanel.xaml.cs @@ -11,15 +11,12 @@ public partial class LeaderboardPanel : UserControl { private const int PageSize = 25; private LeaderboardCoordinator? _coordinator; - private Func? _setSharing; private CancellationTokenSource? _refreshCancellation; private LeaderboardPeriod _period = LeaderboardPeriod.Daily; private LeaderboardPage? _page; private int _pageNumber = 1; private int _refreshVersion; private bool _visible; - private bool _configured; - private bool _changingSharing; private bool _showingCachedData; public LeaderboardPanel() @@ -31,17 +28,11 @@ public LeaderboardPanel() StateText.Text = "Open the leaderboard to load rankings."; } - public void Configure(LeaderboardCoordinator? coordinator, Func setSharing) + public void Configure(LeaderboardCoordinator? coordinator) { if (_coordinator is not null) _coordinator.StatusChanged -= Coordinator_StatusChanged; _coordinator = coordinator; - _setSharing = setSharing; - _configured = coordinator is not null; if (coordinator is not null) coordinator.StatusChanged += Coordinator_StatusChanged; - _changingSharing = true; - ShareLinkedAccountsCheckBox.IsChecked = coordinator?.SharingEnabled == true; - _changingSharing = false; - ShareLinkedAccountsCheckBox.IsEnabled = _configured; StateText.Text = coordinator is null ? "Leaderboard settings could not be loaded on this PC." : coordinator.IsConfigured @@ -269,28 +260,6 @@ private void GoToPage(int page) private void Refresh_Click(object sender, RoutedEventArgs e) => _ = RefreshAsync(); - private async void SharingChanged(object sender, RoutedEventArgs e) - { - if (_changingSharing || !_configured || _setSharing is null || _coordinator is null) return; - var enabled = ShareLinkedAccountsCheckBox.IsChecked == true; - ShareLinkedAccountsCheckBox.IsEnabled = false; - try - { - await _setSharing(enabled); - StateText.Text = enabled - ? "Sharing enabled for linked accounts. Active game views can contribute XP gains." - : "Sharing disabled on this device. Previously recorded gains remain visible until their UTC periods end."; - } - catch - { - _changingSharing = true; - ShareLinkedAccountsCheckBox.IsChecked = _coordinator.SharingEnabled; - _changingSharing = false; - StateText.Text = "Could not save the sharing preference. Try again."; - } - finally { ShareLinkedAccountsCheckBox.IsEnabled = true; } - } - private sealed record LeaderboardRow(string Rank, string Username, string XpGained, string LastSampled, string SampleStatus); }