From 7d2e797140cc473634d36abed74d3fe025fd117e Mon Sep 17 00:00:00 2001 From: director-mouse <340716031+director-mouse@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:53:26 +0100 Subject: [PATCH 1/6] fix(MyAnonaMouse): persist refreshed mam_id cookies Save rotated mam_id values from successful account-status responses in indexer settings so the existing refresh service persists them. This prevents requests from continually reusing the original session cookie until it expires. --- .../Indexers/MyAnonaMouse/MyAnonaMouse.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouse.cs b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouse.cs index 94438a163..be0de59a4 100644 --- a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouse.cs +++ b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouse.cs @@ -242,6 +242,21 @@ protected override async Task TestConnection() } } + // Requests always send Settings.MamId, so adopt MAM's rotated cookie or the original expires after + // ~30 days. MyAnonaMouseAccountStatusService saves Settings after each successful refresh. + private void PersistRefreshedMamId(HttpResponse response) + { + if (!response.GetCookies().TryGetValue("mam_id", out var refreshedMamId) || + string.IsNullOrWhiteSpace(refreshedMamId) || + string.Equals(refreshedMamId, Settings.MamId, StringComparison.Ordinal)) + { + return; + } + + _logger.Info("MAM issued a refreshed mam_id for indexer '{0}', persisting it", Definition?.Name); + Settings.MamId = refreshedMamId; + } + public async Task RefreshAccountStatus() { var request = new HttpRequestBuilder($"{Settings.BaseUrl.TrimEnd('/')}/jsonLoad.php?snatch_summary&pretty") @@ -263,6 +278,8 @@ public async Task RefreshAccountStatus() throw new InvalidOperationException($"Failed to fetch MAM user data: HTTP {(int)response.StatusCode} {response.StatusCode}"); } + PersistRefreshedMamId(response); + var userData = JsonConvert.DeserializeObject(response.Content); var className = userData?.ClassName; From fc1259821704a88c6b000d97f060b04b9568ea36 Mon Sep 17 00:00:00 2001 From: director-mouse <340716031+director-mouse@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:58:44 +0100 Subject: [PATCH 2/6] test(MyAnonaMouse): cover mam_id rotation and persistence Verify that a rotated mam_id is sent on the next account-status request and saved by the refresh service, that missing or blank cookies keep the current value, and that failed refreshes save nothing. --- .../Indexers/MyAnonaMouseWedgeFixture.cs | 121 +++++++++++++++++- 1 file changed, 119 insertions(+), 2 deletions(-) diff --git a/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseWedgeFixture.cs b/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseWedgeFixture.cs index 9f21f6067..7b586340b 100644 --- a/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseWedgeFixture.cs +++ b/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseWedgeFixture.cs @@ -73,12 +73,30 @@ protected override Task> FetchPage(IndexerRequest request, IP private class IndexerFactoryProxy : DispatchProxy { public IIndexer Indexer { get; set; } + public List PersistedMamIds { get; } = new List(); protected override object Invoke(MethodInfo targetMethod, object[] args) { - if (targetMethod?.Name == nameof(IIndexerFactory.GetAvailableProviders)) + switch (targetMethod?.Name) { - return new List { Indexer }; + case nameof(IIndexerFactory.GetAvailableProviders): + return new List { Indexer }; + case nameof(IIndexerFactory.Update): + PersistedMamIds.Add(((MyAnonaMouseSettings)((IndexerDefinition)args[0]).Settings).MamId); + return null; + default: + throw new NotImplementedException(targetMethod?.Name); + } + } + } + + private class SlotGuardProxy : DispatchProxy + { + protected override object Invoke(MethodInfo targetMethod, object[] args) + { + if (targetMethod?.Name == nameof(IMamUnsatisfiedSlotGuard.Reconcile)) + { + return null; } throw new NotImplementedException(targetMethod?.Name); @@ -354,6 +372,88 @@ public async Task account_status_should_accept_an_explicit_zero_count() }); } + [Test] + public async Task account_status_should_send_a_rotated_mam_id_on_the_next_request() + { + var sentMamIds = new List(); + var client = DispatchProxy.Create(); + var clientState = (IndexerHttpClientProxy)(object)client; + clientState.Responses.Enqueue(request => + { + sentMamIds.Add(request.Cookies["mam_id"]); + return ValidSummaryResponse(request, "mam_id=rotated-token; expires=Sat, 24 Oct 2026 03:00:00 GMT; Max-Age=1296000; path=/"); + }); + clientState.Responses.Enqueue(request => + { + sentMamIds.Add(request.Cookies["mam_id"]); + return ValidSummaryResponse(request); + }); + var settings = new MyAnonaMouseSettings { MamId = "original-token" }; + var indexer = CreateIndexer(settings, client); + + await indexer.RefreshAccountStatus(); + await indexer.RefreshAccountStatus(); + + Assert.Multiple(() => + { + Assert.That(sentMamIds, Is.EqualTo(new[] { "original-token", "rotated-token" })); + Assert.That(settings.MamId, Is.EqualTo("rotated-token")); + }); + } + + [Test] + public void account_status_refresh_should_persist_a_rotated_mam_id() + { + var client = CreateClient(request => ValidSummaryResponse(request, "mam_id=rotated-token; path=/")); + var indexer = CreateIndexer(new MyAnonaMouseSettings { MamId = "original-token" }, client); + var factory = DispatchProxy.Create(); + var factoryState = (IndexerFactoryProxy)(object)factory; + factoryState.Indexer = indexer; + + new MyAnonaMouseAccountStatusService(factory, CreateSlotGuard(), LogManager.GetCurrentClassLogger()) + .Execute(new RefreshMyAnonaMouseAccountStatusCommand()); + + Assert.That(factoryState.PersistedMamIds, Is.EqualTo(new[] { "rotated-token" })); + } + + [TestCase(null)] + [TestCase("mam_id=; path=/")] + [TestCase("mam_id= ; path=/")] + [TestCase("mam_ssl=1; path=/")] + public async Task account_status_should_keep_the_current_mam_id_without_a_usable_replacement(string setCookie) + { + var client = CreateClient(request => ValidSummaryResponse(request, setCookie)); + var settings = new MyAnonaMouseSettings { MamId = "original-token" }; + var indexer = CreateIndexer(settings, client); + + await indexer.RefreshAccountStatus(); + + Assert.That(settings.MamId, Is.EqualTo("original-token")); + } + + [TestCase("http-failure")] + [TestCase("invalid-summary")] + public void failed_account_status_refresh_should_not_persist_a_rotated_mam_id(string scenario) + { + var client = CreateClient(request => + { + var response = scenario == "http-failure" + ? new HttpResponse(request, new HttpHeader { ContentType = "application/json" }, "", HttpStatusCode.Forbidden) + : JsonResponse(request, "{\"classname\":\"User\"}"); + response.Headers.Add("Set-Cookie", "mam_id=rotated-token; path=/"); + return response; + }); + var indexer = CreateIndexer(new MyAnonaMouseSettings { MamId = "original-token" }, client); + var factory = DispatchProxy.Create(); + var factoryState = (IndexerFactoryProxy)(object)factory; + factoryState.Indexer = indexer; + + new MyAnonaMouseAccountStatusService(factory, CreateSlotGuard(), LogManager.GetCurrentClassLogger()) + .Execute(new RefreshMyAnonaMouseAccountStatusCommand()); + + Assert.That(factoryState.PersistedMamIds, Is.Empty); + } + [TestCase("malformed")] [TestCase("missing-count")] [TestCase("http-failure")] @@ -550,6 +650,23 @@ private static HttpResponse JsonResponse(HttpRequest request, string content) return new HttpResponse(request, new HttpHeader { ContentType = "application/json" }, content, HttpStatusCode.OK); } + private static HttpResponse ValidSummaryResponse(HttpRequest request, string setCookie = null) + { + var created = DateTimeOffset.UtcNow.AddMinutes(-1).ToUnixTimeSeconds(); + var response = JsonResponse(request, $"{{\"classname\":\"User\",\"created\":{created},\"unsat\":{{\"count\":3,\"limit\":50}}}}"); + if (setCookie != null) + { + response.Headers.Add("Set-Cookie", setCookie); + } + + return response; + } + + private static IMamUnsatisfiedSlotGuard CreateSlotGuard() + { + return DispatchProxy.Create(); + } + private static string EligibleAudiobookUrl() { return "https://www.myanonamouse.net/tor/download.php?tid=42&canUseToken=true&isAudiobook=true"; From fc272f31c2ce9cc2bd7e8404633ae82f15206b2f Mon Sep 17 00:00:00 2001 From: robertlordhood <204023072+robertlordhood@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:34:47 +0000 Subject: [PATCH 3/6] fix(MyAnonaMouse): count unsatisfied slots per MAM user ID Before a grab, take MAM's unsatisfied count from the indexer's last account check and add the grabs made on that user ID since then. Grabs count from 10 minutes before the check, because the summary can trail recent grabs and MAM's clock can run ahead of ours. A retry of the same torrent is not a second grab, but it restarts that torrent's window: the record is written before the .torrent download, so the retry may be the first grab MAM counts. Stale status now pauses retries too. This replaces the reservation bookkeeping (hourly retirement, served confirmations, per-cookie sessions), which stopped matching once each indexer adopts its own renewed mam_id. Grab records are deleted once no usable account check can count them. Store MAM's user ID with the account status, and adopt the renewed mam_id only after the account response validates. Show a System > Status warning naming the indexer when the account check gets a reply Chaptarr can't read, or a 404. It clears on the next readable reply, or when a newer passed check is saved. Send apostrophes in native MAM searches as written. Fixes #379. --- ...AnonaMouseVipAccessSpecificationFixture.cs | 3 - ...ownloadServiceMamUnsatisfiedSlotFixture.cs | 4 - .../MamUnsatisfiedSlotGuardFixture.cs | 455 +++++++++++------- ...tisfiedSlotReservationRepositoryFixture.cs | 42 ++ .../MyAnonaMouseRequestGeneratorFixture.cs | 35 ++ .../Indexers/MyAnonaMouseSeedTimeFixture.cs | 2 +- .../Indexers/MyAnonaMouseWedgeFixture.cs | 281 +++++++---- .../Checks/MyAnonaMouseAccountSummaryCheck.cs | 50 ++ .../MyAnonaMouse/MamUnsatisfiedSlotGuard.cs | 158 +++--- .../MamUnsatisfiedSlotReservation.cs | 1 - ...MamUnsatisfiedSlotReservationRepository.cs | 19 - .../Indexers/MyAnonaMouse/MyAnonaMouse.cs | 79 ++- .../MyAnonaMouseAccountStatusService.cs | 38 +- .../MyAnonaMouseAccountSummaryException.cs | 12 + ...naMouseAccountSummaryHealthChangedEvent.cs | 8 + .../MyAnonaMouseRequestGenerator.cs | 75 +-- .../MyAnonaMouse/MyAnonaMouseSettings.cs | 1 + src/NzbDrone.Core/Localization/Core/en.json | 1 + 18 files changed, 763 insertions(+), 501 deletions(-) create mode 100644 src/Chaptarr.Core.Test/Indexers/MamUnsatisfiedSlotReservationRepositoryFixture.cs create mode 100644 src/NzbDrone.Core/HealthCheck/Checks/MyAnonaMouseAccountSummaryCheck.cs create mode 100644 src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseAccountSummaryException.cs create mode 100644 src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseAccountSummaryHealthChangedEvent.cs diff --git a/src/Chaptarr.Core.Test/DecisionEngine/MyAnonaMouseVipAccessSpecificationFixture.cs b/src/Chaptarr.Core.Test/DecisionEngine/MyAnonaMouseVipAccessSpecificationFixture.cs index 48cdca403..02946c906 100644 --- a/src/Chaptarr.Core.Test/DecisionEngine/MyAnonaMouseVipAccessSpecificationFixture.cs +++ b/src/Chaptarr.Core.Test/DecisionEngine/MyAnonaMouseVipAccessSpecificationFixture.cs @@ -101,9 +101,6 @@ private sealed class RejectingSlotGuard : IMamUnsatisfiedSlotGuard { public MamUnsatisfiedSlotAvailability Check(RemoteBook remoteBook) => MamUnsatisfiedSlotAvailability.Reject("MAM has no safely available unsatisfied slot"); public MamUnsatisfiedSlotAvailability TryReserve(RemoteBook remoteBook) => Check(remoteBook); - public void Reconcile(MyAnonaMouse indexer, MyAnonaMouseAccountStatus status) - { - } } private sealed class StubIndexerFactory : IIndexerFactory diff --git a/src/Chaptarr.Core.Test/Download/DownloadServiceMamUnsatisfiedSlotFixture.cs b/src/Chaptarr.Core.Test/Download/DownloadServiceMamUnsatisfiedSlotFixture.cs index 30295ffb0..524a82a47 100644 --- a/src/Chaptarr.Core.Test/Download/DownloadServiceMamUnsatisfiedSlotFixture.cs +++ b/src/Chaptarr.Core.Test/Download/DownloadServiceMamUnsatisfiedSlotFixture.cs @@ -64,10 +64,6 @@ public MamUnsatisfiedSlotAvailability TryReserve(RemoteBook remoteBook) _calls.Add("reserve"); return Availability; } - - public void Reconcile(MyAnonaMouse indexer, MyAnonaMouseAccountStatus status) - { - } } private sealed class RecordingDownloadClient : IDownloadClient diff --git a/src/Chaptarr.Core.Test/Indexers/MamUnsatisfiedSlotGuardFixture.cs b/src/Chaptarr.Core.Test/Indexers/MamUnsatisfiedSlotGuardFixture.cs index 8f6bc228c..c1a39819d 100644 --- a/src/Chaptarr.Core.Test/Indexers/MamUnsatisfiedSlotGuardFixture.cs +++ b/src/Chaptarr.Core.Test/Indexers/MamUnsatisfiedSlotGuardFixture.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; +using System.Threading.Tasks; using NLog; using NUnit.Framework; using NzbDrone.Core.Indexers; @@ -19,51 +20,66 @@ private class ReservationRepositoryProxy : DispatchProxy public List Rows { get; } = new(); private int _nextId = 1; + // Hand out copies so a change the guard does not save is lost, as with a real database. protected override object Invoke(MethodInfo targetMethod, object[] args) { switch (targetMethod?.Name) { - case nameof(IMamUnsatisfiedSlotReservationRepository.AllForIndexer): - return Rows.Where(r => r.IndexerId == (int)args[0]).ToList(); - - case nameof(IMamUnsatisfiedSlotReservationRepository.Find) when args.Length == 2: - return Rows.SingleOrDefault(r => r.IndexerId == (int)args[0] && r.TorrentId == (string)args[1]); - - case nameof(IMamUnsatisfiedSlotReservationRepository.Insert): - var inserted = (MamUnsatisfiedSlotReservation)args[0]; - inserted.Id = _nextId++; - Rows.Add(inserted); - return inserted; - - case nameof(IMamUnsatisfiedSlotReservationRepository.Update): - return args[0]; - - case nameof(IMamUnsatisfiedSlotReservationRepository.Delete) when args[0] is int id: - Rows.RemoveAll(r => r.Id == id); - return null; - case nameof(IMamUnsatisfiedSlotReservationRepository.All): - return Rows.ToList(); + return Rows.Select(Copy).ToList(); + + case nameof(IMamUnsatisfiedSlotReservationRepository.Upsert): + var saved = (MamUnsatisfiedSlotReservation)args[0]; + if (saved.Id == 0) + { + saved.Id = _nextId++; + Rows.Add(Copy(saved)); + } + else + { + Rows[Rows.FindIndex(r => r.Id == saved.Id)] = Copy(saved); + } + + return saved; + + case nameof(IMamUnsatisfiedSlotReservationRepository.DeleteMany) when args[0] is IEnumerable ids: + var deleted = ids.ToHashSet(); + Rows.RemoveAll(r => deleted.Contains(r.Id)); + return null; default: throw new NotImplementedException(targetMethod?.Name); } } + + public void Add(int indexerId, string torrentId, DateTime reservedUtc) + { + Rows.Add(new MamUnsatisfiedSlotReservation { Id = _nextId++, IndexerId = indexerId, TorrentId = torrentId, ReservedUtc = reservedUtc }); + } + + private static MamUnsatisfiedSlotReservation Copy(MamUnsatisfiedSlotReservation row) + { + return new MamUnsatisfiedSlotReservation { Id = row.Id, IndexerId = row.IndexerId, TorrentId = row.TorrentId, ReservedUtc = row.ReservedUtc }; + } } private class IndexerFactoryProxy : DispatchProxy { public List Definitions { get; } = new(); + public int AllCalls { get; private set; } + public List Finds { get; } = new(); protected override object Invoke(MethodInfo targetMethod, object[] args) { switch (targetMethod?.Name) { case nameof(IIndexerFactory.Find): - case nameof(IIndexerFactory.Get): - return Definitions.SingleOrDefault(d => d.Id == (int)args[0]); + var id = (int)args[0]; + Finds.Add(id); + return Definitions.SingleOrDefault(d => d.Id == id); case nameof(IIndexerFactory.All): + AllCalls++; return Definitions.ToList(); default: @@ -73,106 +89,254 @@ protected override object Invoke(MethodInfo targetMethod, object[] args) } [Test] - public void reservation_should_survive_a_new_guard_instance_and_block_the_next_slot() + public void a_slot_check_only_reads_indexers_for_counted_reservations() + { + var settings = FreshSettings(count: 12, limit: 50, safetyReserve: 5); + settings.UserId = "account"; + var repository = CreateRepository(out var state); + var snapshot = settings.UnsatisfiedSnapshotUtc.Value; + state.Add(9, "100", snapshot); + state.Add(10, "101", snapshot - MamUnsatisfiedSlotGuard.SummaryAccountingLag); + state.Add(11, "102", snapshot); + var factory = CreateFactory(Definition(settings)); + var queries = (IndexerFactoryProxy)(object)factory; + var guard = CreateGuard(factory, repository); + + Assert.That(guard.Check(Release("102")).Accepted, Is.True); + Assert.That(queries.AllCalls, Is.Zero); + Assert.That(queries.Finds, Is.EqualTo(new[] { 9 })); + + state.Add(12, "103", snapshot); + state.Add(12, "104", snapshot); + queries.Finds.Clear(); + + Assert.That(guard.Check(Release("102")).Accepted, Is.True); + Assert.That(queries.AllCalls, Is.Zero); + Assert.That(queries.Finds, Is.EqualTo(new[] { 9, 12 })); + } + + [Test] + public void a_grab_should_count_after_a_restart_and_block_the_next_slot() { var settings = FreshSettings(count: 44, limit: 50, safetyReserve: 5); - var repository = CreateRepository(out var repositoryState); + var repository = CreateRepository(out var state); var factory = CreateFactory(Definition(settings)); - var firstGuard = CreateGuard(factory, repository); - Assert.That(firstGuard.TryReserve(Release("100")).Accepted, Is.True); + Assert.That(CreateGuard(factory, repository).TryReserve(Release("100")).Accepted, Is.True); - var afterRestart = CreateGuard(factory, repository); - var next = afterRestart.Check(Release("101")); + var next = CreateGuard(factory, repository).Check(Release("101")); Assert.Multiple(() => { - Assert.That(repositoryState.Rows.Select(r => r.TorrentId), Is.EqualTo(new[] { "100" })); + Assert.That(state.Rows.Select(r => r.TorrentId), Is.EqualTo(new[] { "100" })); Assert.That(next.Accepted, Is.False); Assert.That(next.Reason, Does.Contain("45 of 50")); }); } [Test] - public void existing_reservation_should_remain_retryable_when_status_becomes_stale() + public void grabs_made_shortly_before_the_last_check_should_still_count() + { + // MAM said 30 at the last check, but 15 grabs made just before it may not be in that count yet. + var settings = FreshSettings(count: 30, limit: 50, safetyReserve: 5); + var repository = CreateRepository(out var state); + for (var torrentId = 1; torrentId <= 15; torrentId++) + { + state.Add(9, torrentId.ToString(), settings.UnsatisfiedSnapshotUtc.Value - MamUnsatisfiedSlotGuard.SummaryAccountingLag + TimeSpan.FromMinutes(1)); + } + + var result = CreateGuard(CreateFactory(Definition(settings)), repository).Check(Release("100")); + + Assert.That(result.Accepted, Is.False); + Assert.That(result.Reason, Does.Contain("45 of 50")); + } + + [TestCase(1, false)] + [TestCase(0, true)] + public void a_grab_should_stop_counting_once_the_last_check_is_a_full_window_newer(int minutesInsideWindow, bool accepted) + { + var settings = FreshSettings(count: 44, limit: 50, safetyReserve: 5); + var repository = CreateRepository(out var state); + state.Add(9, "99", settings.UnsatisfiedSnapshotUtc.Value - MamUnsatisfiedSlotGuard.SummaryAccountingLag + TimeSpan.FromMinutes(minutesInsideWindow)); + + Assert.That(CreateGuard(CreateFactory(Definition(settings)), repository).Check(Release("100")).Accepted, Is.EqualTo(accepted)); + } + + [Test] + public void a_grab_should_count_when_mams_clock_runs_ahead_of_ours() + { + var settings = FreshSettings(count: 44, limit: 50, safetyReserve: 5); + var now = DateTime.UtcNow; + settings.UnsatisfiedSnapshotUtc = now.AddMinutes(4.5); + var repository = CreateRepository(out var state); + state.Add(9, "99", now.AddSeconds(-90)); + + var result = CreateGuard(CreateFactory(Definition(settings)), repository).Check(Release("100")); + + Assert.That(result.Accepted, Is.False); + Assert.That(result.Reason, Does.Contain("45 of 50")); + } + + [Test] + public void stale_status_should_pause_every_grab_including_a_retry() { var settings = FreshSettings(count: 0, limit: 50, safetyReserve: 5); - var repository = CreateRepository(out _); - var factory = CreateFactory(Definition(settings)); - var guard = CreateGuard(factory, repository); + var guard = CreateGuard(CreateFactory(Definition(settings)), CreateRepository(out _)); Assert.That(guard.TryReserve(Release("100")).Accepted, Is.True); settings.UnsatisfiedStatusRefreshedUtc = DateTime.UtcNow.AddHours(-3); + var retry = guard.TryReserve(Release("100")); + + Assert.That(retry.Accepted, Is.False); + Assert.That(retry.Reason, Does.Contain("stale")); + } + + [Test] + public void a_retry_after_a_check_counts_until_the_next_check() + { + var settings = FreshSettings(count: 18, limit: 20, safetyReserve: 0); + var repository = CreateRepository(out var state); + state.Add(9, "100", DateTime.UtcNow.AddMinutes(-30)); + var guard = CreateGuard(CreateFactory(Definition(settings)), repository); + + Assert.That(guard.TryReserve(Release("100")).Accepted, Is.True); + Assert.That(state.Rows.Select(row => row.TorrentId), Is.EqualTo(new[] { "100" })); + Assert.That(guard.TryReserve(Release("101")).Accepted, Is.True); + + var next = guard.TryReserve(Release("102")); + Assert.That(next.Accepted, Is.False); + Assert.That(next.Reason, Does.Contain("20 of 20")); + } + + [Test] + public void a_torrent_grabbed_through_two_indexers_should_count_once() + { + var first = FreshSettings(count: 3, limit: 50, safetyReserve: 45); + var second = FreshSettings(count: 3, limit: 50, safetyReserve: 45); + var repository = CreateRepository(out var state); + var guard = CreateGuard(CreateFactory(Definition(first), Definition(second, 10, "MAM ebooks")), repository); + + Assert.That(guard.TryReserve(Release("99", indexerId: 10)).Accepted, Is.True); + Assert.That(guard.TryReserve(Release("99")).Accepted, Is.True); + Assert.That(state.Rows, Has.Count.EqualTo(2)); + + var next = guard.Check(Release("100")); + + Assert.That(next.Accepted, Is.True); + } + + [Test] + public void indexers_on_one_user_id_should_count_each_others_grabs_from_their_own_last_check() + { + // Audio last checked at 10:00 (30), ebooks at 10:40 (40, which includes 10 audio grabs at 10:10). + var now = DateTime.UtcNow; + var audio = FreshSettings(count: 30, limit: 50, safetyReserve: 9, userId: "42"); + var ebook = FreshSettings(count: 40, limit: 50, safetyReserve: 9, userId: "42"); + audio.UnsatisfiedSnapshotUtc = now.AddMinutes(-45); + ebook.UnsatisfiedSnapshotUtc = now.AddMinutes(-5); + var repository = CreateRepository(out var state); + for (var torrentId = 1; torrentId <= 10; torrentId++) + { + state.Add(9, torrentId.ToString(), now.AddMinutes(-35)); + } + + var guard = CreateGuard(CreateFactory(Definition(audio), Definition(ebook, 10, "MAM ebooks")), repository); + Assert.That(guard.TryReserve(Release("50", indexerId: 10)).Accepted, Is.True); + Assert.Multiple(() => { - Assert.That(guard.Check(Release("100")).Accepted, Is.True); - Assert.That(guard.Check(Release("101")).Accepted, Is.False); + Assert.That(guard.Check(Release("100")).Reason, Does.Contain("41 of 50")); + Assert.That(guard.Check(Release("100", indexerId: 10)).Reason, Does.Contain("41 of 50")); }); } [Test] - public void reservations_should_not_expire_without_a_provider_snapshot() + public async Task indexers_should_keep_sharing_the_count_after_one_renews_its_cookie() { - var settings = FreshSettings(count: 44, limit: 50, safetyReserve: 5); - var repository = CreateRepository(out var repositoryState); - repositoryState.Rows.Add(new MamUnsatisfiedSlotReservation + var audio = FreshSettings(count: 3, limit: 50, safetyReserve: 46); + var ebook = FreshSettings(count: 3, limit: 50, safetyReserve: 46); + await MyAnonaMouseWedgeFixture.CreateIndexerWithAccountSummary(audio).RefreshAccountStatus(); + await MyAnonaMouseWedgeFixture.CreateIndexerWithAccountSummary(ebook, "mam_id=renewed; path=/").RefreshAccountStatus(); + + var guard = CreateGuard(CreateFactory(Definition(audio), Definition(ebook, 10, "MAM ebooks")), CreateRepository(out _)); + Assert.That(guard.TryReserve(Release("99", indexerId: 10)).Accepted, Is.True); + + var next = guard.Check(Release("100")); + + Assert.Multiple(() => { - Id = 1, - IndexerId = 9, - TorrentId = "99", - ReservedUtc = DateTime.UtcNow.AddYears(-1) + Assert.That(ebook.MamId, Is.EqualTo("renewed")); + Assert.That(ebook.UserId, Is.EqualTo("42")); + Assert.That(next.Accepted, Is.False); + Assert.That(next.Reason, Does.Contain("4 of 50")); }); + } - var guard = CreateGuard(CreateFactory(Definition(settings)), repository); + [TestCase("42", null)] + [TestCase(null, "42")] + [TestCase(null, null)] + public void grabs_should_count_when_either_user_id_is_unknown(string userId, string otherUserId) + { + var settings = FreshSettings(count: 44, limit: 50, safetyReserve: 5, userId: userId); + var other = FreshSettings(count: 44, limit: 50, safetyReserve: 5, userId: otherUserId); + var repository = CreateRepository(out var state); + state.Add(10, "99", DateTime.UtcNow); + + var guard = CreateGuard(CreateFactory(Definition(settings), Definition(other, 10, "MAM ebooks")), repository); Assert.That(guard.Check(Release("100")).Accepted, Is.False); } [Test] - public void reservations_from_another_native_indexer_on_the_same_account_should_count_toward_the_limit() + public void grabs_on_a_different_user_id_should_not_count() { - var firstSettings = FreshSettings(count: 44, limit: 50, safetyReserve: 5); - var secondSettings = FreshSettings(count: 44, limit: 50, safetyReserve: 5); - var repository = CreateRepository(out var repositoryState); - repositoryState.Rows.Add(new MamUnsatisfiedSlotReservation - { - Id = 1, - IndexerId = 10, - TorrentId = "99", - ReservedUtc = DateTime.UtcNow - }); + var settings = FreshSettings(count: 44, limit: 50, safetyReserve: 5, userId: "42"); + var other = FreshSettings(count: 44, limit: 50, safetyReserve: 5, userId: "43"); + var repository = CreateRepository(out var state); + state.Add(10, "99", DateTime.UtcNow); + + var guard = CreateGuard(CreateFactory(Definition(settings), Definition(other, 10, "Other MAM account")), repository); + + Assert.That(guard.Check(Release("100")).Accepted, Is.True); + } - var guard = CreateGuard( - CreateFactory(Definition(firstSettings), Definition(secondSettings, 10, "MAM ebooks")), - repository); + [Test] + public void grabs_of_a_removed_indexer_should_count() + { + var settings = FreshSettings(count: 44, limit: 50, safetyReserve: 5, userId: "42"); + var repository = CreateRepository(out var state); + state.Add(10, "99", DateTime.UtcNow); - var result = guard.Check(Release("100")); + var result = CreateGuard(CreateFactory(Definition(settings)), repository).Check(Release("100")); Assert.That(result.Accepted, Is.False); Assert.That(result.Reason, Does.Contain("45 of 50")); } [Test] - public void reservations_from_a_different_mam_account_should_not_count_toward_the_limit() + public void a_grab_should_remove_records_too_old_for_any_usable_check() { - var firstSettings = FreshSettings(count: 44, limit: 50, safetyReserve: 5); - var secondSettings = FreshSettings(count: 44, limit: 50, safetyReserve: 5); - secondSettings.MamId = "different-account-token"; - var repository = CreateRepository(out var repositoryState); - repositoryState.Rows.Add(new MamUnsatisfiedSlotReservation - { - Id = 1, - IndexerId = 10, - TorrentId = "99", - ReservedUtc = DateTime.UtcNow - }); + var settings = FreshSettings(count: 0, limit: 50, safetyReserve: 5); + var repository = CreateRepository(out var state); + var expiredBefore = DateTime.UtcNow.AddHours(-2) - MamUnsatisfiedSlotGuard.SummaryAccountingLag; + state.Add(9, "98", expiredBefore.AddMinutes(-1)); + state.Add(9, "99", expiredBefore.AddMinutes(1)); - var guard = CreateGuard( - CreateFactory(Definition(firstSettings), Definition(secondSettings, 10, "Other MAM account")), - repository); + Assert.That(CreateGuard(CreateFactory(Definition(settings)), repository).TryReserve(Release("100")).Accepted, Is.True); - Assert.That(guard.Check(Release("100")).Accepted, Is.True); + Assert.That(state.Rows.Select(r => r.TorrentId), Is.EquivalentTo(new[] { "99", "100" })); + } + + [Test] + public void a_check_should_not_record_a_grab() + { + var settings = FreshSettings(count: 0, limit: 50, safetyReserve: 5); + var repository = CreateRepository(out var state); + + Assert.That(CreateGuard(CreateFactory(Definition(settings)), repository).Check(Release("100")).Accepted, Is.True); + + Assert.That(state.Rows, Is.Empty); } [Test] @@ -186,13 +350,62 @@ public void generic_torznab_named_mam_should_not_use_the_native_slot_guard() Implementation = "Torznab", Settings = new TorznabSettings() }; - var repository = CreateRepository(out var repositoryState); + var repository = CreateRepository(out var state); var guard = CreateGuard(CreateFactory(definition), repository); - var result = guard.Check(Release("100", ReleaseSourceType.Search, 12, definition.Name)); + var result = guard.TryReserve(Release("100", ReleaseSourceType.Search, 12, definition.Name)); Assert.That(result.Accepted, Is.True); - Assert.That(repositoryState.Rows, Is.Empty); + Assert.That(state.Rows, Is.Empty); + } + + [TestCase("no count")] + [TestCase("no limit")] + [TestCase("no snapshot")] + [TestCase("snapshot from the future")] + public void unusable_status_should_pause_grabs(string problem) + { + var settings = FreshSettings(count: 0, limit: 50, safetyReserve: 5); + switch (problem) + { + case "no count": + settings.UnsatisfiedCount = null; + break; + case "no limit": + settings.UnsatisfiedLimit = 0; + break; + case "no snapshot": + settings.UnsatisfiedSnapshotUtc = null; + break; + default: + settings.UnsatisfiedSnapshotUtc = DateTime.UtcNow.AddMinutes(10); + break; + } + + var result = CreateGuard(CreateFactory(Definition(settings)), CreateRepository(out _)).Check(Release("100")); + + Assert.That(result.Reason, Does.Contain("unavailable or stale")); + } + + [TestCase("MAM-abc")] + [TestCase("MAM-0")] + [TestCase("12345")] + public void a_release_without_a_mam_torrent_id_should_pause(string guid) + { + var release = Release("100"); + release.Release.Guid = guid; + + var result = CreateGuard(CreateFactory(Definition(FreshSettings(count: 0, limit: 50, safetyReserve: 5))), CreateRepository(out _)).Check(release); + + Assert.That(result.Reason, Does.Contain("no valid MAM torrent identity")); + } + + [Test] + public void a_book_without_a_release_should_not_use_the_slot_guard() + { + var guard = CreateGuard(CreateFactory(), CreateRepository(out _)); + + Assert.That(guard.Check(new RemoteBook()).Accepted, Is.True); } [Test] @@ -224,8 +437,7 @@ public void non_interactive_grabs_should_stop_at_the_safety_reserve_plus_user_bu public void interactive_grab_should_use_the_user_buffer_but_never_use_the_safety_reserve() { var settings = FreshSettings(count: 40, limit: 50, safetyReserve: 5, manualGrabBuffer: 5); - var repository = CreateRepository(out _); - var guard = CreateGuard(CreateFactory(Definition(settings)), repository); + var guard = CreateGuard(CreateFactory(Definition(settings)), CreateRepository(out _)); Assert.Multiple(() => { @@ -238,84 +450,13 @@ public void interactive_grab_should_use_the_user_buffer_but_never_use_the_safety Assert.That(guard.Check(Release("102", ReleaseSourceType.InteractiveSearch)).Accepted, Is.False); } - [Test] - public void retry_should_refresh_an_unconfirmed_reservations_accounting_window() - { - var settings = FreshSettings(count: 0, limit: 50, safetyReserve: 5); - var repository = CreateRepository(out var repositoryState); - repositoryState.Rows.Add(new MamUnsatisfiedSlotReservation - { - Id = 1, - IndexerId = 9, - TorrentId = "100", - ReservedUtc = DateTime.UtcNow.AddHours(-1) - }); - - var previousAttempt = repositoryState.Rows.Single().ReservedUtc; - var guard = CreateGuard(CreateFactory(Definition(settings)), repository); - - Assert.That(guard.TryReserve(Release("100")).Accepted, Is.True); - Assert.That(repositoryState.Rows.Single().ReservedUtc, Is.GreaterThan(previousAttempt)); - Assert.That(repositoryState.Rows.Single().ConfirmedUtc, Is.Null); - } - - [Test] - public void provider_snapshot_should_retire_reservations_from_another_indexer_on_the_same_account() - { - var firstSettings = FreshSettings(count: 1, limit: 50, safetyReserve: 5); - var secondSettings = FreshSettings(count: 1, limit: 50, safetyReserve: 5); - var repository = CreateRepository(out var repositoryState); - var anchor = DateTime.UtcNow.AddMinutes(-30); - repositoryState.Rows.Add(new MamUnsatisfiedSlotReservation - { - Id = 1, - IndexerId = 10, - TorrentId = "659145", - ReservedUtc = anchor - }); - - var indexer = CreateMamIndexer(firstSettings, repository); - var guard = CreateGuard( - CreateFactory((IndexerDefinition)indexer.Definition, Definition(secondSettings, 10, "MAM ebooks")), - repository); - - guard.Reconcile(indexer, new MyAnonaMouseAccountStatus { SnapshotCreatedUtc = anchor.AddMinutes(20) }); - - Assert.That(repositoryState.Rows, Is.Empty); - } - - [TestCase(false)] - [TestCase(true)] - public void reservation_should_retire_only_after_the_provider_snapshot_covers_the_accounting_lag(bool confirmed) - { - var settings = FreshSettings(count: 1, limit: 50, safetyReserve: 5); - var repository = CreateRepository(out var repositoryState); - var anchor = DateTime.UtcNow.AddMinutes(-30); - repositoryState.Rows.Add(new MamUnsatisfiedSlotReservation - { - Id = 1, - IndexerId = 9, - TorrentId = "659145", - ReservedUtc = confirmed ? anchor.AddMinutes(-30) : anchor, - ConfirmedUtc = confirmed ? anchor : null - }); - - var indexer = CreateMamIndexer(settings, repository); - var guard = CreateGuard(CreateFactory((IndexerDefinition)indexer.Definition), repository); - - guard.Reconcile(indexer, new MyAnonaMouseAccountStatus { SnapshotCreatedUtc = anchor.AddMinutes(19) }); - Assert.That(repositoryState.Rows, Has.Count.EqualTo(1)); - - guard.Reconcile(indexer, new MyAnonaMouseAccountStatus { SnapshotCreatedUtc = anchor.AddMinutes(20) }); - Assert.That(repositoryState.Rows, Is.Empty); - } - - private static MyAnonaMouseSettings FreshSettings(int count, int limit, int safetyReserve, int manualGrabBuffer = 0) + private static MyAnonaMouseSettings FreshSettings(int count, int limit, int safetyReserve, int manualGrabBuffer = 0, string userId = null) { return new MyAnonaMouseSettings { ProtectUnsatisfiedSlots = true, MamId = "shared-account-token", + UserId = userId, UnsatisfiedSlotReserve = safetyReserve, ManualGrabBuffer = manualGrabBuffer, UnsatisfiedCount = count, @@ -370,13 +511,5 @@ private static MamUnsatisfiedSlotGuard CreateGuard(IIndexerFactory factory, IMam { return new MamUnsatisfiedSlotGuard(factory, repository, LogManager.GetCurrentClassLogger()); } - - private static MyAnonaMouse CreateMamIndexer(MyAnonaMouseSettings settings, IMamUnsatisfiedSlotReservationRepository repository) - { - return new MyAnonaMouse(null, null, null, null, repository, LogManager.GetCurrentClassLogger()) - { - Definition = Definition(settings) - }; - } } } diff --git a/src/Chaptarr.Core.Test/Indexers/MamUnsatisfiedSlotReservationRepositoryFixture.cs b/src/Chaptarr.Core.Test/Indexers/MamUnsatisfiedSlotReservationRepositoryFixture.cs new file mode 100644 index 000000000..8bf62fc64 --- /dev/null +++ b/src/Chaptarr.Core.Test/Indexers/MamUnsatisfiedSlotReservationRepositoryFixture.cs @@ -0,0 +1,42 @@ +using System; +using System.Linq; +using Chaptarr.Core.Test.Common; +using NUnit.Framework; +using NzbDrone.Core.Datastore.Migration.Framework; +using NzbDrone.Core.Indexers.MyAnonaMouse; +using NzbDrone.Core.Messaging.Events; + +namespace Chaptarr.Core.Test.Indexers +{ + [TestFixture] + public class MamUnsatisfiedSlotReservationRepositoryFixture + { + // The shipped table still has the unused ConfirmedUtc column. + [TestCase(false)] + [TestCase(true)] + public void reservations_should_upsert_read_and_delete_on_the_shipped_table(bool postgres) + { + DualDatabaseFixture.Run(postgres, database => + { + var repository = new MamUnsatisfiedSlotReservationRepository(database, InterfaceProxy.Proxy((_, _) => null)); + var reservedUtc = new DateTime(2026, 11, 21, 10, 0, 0, DateTimeKind.Utc); + var kept = repository.Upsert(new MamUnsatisfiedSlotReservation { IndexerId = 9, TorrentId = "100", ReservedUtc = reservedUtc }); + var expired = repository.Upsert(new MamUnsatisfiedSlotReservation { IndexerId = 10, TorrentId = "101", ReservedUtc = reservedUtc.AddHours(-3) }); + + kept.ReservedUtc = reservedUtc.AddMinutes(5); + repository.Upsert(kept); + repository.DeleteMany(new[] { expired.Id }); + + var row = repository.All().Single(); + + Assert.Multiple(() => + { + Assert.That(row.Id, Is.EqualTo(kept.Id)); + Assert.That(row.IndexerId, Is.EqualTo(9)); + Assert.That(row.TorrentId, Is.EqualTo("100")); + Assert.That(row.ReservedUtc, Is.EqualTo(reservedUtc.AddMinutes(5))); + }); + }, MigrationType.Main, desiredVersion: 100); + } + } +} diff --git a/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseRequestGeneratorFixture.cs b/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseRequestGeneratorFixture.cs index 6a4176a1f..75cdc68db 100644 --- a/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseRequestGeneratorFixture.cs +++ b/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseRequestGeneratorFixture.cs @@ -56,6 +56,41 @@ public void should_use_title_only_as_fallback_tier_when_primary_query_includes_a Assert.That(GetRequestPayload(chain, 1), Does.Contain("\"text\":\"Godblight\"")); } + [TestCase("'")] + [TestCase("’")] + public void should_preserve_apostrophes_in_search_terms(string apostrophe) + { + var criteria = CreateAudiobookCriteria("en"); + criteria.BookTitle = $"It{apostrophe}s Beginning to Look a Lot Like Murder"; + criteria.Author.Name = $"Morgan D{apostrophe}Arcy"; + criteria.Books[0].AnyEditionOk = false; + criteria.Books[0].Editions = new List + { + new Edition { ReadingFormatId = 2, Monitored = true, Narrator = $"Casey O{apostrophe}Connor" } + }; + + var chain = CreateGenerator().GetSearchRequests(criteria); + var titleAndAuthor = $"{criteria.BookTitle} {criteria.Author.Name}"; + + Assert.That(chain.Tiers, Is.EqualTo(3)); + Assert.That(GetRequestPayloadObject(chain, 0)["tor"]?["text"]?.Value(), + Is.EqualTo($"{titleAndAuthor} Casey O{apostrophe}Connor")); + Assert.That(GetRequestPayloadObject(chain, 1)["tor"]?["text"]?.Value(), Is.EqualTo(titleAndAuthor)); + Assert.That(GetRequestPayloadObject(chain, 2)["tor"]?["text"]?.Value(), Is.EqualTo(criteria.BookTitle)); + } + + [Test] + public void should_normalize_spacing_when_the_shared_search_keeps_a_punctuation_only_title() + { + var criteria = CreateAudiobookCriteria("en"); + criteria.BookTitle = "?! …"; + + var chain = CreateGenerator().GetSearchRequests(criteria); + + Assert.That(GetRequestPayloadObject(chain, 0)["tor"]?["text"]?.Value(), Is.EqualTo("?! … Author")); + Assert.That(GetRequestPayloadObject(chain, 1)["tor"]?["text"]?.Value(), Is.EqualTo("?! …")); + } + [Test] public void should_add_book_number_fallback_as_last_tier_for_interactive_search() { diff --git a/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseSeedTimeFixture.cs b/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseSeedTimeFixture.cs index e7d057301..d8c18eae2 100644 --- a/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseSeedTimeFixture.cs +++ b/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseSeedTimeFixture.cs @@ -31,7 +31,7 @@ public void should_allow_seed_time_to_be_cleared_and_persist_as_null() public void default_definition_should_set_seed_time_hours_to_72() { var logger = LogManager.GetCurrentClassLogger(); - var indexer = new MyAnonaMouse(null, null, null, null, null, logger); + var indexer = new MyAnonaMouse(null, null, null, null, logger); var definition = (IndexerDefinition)indexer.DefaultDefinitions.Single(); var settings = (MyAnonaMouseSettings)definition.Settings; diff --git a/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseWedgeFixture.cs b/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseWedgeFixture.cs index 7b586340b..738fc848e 100644 --- a/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseWedgeFixture.cs +++ b/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseWedgeFixture.cs @@ -11,12 +11,21 @@ using NLog.Config; using NLog.Targets; using NUnit.Framework; +using NzbDrone.Common.Cache; +using NzbDrone.Common.EnvironmentInfo; using NzbDrone.Common.Http; +using NzbDrone.Core.Configuration; +using NzbDrone.Core.HealthCheck; +using NzbDrone.Core.HealthCheck.Checks; using NzbDrone.Core.Indexers; using NzbDrone.Core.Indexers.MyAnonaMouse; +using NzbDrone.Core.Localization; +using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Parser; using NzbDrone.Core.Parser.Model; using NzbDrone.Core.ThingiProvider; +using NzbDrone.Core.ThingiProvider.Events; +using static Chaptarr.Core.Test.Common.InterfaceProxy; namespace Chaptarr.Core.Test.Indexers { @@ -60,7 +69,7 @@ protected override object Invoke(MethodInfo targetMethod, object[] args) private sealed class TestableMyAnonaMouse : MyAnonaMouse { public TestableMyAnonaMouse(IIndexerHttpClientFactory httpClientFactory, Logger logger) - : base(httpClientFactory, null, null, null, null, logger) + : base(httpClientFactory, null, null, null, logger) { } @@ -81,6 +90,8 @@ protected override object Invoke(MethodInfo targetMethod, object[] args) { case nameof(IIndexerFactory.GetAvailableProviders): return new List { Indexer }; + case nameof(IIndexerFactory.All): + return new List { (IndexerDefinition)Indexer.Definition }; case nameof(IIndexerFactory.Update): PersistedMamIds.Add(((MyAnonaMouseSettings)((IndexerDefinition)args[0]).Settings).MamId); return null; @@ -90,39 +101,6 @@ protected override object Invoke(MethodInfo targetMethod, object[] args) } } - private class SlotGuardProxy : DispatchProxy - { - protected override object Invoke(MethodInfo targetMethod, object[] args) - { - if (targetMethod?.Name == nameof(IMamUnsatisfiedSlotGuard.Reconcile)) - { - return null; - } - - throw new NotImplementedException(targetMethod?.Name); - } - } - - private class ReservationRepositoryProxy : DispatchProxy - { - public List Rows { get; } = new List(); - public int UpdateCount { get; private set; } - - protected override object Invoke(MethodInfo targetMethod, object[] args) - { - switch (targetMethod?.Name) - { - case nameof(IMamUnsatisfiedSlotReservationRepository.Find): - return Rows.SingleOrDefault(row => row.IndexerId == (int)args[0] && row.TorrentId == (string)args[1]); - case nameof(IMamUnsatisfiedSlotReservationRepository.Update): - UpdateCount++; - return args[0]; - default: - throw new NotImplementedException(targetMethod?.Name); - } - } - } - [Test] public void follow_mam_preferences_should_strip_internal_markers_without_forcing_wedge() { @@ -217,18 +195,11 @@ public async Task preferred_wedge_should_retry_without_fl_when_mam_does_not_retu Encoding.ASCII.GetBytes(MinimalTorrent), HttpStatusCode.OK)); - var repository = DispatchProxy.Create(); - var repositoryState = (ReservationRepositoryProxy)(object)repository; - repositoryState.Rows.Add(new MamUnsatisfiedSlotReservation - { - Id = 1, IndexerId = 9, TorrentId = "42", ReservedUtc = DateTime.UtcNow - }); - var indexer = CreateIndexer(new MyAnonaMouseSettings { UseFreeleechWedge = (int)MyAnonaMouseFreeleechWedgeAction.Preferred, UseFreeleechOnlyForAudiobooks = true - }, client, repository); + }, client); var request = indexer.GetDownloadRequest(EligibleAudiobookUrl()); var response = await indexer.ExecuteDownloadRequestAsync(request); @@ -237,34 +208,6 @@ public async Task preferred_wedge_should_retry_without_fl_when_mam_does_not_retu Assert.That(clientState.Requests, Has.Count.EqualTo(2)); Assert.That(clientState.Requests[0], Does.Contain("fl")); Assert.That(clientState.Requests[1], Does.Not.Contain("fl")); - Assert.That(repositoryState.Rows.Single().ConfirmedUtc, Is.Not.Null); - Assert.That(repositoryState.UpdateCount, Is.EqualTo(1)); - } - - [Test] - public async Task html_response_should_not_confirm_that_mam_served_a_torrent() - { - var client = DispatchProxy.Create(); - var clientState = (IndexerHttpClientProxy)(object)client; - clientState.Responses.Enqueue(request => new HttpResponse( - request, - new HttpHeader { ContentType = "text/html" }, - "Not signed in", - HttpStatusCode.OK)); - - var repository = DispatchProxy.Create(); - var repositoryState = (ReservationRepositoryProxy)(object)repository; - repositoryState.Rows.Add(new MamUnsatisfiedSlotReservation - { - Id = 1, IndexerId = 9, TorrentId = "42", ReservedUtc = DateTime.UtcNow - }); - - var indexer = CreateIndexer(new MyAnonaMouseSettings(), client, repository); - - await indexer.ExecuteDownloadRequestAsync(indexer.GetDownloadRequest(EligibleAudiobookUrl())); - - Assert.That(repositoryState.Rows.Single().ConfirmedUtc, Is.Null); - Assert.That(repositoryState.UpdateCount, Is.Zero); } [Test] @@ -298,8 +241,8 @@ public async Task account_status_should_use_mam_unsatisfied_count_limit_and_snap request, new HttpHeader { ContentType = "application/json" }, nested - ? "{\"classname\":\"Elite VIP\",\"snatch_summary\":{\"created\":1785171600,\"unsat\":{\"count\":196,\"limit\":200}}}" - : "{\"classname\":\"Elite VIP\",\"created\":1785171600,\"unsat\":{\"count\":196,\"limit\":200}}", + ? "{\"uid\":42,\"classname\":\"Elite VIP\",\"snatch_summary\":{\"created\":1785171600,\"unsat\":{\"count\":196,\"limit\":200}}}" + : "{\"uid\":42,\"classname\":\"Elite VIP\",\"created\":1785171600,\"unsat\":{\"count\":196,\"limit\":200}}", HttpStatusCode.OK)); var settings = new MyAnonaMouseSettings { MamId = "secret" }; @@ -321,8 +264,8 @@ public async Task account_status_should_use_mam_unsatisfied_count_limit_and_snap }); } - [TestCase("{\"classname\":\"User\",\"created\":1785171600,\"unsat\":{\"limit\":200}}")] - [TestCase("{\"classname\":\"User\",\"created\":1785171600,\"unsat\":{\"count\":null,\"limit\":200}}")] + [TestCase("{\"uid\":42,\"classname\":\"User\",\"created\":1785171600,\"unsat\":{\"limit\":200}}")] + [TestCase("{\"uid\":42,\"classname\":\"User\",\"created\":1785171600,\"unsat\":{\"count\":null,\"limit\":200}}")] public void account_status_should_reject_missing_or_null_count_without_overwriting_cached_settings(string content) { var client = CreateClient(request => JsonResponse(request, content)); @@ -340,7 +283,7 @@ public void account_status_should_reject_missing_or_null_count_without_overwriti var priorRefresh = settings.UnsatisfiedStatusRefreshedUtc; var indexer = CreateIndexer(settings, client); - Assert.ThrowsAsync(async () => await indexer.RefreshAccountStatus()); + Assert.ThrowsAsync(async () => await indexer.RefreshAccountStatus()); Assert.Multiple(() => { @@ -358,7 +301,7 @@ public async Task account_status_should_accept_an_explicit_zero_count() { var created = DateTimeOffset.UtcNow.AddMinutes(-1).ToUnixTimeSeconds(); var client = CreateClient(request => JsonResponse(request, - $"{{\"classname\":\"User\",\"created\":{created},\"unsat\":{{\"count\":0,\"limit\":50}}}}")); + $"{{\"uid\":42,\"classname\":\"User\",\"created\":{created},\"unsat\":{{\"count\":0,\"limit\":50}}}}")); var settings = new MyAnonaMouseSettings { MamId = "fixture-token" }; var indexer = CreateIndexer(settings, client); @@ -372,6 +315,34 @@ public async Task account_status_should_accept_an_explicit_zero_count() }); } + [TestCase("42")] + [TestCase("\"42\"")] + public async Task account_status_should_store_the_user_id_whether_mam_sends_text_or_a_number(string uid) + { + var created = DateTimeOffset.UtcNow.AddMinutes(-1).ToUnixTimeSeconds(); + var settings = new MyAnonaMouseSettings { MamId = "fixture-token" }; + var indexer = CreateIndexer(settings, CreateClient(request => JsonResponse(request, $"{{\"uid\":{uid},\"classname\":\"User\",\"created\":{created},\"unsat\":{{\"count\":3,\"limit\":50}}}}"))); + + await indexer.RefreshAccountStatus(); + + Assert.That(settings.UserId, Is.EqualTo("42")); + } + + [Test] + public async Task account_status_without_a_user_id_should_refresh_and_leave_the_account_unidentified() + { + var settings = new MyAnonaMouseSettings { MamId = "fixture-token", UserId = "42" }; + var indexer = CreateIndexer(settings, CreateSummaryClient("missing-uid")); + + await indexer.RefreshAccountStatus(); + + Assert.Multiple(() => + { + Assert.That(settings.UnsatisfiedCount, Is.EqualTo(3)); + Assert.That(settings.UserId, Is.Null); + }); + } + [Test] public async Task account_status_should_send_a_rotated_mam_id_on_the_next_request() { @@ -404,13 +375,12 @@ public async Task account_status_should_send_a_rotated_mam_id_on_the_next_reques [Test] public void account_status_refresh_should_persist_a_rotated_mam_id() { - var client = CreateClient(request => ValidSummaryResponse(request, "mam_id=rotated-token; path=/")); - var indexer = CreateIndexer(new MyAnonaMouseSettings { MamId = "original-token" }, client); + var indexer = CreateIndexerWithAccountSummary(new MyAnonaMouseSettings { MamId = "original-token" }, "mam_id=rotated-token; path=/"); var factory = DispatchProxy.Create(); var factoryState = (IndexerFactoryProxy)(object)factory; factoryState.Indexer = indexer; - new MyAnonaMouseAccountStatusService(factory, CreateSlotGuard(), LogManager.GetCurrentClassLogger()) + new MyAnonaMouseAccountStatusService(factory, Proxy((_, _) => null), LogManager.GetCurrentClassLogger()) .Execute(new RefreshMyAnonaMouseAccountStatusCommand()); Assert.That(factoryState.PersistedMamIds, Is.EqualTo(new[] { "rotated-token" })); @@ -439,7 +409,7 @@ public void failed_account_status_refresh_should_not_persist_a_rotated_mam_id(st { var response = scenario == "http-failure" ? new HttpResponse(request, new HttpHeader { ContentType = "application/json" }, "", HttpStatusCode.Forbidden) - : JsonResponse(request, "{\"classname\":\"User\"}"); + : JsonResponse(request, "{\"uid\":42,\"classname\":\"User\"}"); response.Headers.Add("Set-Cookie", "mam_id=rotated-token; path=/"); return response; }); @@ -448,10 +418,11 @@ public void failed_account_status_refresh_should_not_persist_a_rotated_mam_id(st var factoryState = (IndexerFactoryProxy)(object)factory; factoryState.Indexer = indexer; - new MyAnonaMouseAccountStatusService(factory, CreateSlotGuard(), LogManager.GetCurrentClassLogger()) + new MyAnonaMouseAccountStatusService(factory, Proxy((_, _) => null), LogManager.GetCurrentClassLogger()) .Execute(new RefreshMyAnonaMouseAccountStatusCommand()); Assert.That(factoryState.PersistedMamIds, Is.Empty); + Assert.That(((MyAnonaMouseSettings)indexer.Definition.Settings).MamId, Is.EqualTo("original-token")); } [TestCase("malformed")] @@ -542,7 +513,7 @@ public void account_status_warning_should_identify_indexer_without_exposing_resp using var logs = new LogFactory { Configuration = configuration }; var logger = logs.GetLogger("AccountStatusDiagnostic"); var client = CreateClient(request => JsonResponse(request, - $"{{\"classname\":\"User\",\"created\":1785171600,\"unsat\":{{\"count\":\"{privateValue}\",\"limit\":200}}}}")); + $"{{\"uid\":42,\"classname\":\"User\",\"created\":1785171600,\"unsat\":{{\"count\":\"{privateValue}\",\"limit\":200}}}}")); var indexer = CreateTestIndexer(new MyAnonaMouseSettings { MamId = "fixture-token" }, client, logger); indexer.Definition.Name = "Fixture MAM"; @@ -550,7 +521,8 @@ public void account_status_warning_should_identify_indexer_without_exposing_resp { var factory = DispatchProxy.Create(); ((IndexerFactoryProxy)(object)factory).Indexer = indexer; - new MyAnonaMouseAccountStatusService(factory, null, logger).Execute(new RefreshMyAnonaMouseAccountStatusCommand()); + new MyAnonaMouseAccountStatusService(factory, Proxy((_, _) => null), logger) + .Execute(new RefreshMyAnonaMouseAccountStatusCommand()); } else { @@ -562,12 +534,132 @@ public void account_status_warning_should_identify_indexer_without_exposing_resp { Assert.That(messages.Logs[0], Does.StartWith("Warn|")); Assert.That(messages.Logs[0], Does.Contain("Fixture MAM")); - Assert.That(messages.Logs[0], Does.Contain(nameof(JsonReaderException))); + Assert.That(messages.Logs[0], Does.Contain(background ? "could not be decoded" : nameof(MyAnonaMouseAccountSummaryException))); Assert.That(messages.Logs[0], Does.Not.Contain(privateValue)); Assert.That(messages.Logs[0], Does.Not.Contain("fixture-token")); }); } + [TestCase("unreadable-private-content")] + [TestCase("{\"uid\":42,\"created\":1785171600,\"unsat\":{\"count\":1,\"limit\":50}}")] + [TestCase("{\"classname\":\"User\",\"created\":1785171600}")] + [TestCase("{\"classname\":\"User\",\"created\":9223372036854775807,\"unsat\":{\"count\":1,\"limit\":50}}")] + [TestCase(null)] + public void account_summary_health_warning_follows_refresh_results(string unreadableReply) + { + const string privateResponse = "fixture-private-response"; + HttpResponse UnreadableResponse(HttpRequest request) + { + var statusCode = unreadableReply == null ? HttpStatusCode.NotFound : HttpStatusCode.OK; + Assert.That(request.SuppressHttpErrorStatusCodes, Is.EqualTo(new[] { HttpStatusCode.NotFound })); + var response = new HttpResponse(request, new HttpHeader(), unreadableReply ?? privateResponse, statusCode); + response.Headers.Add("Set-Cookie", "mam_id=unverified-token; path=/"); + return response; + } + + var client = CreateClient(request => new HttpResponse(request, new HttpHeader(), "", HttpStatusCode.Forbidden)); + var clientState = (IndexerHttpClientProxy)(object)client; + clientState.Responses.Enqueue(UnreadableResponse); + clientState.Responses.Enqueue(UnreadableResponse); + clientState.Responses.Enqueue(_ => throw new TimeoutException()); + clientState.Responses.Enqueue(request => ValidSummaryResponse(request, "mam_id=rotated-token; path=/")); + + var indexer = CreateIndexer(new MyAnonaMouseSettings { MamId = "fixture-token" }, client); + var definition = (IndexerDefinition)indexer.Definition; + definition.Name = "Fixture MAM"; + definition.EnableAutomaticSearch = true; + var factory = DispatchProxy.Create(); + var factoryState = (IndexerFactoryProxy)(object)factory; + factoryState.Indexer = indexer; + var logger = LogManager.GetCurrentClassLogger(); + + HealthCheckService health = null; + MyAnonaMouseAccountStatusService refresh = null; + var summaryHealthChanges = 0; + var events = Proxy((_, args) => + { + switch (args[0]) + { + case MyAnonaMouseAccountSummaryHealthChangedEvent changed: + summaryHealthChanges++; + health.HandleAsync(changed); + break; + case HealthCheckCompleteEvent complete: + refresh.Handle(complete); + break; + case ProviderUpdatedEvent updated: + health.HandleAsync(updated); + break; + } + + return null; + }); + + refresh = new MyAnonaMouseAccountStatusService(factory, events, logger); + var cache = new CacheManager(); + var localization = new LocalizationService( + Proxy((_, _) => (int)NzbDrone.Core.Languages.Language.English), + Proxy((_, _) => TestContext.CurrentContext.TestDirectory), cache, logger); + var check = new MyAnonaMouseAccountSummaryCheck(factory, refresh, localization); + health = new HealthCheckService(new[] { check }, null, null, events, cache, + Proxy((_, _) => DateTime.UtcNow), logger); + var lastAttempt = typeof(MyAnonaMouseAccountStatusService).GetField("_lastRefreshAttemptUtc", BindingFlags.Instance | BindingFlags.NonPublic); + + void Refresh() + { + lastAttempt.SetValue(refresh, DateTime.MinValue); + refresh.Execute(new RefreshMyAnonaMouseAccountStatusCommand()); + } + + Refresh(); + Assert.That(health.Results(), Is.Empty, "An HTTP 403 is not an unreadable account summary."); + + Refresh(); + var warning = health.Results().Single(); + Assert.Multiple(() => + { + Assert.That(warning.Type, Is.EqualTo(HealthCheckResult.Warning)); + Assert.That(warning.Message, Does.Contain("Fixture MAM").And.Contain("Please report this")); + Assert.That(warning.Message, Does.Not.Contain("fixture-token").And.Not.Contain(unreadableReply ?? privateResponse)); + Assert.That(summaryHealthChanges, Is.EqualTo(1)); + Assert.That(clientState.Requests, Has.Count.EqualTo(2)); + Assert.That(factoryState.PersistedMamIds, Is.Empty); + Assert.That(((MyAnonaMouseSettings)definition.Settings).MamId, Is.EqualTo("fixture-token")); + }); + + definition.EnableAutomaticSearch = false; + events.PublishEvent(new ProviderUpdatedEvent(definition)); + Assert.That(health.Results(), Is.Empty); + definition.EnableAutomaticSearch = true; + events.PublishEvent(new ProviderUpdatedEvent(definition)); + Assert.That(health.Results().Single().Message, Is.EqualTo(warning.Message)); + Assert.That(clientState.Requests, Has.Count.EqualTo(2)); + + var testedSettings = new MyAnonaMouseSettings { MamId = "fixture-token" }; + var testedIndexer = CreateTestIndexer(testedSettings, CreateSummaryClient("fresh")); + Assert.That(testedIndexer.Test().IsValid, Is.True); + Assert.That(health.Results().Single().Message, Is.EqualTo(warning.Message)); + + definition.Settings = testedSettings; + events.PublishEvent(new ProviderUpdatedEvent(definition)); + Assert.That(health.Results(), Is.Empty); + + Refresh(); + Assert.That(health.Results().Single().Message, Is.EqualTo(warning.Message)); + Refresh(); + Assert.That(summaryHealthChanges, Is.EqualTo(2), "The new unreadable reply raises the warning again, and the timeout leaves it in place."); + Assert.That(health.Results().Single().Message, Is.EqualTo(warning.Message)); + + Refresh(); + Assert.Multiple(() => + { + Assert.That(health.Results(), Is.Empty); + Assert.That(summaryHealthChanges, Is.EqualTo(3)); + Assert.That(clientState.Requests, Has.Count.EqualTo(5)); + Assert.That(factoryState.PersistedMamIds, Is.EqualTo(new[] { "rotated-token" })); + }); + } + [Test] public void unsatisfied_slot_protection_should_default_on_for_legacy_settings_json() { @@ -589,12 +681,17 @@ public void unsatisfied_slot_protection_should_preserve_an_explicit_advanced_opt Assert.That(settings.ProtectUnsatisfiedSlots, Is.False); } - private static MyAnonaMouse CreateIndexer(MyAnonaMouseSettings settings, IIndexerHttpClient client = null, IMamUnsatisfiedSlotReservationRepository repository = null) + internal static MyAnonaMouse CreateIndexerWithAccountSummary(MyAnonaMouseSettings settings, string setCookie = null) + { + return CreateIndexer(settings, CreateClient(request => ValidSummaryResponse(request, setCookie))); + } + + private static MyAnonaMouse CreateIndexer(MyAnonaMouseSettings settings, IIndexerHttpClient client = null) { var factory = DispatchProxy.Create(); ((IndexerHttpClientFactoryProxy)(object)factory).Client = client; - return new MyAnonaMouse(factory, null, null, null, repository, LogManager.GetCurrentClassLogger()) + return new MyAnonaMouse(factory, null, null, null, LogManager.GetCurrentClassLogger()) { Definition = new IndexerDefinition { @@ -631,9 +728,10 @@ private static IIndexerHttpClient CreateSummaryClient(string scenario) ((IndexerHttpClientProxy)(object)client).Responses.Enqueue(request => scenario switch { "malformed" => JsonResponse(request, "not-json"), - "missing-count" => JsonResponse(request, $"{{\"classname\":\"User\",\"created\":{created},\"unsat\":{{\"limit\":50}}}}"), + "missing-uid" => JsonResponse(request, $"{{\"classname\":\"User\",\"created\":{created},\"unsat\":{{\"count\":3,\"limit\":50}}}}"), + "missing-count" => JsonResponse(request, $"{{\"uid\":42,\"classname\":\"User\",\"created\":{created},\"unsat\":{{\"limit\":50}}}}"), "http-failure" => new HttpResponse(request, new HttpHeader { ContentType = "application/json" }, "", HttpStatusCode.ServiceUnavailable), - _ => JsonResponse(request, $"{{\"classname\":\"User\",\"created\":{created},\"unsat\":{{\"count\":3,\"limit\":50}}}}") + _ => JsonResponse(request, $"{{\"uid\":42,\"classname\":\"User\",\"created\":{created},\"unsat\":{{\"count\":3,\"limit\":50}}}}") }); return client; } @@ -653,7 +751,7 @@ private static HttpResponse JsonResponse(HttpRequest request, string content) private static HttpResponse ValidSummaryResponse(HttpRequest request, string setCookie = null) { var created = DateTimeOffset.UtcNow.AddMinutes(-1).ToUnixTimeSeconds(); - var response = JsonResponse(request, $"{{\"classname\":\"User\",\"created\":{created},\"unsat\":{{\"count\":3,\"limit\":50}}}}"); + var response = JsonResponse(request, $"{{\"uid\":42,\"classname\":\"User\",\"created\":{created},\"unsat\":{{\"count\":3,\"limit\":50}}}}"); if (setCookie != null) { response.Headers.Add("Set-Cookie", setCookie); @@ -662,11 +760,6 @@ private static HttpResponse ValidSummaryResponse(HttpRequest request, string set return response; } - private static IMamUnsatisfiedSlotGuard CreateSlotGuard() - { - return DispatchProxy.Create(); - } - private static string EligibleAudiobookUrl() { return "https://www.myanonamouse.net/tor/download.php?tid=42&canUseToken=true&isAudiobook=true"; diff --git a/src/NzbDrone.Core/HealthCheck/Checks/MyAnonaMouseAccountSummaryCheck.cs b/src/NzbDrone.Core/HealthCheck/Checks/MyAnonaMouseAccountSummaryCheck.cs new file mode 100644 index 000000000..fcd4a1f02 --- /dev/null +++ b/src/NzbDrone.Core/HealthCheck/Checks/MyAnonaMouseAccountSummaryCheck.cs @@ -0,0 +1,50 @@ +using System.Linq; +using NzbDrone.Core.Indexers; +using NzbDrone.Core.Indexers.MyAnonaMouse; +using NzbDrone.Core.Localization; +using NzbDrone.Core.ThingiProvider.Events; + +namespace NzbDrone.Core.HealthCheck.Checks +{ + [CheckOn(typeof(MyAnonaMouseAccountSummaryHealthChangedEvent))] + [CheckOn(typeof(ProviderUpdatedEvent))] + [CheckOn(typeof(ProviderDeletedEvent))] + public class MyAnonaMouseAccountSummaryCheck : HealthCheckBase + { + private readonly IIndexerFactory _indexerFactory; + private readonly IMyAnonaMouseAccountStatusService _accountStatusService; + + public MyAnonaMouseAccountSummaryCheck(IIndexerFactory indexerFactory, + IMyAnonaMouseAccountStatusService accountStatusService, + ILocalizationService localizationService) + : base(localizationService) + { + _indexerFactory = indexerFactory; + _accountStatusService = accountStatusService; + } + + public override HealthCheck Check() + { + var unreadable = _accountStatusService.GetUnreadableSummaryFailures(); + if (unreadable.Count == 0) + { + return new HealthCheck(GetType()); + } + + var indexerNames = _indexerFactory.All() + .Where(indexer => indexer.Enable && + indexer.Settings is MyAnonaMouseSettings settings && + unreadable.TryGetValue(indexer.Id, out var failedAt) && + (settings.UnsatisfiedStatusRefreshedUtc is not { } refreshedAt || refreshedAt <= failedAt)) + .Select(indexer => indexer.Name) + .ToList(); + if (indexerNames.Count == 0) + { + return new HealthCheck(GetType()); + } + + return new HealthCheck(GetType(), HealthCheckResult.Warning, + string.Format(_localizationService.GetLocalizedString("MyAnonaMouseAccountSummaryUnreadable"), string.Join(", ", indexerNames))); + } + } +} diff --git a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MamUnsatisfiedSlotGuard.cs b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MamUnsatisfiedSlotGuard.cs index bc3493254..f775e8e6e 100644 --- a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MamUnsatisfiedSlotGuard.cs +++ b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MamUnsatisfiedSlotGuard.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using NLog; -using NzbDrone.Core.Indexers; using NzbDrone.Core.Parser.Model; namespace NzbDrone.Core.Indexers.MyAnonaMouse @@ -11,7 +11,6 @@ public interface IMamUnsatisfiedSlotGuard { MamUnsatisfiedSlotAvailability Check(RemoteBook remoteBook); MamUnsatisfiedSlotAvailability TryReserve(RemoteBook remoteBook); - void Reconcile(MyAnonaMouse indexer, MyAnonaMouseAccountStatus status); } public sealed class MamUnsatisfiedSlotAvailability @@ -38,18 +37,17 @@ public static MamUnsatisfiedSlotAvailability Reject(string reason) public class MamUnsatisfiedSlotGuard : IMamUnsatisfiedSlotGuard { + // Covers delayed accounting and clock skew. Revisit 5 minutes after more timing tests. + internal static readonly TimeSpan SummaryAccountingLag = TimeSpan.FromMinutes(10); + private static readonly TimeSpan MaximumStatusAge = TimeSpan.FromHours(2); - // MAM documents a 5-20 minute lag before snatches reach account summaries. Keep counting locally through the full window. - private static readonly TimeSpan SummaryAccountingLag = TimeSpan.FromMinutes(20); private readonly IIndexerFactory _indexerFactory; private readonly IMamUnsatisfiedSlotReservationRepository _repository; private readonly Logger _logger; private readonly object _reservationLock = new object(); - public MamUnsatisfiedSlotGuard(IIndexerFactory indexerFactory, - IMamUnsatisfiedSlotReservationRepository repository, - Logger logger) + public MamUnsatisfiedSlotGuard(IIndexerFactory indexerFactory, IMamUnsatisfiedSlotReservationRepository repository, Logger logger) { _indexerFactory = indexerFactory; _repository = repository; @@ -72,45 +70,7 @@ public MamUnsatisfiedSlotAvailability TryReserve(RemoteBook remoteBook) } } - public void Reconcile(MyAnonaMouse indexer, MyAnonaMouseAccountStatus status) - { - if (indexer?.Definition is not IndexerDefinition definition || - definition.Settings is not MyAnonaMouseSettings settings || - !settings.ProtectUnsatisfiedSlots || - status == null) - { - return; - } - - var reservations = GetAccountReservations(definition, settings); - - // This does not infer that a torrent became satisfied. Once MAM's own snapshot covers the - // latest attempt plus its documented accounting lag, a served torrent is in the reported - // count and an unserved attempt is a phantom; either way, retaining the row would double-count. - foreach (var reservation in reservations.Where(r => - status.SnapshotCreatedUtc >= (r.ConfirmedUtc ?? r.ReservedUtc).Add(SummaryAccountingLag))) - { - lock (_reservationLock) - { - var current = _repository.Find(reservation.IndexerId, reservation.TorrentId); - if (current != null && - status.SnapshotCreatedUtc >= (current.ConfirmedUtc ?? current.ReservedUtc).Add(SummaryAccountingLag)) - { - var accountingAnchor = current.ConfirmedUtc ?? current.ReservedUtc; - _repository.Delete(current.Id); - _logger.Debug( - "Retired MAM slot reservation for torrent {0} on indexer '{1}': provider snapshot {2:u} covers {3:u} plus the {4}-minute accounting window", - current.TorrentId, - definition.Name, - status.SnapshotCreatedUtc, - accountingAnchor, - SummaryAccountingLag.TotalMinutes); - } - } - } - } - - internal static bool TryGetTorrentId(ReleaseInfo release, out string torrentId) + private static bool TryGetTorrentId(ReleaseInfo release, out string torrentId) { torrentId = null; var guid = release?.Guid; @@ -131,14 +91,10 @@ internal static bool TryGetTorrentId(ReleaseInfo release, out string torrentId) private MamUnsatisfiedSlotAvailability Evaluate(RemoteBook remoteBook, bool reserve) { + var started = Stopwatch.GetTimestamp(); var release = remoteBook?.Release; - var definition = GetMamDefinition(release); - if (definition == null) - { - return MamUnsatisfiedSlotAvailability.Accept(); - } - - if (definition.Settings is not MyAnonaMouseSettings settings || !settings.ProtectUnsatisfiedSlots) + var definition = release?.IndexerId > 0 ? _indexerFactory.Find(release.IndexerId) : null; + if (definition?.Settings is not MyAnonaMouseSettings settings || !settings.ProtectUnsatisfiedSlots) { return MamUnsatisfiedSlotAvailability.Accept(); } @@ -148,31 +104,36 @@ private MamUnsatisfiedSlotAvailability Evaluate(RemoteBook remoteBook, bool rese return MamUnsatisfiedSlotAvailability.Reject("MAM safety pause: this release has no valid MAM torrent identity"); } - var reservations = GetAccountReservations(definition, settings); - var existingReservation = reservations.FirstOrDefault(r => string.Equals(r.TorrentId, torrentId, StringComparison.Ordinal)); - if (existingReservation != null) - { - if (reserve && !existingReservation.ConfirmedUtc.HasValue) - { - existingReservation.ReservedUtc = DateTime.UtcNow; - _repository.Update(existingReservation); - } - - return MamUnsatisfiedSlotAvailability.Accept(); - } - var now = DateTime.UtcNow; if (!HasFreshStatus(settings, now)) { return MamUnsatisfiedSlotAvailability.Reject("MAM safety pause: the unsatisfied-slot status is unavailable or stale; test the indexer and try again"); } + // MAM's count at the last check plus the other torrents grabbed on that account since then. + var reservations = _repository.All().ToList(); + var countedSince = settings.UnsatisfiedSnapshotUtc.Value - SummaryAccountingLag; + var recent = reservations.Where(r => r.ReservedUtc > countedSince && r.TorrentId != torrentId).ToList(); + var otherAccountIndexerIds = GetOtherAccountIndexerIds(recent, definition.Id, settings.UserId); + var grabsSince = recent + .Where(r => !otherAccountIndexerIds.Contains(r.IndexerId)) + .Select(r => r.TorrentId) + .Distinct() + .Count(); + var effectiveUnsatisfied = settings.UnsatisfiedCount.Value + grabsSince; + var manualGrab = remoteBook.ReleaseSource == ReleaseSourceType.InteractiveSearch; var safetyReserve = Math.Max(0, settings.UnsatisfiedSlotReserve); var manualGrabBuffer = Math.Max(0, settings.ManualGrabBuffer); var reservedSlots = safetyReserve + (manualGrab ? 0 : manualGrabBuffer); var usableSlots = Math.Max(0, settings.UnsatisfiedLimit.Value - reservedSlots); - var effectiveUnsatisfied = settings.UnsatisfiedCount.Value + reservations.Count; + + if (!reserve) + { + _logger.Trace( + "Checked MAM torrent {0} on indexer '{1}': {2} reported at the last check plus {3} grabbed since, {4} usable, read {5} reservation rows in {6:F1} ms", + torrentId, definition.Name, settings.UnsatisfiedCount.Value, grabsSince, usableSlots, reservations.Count, Stopwatch.GetElapsedTime(started).TotalMilliseconds); + } if (effectiveUnsatisfied >= usableSlots) { @@ -186,48 +147,46 @@ private MamUnsatisfiedSlotAvailability Evaluate(RemoteBook remoteBook, bool rese if (reserve) { - _repository.Insert(new MamUnsatisfiedSlotReservation - { - IndexerId = definition.Id, - TorrentId = torrentId, - ReservedUtc = now - }); + var reservation = reservations.FirstOrDefault(r => r.IndexerId == definition.Id && r.TorrentId == torrentId) ?? + new MamUnsatisfiedSlotReservation { IndexerId = definition.Id, TorrentId = torrentId }; + // A retry may be the first request MAM counts, so it restarts this torrent's window. + reservation.ReservedUtc = now; + _repository.Upsert(reservation); + + // Status older than two hours is never used, so no usable check can still count these grabs. + var expired = reservations.Where(r => r.ReservedUtc <= now - MaximumStatusAge - SummaryAccountingLag).Select(r => r.Id).ToList(); + _repository.DeleteMany(expired); + + _logger.Debug( + "Reserved MAM torrent {0} on indexer '{1}': {2} reported at the last check plus {3} grabbed since, {4} usable; read {5} reservation rows and removed {6} old records in {7:F1} ms", + torrentId, + definition.Name, + settings.UnsatisfiedCount.Value, + grabsSince, + usableSlots, + reservations.Count, + expired.Count, + Stopwatch.GetElapsedTime(started).TotalMilliseconds); } return MamUnsatisfiedSlotAvailability.Accept(); } - private IndexerDefinition GetMamDefinition(ReleaseInfo release) + // MAM tracks unsatisfied slots per user ID, not per indexer, so every MAM indexer on one user ID shares the count. + private HashSet GetOtherAccountIndexerIds(List recent, int indexerId, string userId) { - if (release?.IndexerId <= 0) + if (string.IsNullOrWhiteSpace(userId)) { - return null; + return new HashSet(); } - var definition = _indexerFactory.Find(release.IndexerId); - return definition?.Settings is MyAnonaMouseSettings ? definition : null; - } - - // MAM reports one unsatisfied limit per account. Native indexers sharing the same mam_id - // must also share in-flight reservations or each can spend the same apparent free slots. - private List GetAccountReservations( - IndexerDefinition definition, - MyAnonaMouseSettings settings) - { - var accountIndexerIds = _indexerFactory.All() - .Where(candidate => - candidate.Id > 0 && - candidate.Settings is MyAnonaMouseSettings candidateSettings && - !string.IsNullOrWhiteSpace(settings.MamId) && - string.Equals(candidateSettings.MamId, settings.MamId, StringComparison.Ordinal)) - .Select(candidate => candidate.Id) + return recent.Select(r => r.IndexerId) + .Where(id => id != indexerId) + .Distinct() + .Where(id => _indexerFactory.Find(id)?.Settings is MyAnonaMouseSettings other && + !string.IsNullOrWhiteSpace(other.UserId) && + other.UserId != userId) .ToHashSet(); - - accountIndexerIds.Add(definition.Id); - - return _repository.All() - .Where(reservation => accountIndexerIds.Contains(reservation.IndexerId)) - .ToList(); } internal static bool HasFreshStatus(MyAnonaMouseSettings settings, DateTime now) @@ -247,6 +206,5 @@ internal static bool HasFreshStatus(MyAnonaMouseSettings settings, DateTime now) now - settings.UnsatisfiedSnapshotUtc.Value <= MaximumStatusAge && now - settings.UnsatisfiedStatusRefreshedUtc.Value <= MaximumStatusAge; } - } } diff --git a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MamUnsatisfiedSlotReservation.cs b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MamUnsatisfiedSlotReservation.cs index b6d906f46..66bd2b3c1 100644 --- a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MamUnsatisfiedSlotReservation.cs +++ b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MamUnsatisfiedSlotReservation.cs @@ -8,6 +8,5 @@ public class MamUnsatisfiedSlotReservation : ModelBase public int IndexerId { get; set; } public string TorrentId { get; set; } public DateTime ReservedUtc { get; set; } - public DateTime? ConfirmedUtc { get; set; } } } diff --git a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MamUnsatisfiedSlotReservationRepository.cs b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MamUnsatisfiedSlotReservationRepository.cs index a8123204f..5b175f6db 100644 --- a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MamUnsatisfiedSlotReservationRepository.cs +++ b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MamUnsatisfiedSlotReservationRepository.cs @@ -1,5 +1,3 @@ -using System.Collections.Generic; -using System.Linq; using NzbDrone.Core.Datastore; using NzbDrone.Core.Messaging.Events; @@ -7,8 +5,6 @@ namespace NzbDrone.Core.Indexers.MyAnonaMouse { public interface IMamUnsatisfiedSlotReservationRepository : IBasicRepository { - List AllForIndexer(int indexerId); - MamUnsatisfiedSlotReservation Find(int indexerId, string torrentId); } public class MamUnsatisfiedSlotReservationRepository : BasicRepository, IMamUnsatisfiedSlotReservationRepository @@ -17,20 +13,5 @@ public MamUnsatisfiedSlotReservationRepository(IMainDatabase database, IEventAgg : base(database, eventAggregator) { } - - public List AllForIndexer(int indexerId) - { - return Query(r => r.IndexerId == indexerId); - } - - public MamUnsatisfiedSlotReservation Find(int indexerId, string torrentId) - { - if (indexerId <= 0 || string.IsNullOrWhiteSpace(torrentId)) - { - return null; - } - - return Query(r => r.IndexerId == indexerId && r.TorrentId == torrentId).SingleOrDefault(); - } } } diff --git a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouse.cs b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouse.cs index be0de59a4..d2f9413e1 100644 --- a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouse.cs +++ b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouse.cs @@ -17,8 +17,6 @@ namespace NzbDrone.Core.Indexers.MyAnonaMouse { public class MyAnonaMouse : HttpIndexerBase { - private readonly IMamUnsatisfiedSlotReservationRepository _slotReservationRepository; - public override string Name => "MyAnonaMouse"; public override DownloadProtocol Protocol => DownloadProtocol.Torrent; @@ -26,11 +24,9 @@ public class MyAnonaMouse : HttpIndexerBase public override bool SupportsSearch => true; public override int PageSize => 100; - public MyAnonaMouse(IIndexerHttpClientFactory httpClientFactory, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, - IMamUnsatisfiedSlotReservationRepository slotReservationRepository, Logger logger) + public MyAnonaMouse(IIndexerHttpClientFactory httpClientFactory, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) : base(httpClientFactory, indexerStatusService, configService, parsingService, logger) { - _slotReservationRepository = slotReservationRepository; } public override IEnumerable DefaultDefinitions @@ -140,7 +136,6 @@ public override async Task ExecuteDownloadRequestAsync(HttpRequest var response = await base.ExecuteDownloadRequestAsync(request); if (!HasFreeleechParameter(request?.Url?.FullUri) || IsTorrentResponse(response)) { - ConfirmServedTorrent(request, response); return response; } @@ -151,9 +146,7 @@ public override async Task ExecuteDownloadRequestAsync(HttpRequest fallbackRequest.RequestTimeout = request.RequestTimeout; fallbackRequest.Headers.Accept = request.Headers.Accept; - var fallbackResponse = await base.ExecuteDownloadRequestAsync(fallbackRequest); - ConfirmServedTorrent(fallbackRequest, fallbackResponse); - return fallbackResponse; + return await base.ExecuteDownloadRequestAsync(fallbackRequest); } protected override async Task TestConnection() @@ -253,7 +246,7 @@ private void PersistRefreshedMamId(HttpResponse response) return; } - _logger.Info("MAM issued a refreshed mam_id for indexer '{0}', persisting it", Definition?.Name); + _logger.Debug("MAM issued a refreshed mam_id for indexer '{0}'", Definition?.Name); Settings.MamId = refreshedMamId; } @@ -264,6 +257,7 @@ public async Task RefreshAccountStatus() .SetHeader("User-Agent", $"{BuildInfo.AppName}/{BuildInfo.Version}") .Build(); + request.SuppressHttpErrorStatusCodes = new[] { HttpStatusCode.NotFound }; request.RateLimitKey = Definition?.Id > 0 ? Definition.Id.ToString() : null; request.Cookies["mam_id"] = Settings.MamId; if (Settings.MamSsl) @@ -273,26 +267,39 @@ public async Task RefreshAccountStatus() var response = await _httpClient.ExecuteAsync(request); + if (response.StatusCode == HttpStatusCode.NotFound) + { + throw new MyAnonaMouseAccountSummaryException("MAM account summary endpoint returned HTTP 404"); + } + if (response.StatusCode != HttpStatusCode.OK) { throw new InvalidOperationException($"Failed to fetch MAM user data: HTTP {(int)response.StatusCode} {response.StatusCode}"); } - PersistRefreshedMamId(response); + MyAnonaMouseUserDataResponse userData; + try + { + userData = JsonConvert.DeserializeObject(response.Content); + } + catch (JsonException) + { + throw new MyAnonaMouseAccountSummaryException("MAM user data response could not be decoded"); + } - var userData = JsonConvert.DeserializeObject(response.Content); var className = userData?.ClassName; if (string.IsNullOrWhiteSpace(className)) { - throw new InvalidOperationException("MAM user data response did not include a user class"); + throw new MyAnonaMouseAccountSummaryException("MAM user data response did not include a user class"); } + var userId = userData.UserId; userData = userData.SnatchSummary ?? userData; if (userData.Unsatisfied == null || userData.Unsatisfied.Count < 0 || userData.Unsatisfied.Limit <= 0 || userData.Created <= 0) { - throw new InvalidOperationException("MAM user data response did not include a valid unsatisfied-torrent summary"); + throw new MyAnonaMouseAccountSummaryException("MAM user data response did not include a valid unsatisfied-torrent summary"); } DateTime snapshotCreatedUtc; @@ -300,19 +307,26 @@ public async Task RefreshAccountStatus() { snapshotCreatedUtc = DateTimeOffset.FromUnixTimeSeconds(userData.Created).UtcDateTime; } - catch (ArgumentOutOfRangeException ex) + catch (ArgumentOutOfRangeException) { - throw new InvalidOperationException("MAM user data response included an invalid summary timestamp", ex); + throw new MyAnonaMouseAccountSummaryException("MAM user data response included an invalid summary timestamp"); } var refreshedUtc = DateTime.UtcNow; var isVip = IsVipClass(className); + if (string.IsNullOrWhiteSpace(userId)) + { + _logger.Debug("MAM account response for indexer '{0}' had no user ID, so other MAM indexers' grabs count toward its limit", Definition?.Name); + } + + Settings.UserId = userId; Settings.UserClass = className; Settings.IsVip = isVip; Settings.UnsatisfiedCount = userData.Unsatisfied.Count; Settings.UnsatisfiedLimit = userData.Unsatisfied.Limit; Settings.UnsatisfiedSnapshotUtc = snapshotCreatedUtc; Settings.UnsatisfiedStatusRefreshedUtc = refreshedUtc; + PersistRefreshedMamId(response); _logger.Debug("MAM account status detected: {0} (VIP: {1}), unsatisfied {2}/{3}", className, isVip, userData.Unsatisfied.Count, userData.Unsatisfied.Limit); @@ -361,36 +375,6 @@ private static string RemoveFreeleechParameter(string url) (string.IsNullOrWhiteSpace(queryString) ? string.Empty : "?" + queryString); } - private void ConfirmServedTorrent(HttpRequest request, HttpResponse response) - { - if (_slotReservationRepository == null || - Definition?.Id <= 0 || - !IsTorrentResponse(response) || - !Uri.TryCreate(request?.Url?.FullUri, UriKind.Absolute, out var uri)) - { - return; - } - - var torrentId = System.Web.HttpUtility.ParseQueryString(uri.Query)["tid"]; - if (string.IsNullOrWhiteSpace(torrentId)) - { - return; - } - - var reservation = _slotReservationRepository.Find(Definition.Id, torrentId); - if (reservation == null || reservation.ConfirmedUtc.HasValue) - { - return; - } - - reservation.ConfirmedUtc = DateTime.UtcNow; - _slotReservationRepository.Update(reservation); - _logger.Debug( - "Confirmed MAM slot reservation for torrent {0} on indexer '{1}' when MAM returned a valid torrent payload", - torrentId, - Definition.Name); - } - private static bool IsTorrentResponse(HttpResponse response) { if (response?.StatusCode != HttpStatusCode.OK || response.ResponseData?.Length == 0) @@ -422,6 +406,9 @@ public class MyAnonaMouseAccountStatus public class MyAnonaMouseUserDataResponse { + [JsonProperty("uid")] + public string UserId { get; set; } + [JsonProperty("snatch_summary")] public MyAnonaMouseUserDataResponse SnatchSummary { get; set; } diff --git a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseAccountStatusService.cs b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseAccountStatusService.cs index ae4761e5e..ab9299172 100644 --- a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseAccountStatusService.cs +++ b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseAccountStatusService.cs @@ -1,4 +1,6 @@ using System; +using System.Collections.Concurrent; +using System.Collections.Generic; using System.Linq; using NLog; using NzbDrone.Core.HealthCheck; @@ -9,27 +11,37 @@ namespace NzbDrone.Core.Indexers.MyAnonaMouse { - public class MyAnonaMouseAccountStatusService : IHandle, + public interface IMyAnonaMouseAccountStatusService + { + IReadOnlyDictionary GetUnreadableSummaryFailures(); + } + + public class MyAnonaMouseAccountStatusService : IMyAnonaMouseAccountStatusService, + IHandle, IHandle, IExecute { private readonly IIndexerFactory _indexerFactory; + private readonly IEventAggregator _eventAggregator; private readonly Logger _logger; - private readonly IMamUnsatisfiedSlotGuard _slotGuard; private readonly object _refreshLock = new object(); + private readonly ConcurrentDictionary _unreadableSummaries = new(); private DateTime _lastRefreshAttemptUtc = DateTime.MinValue; private bool _refreshInProgress; private static readonly TimeSpan RefreshInterval = TimeSpan.FromHours(1); - public MyAnonaMouseAccountStatusService(IIndexerFactory indexerFactory, - IMamUnsatisfiedSlotGuard slotGuard, - Logger logger) + public MyAnonaMouseAccountStatusService(IIndexerFactory indexerFactory, IEventAggregator eventAggregator, Logger logger) { _indexerFactory = indexerFactory; + _eventAggregator = eventAggregator; _logger = logger; - _slotGuard = slotGuard; + } + + public IReadOnlyDictionary GetUnreadableSummaryFailures() + { + return _unreadableSummaries; } [EventHandleOrder(EventHandleOrder.Last)] @@ -71,6 +83,7 @@ private void RefreshAccountStatuses(string source) var refreshed = 0; var changed = 0; + var summaryHealthChanged = false; foreach (var indexer in _indexerFactory.GetAvailableProviders().OfType()) { @@ -89,11 +102,11 @@ private void RefreshAccountStatuses(string source) try { var status = indexer.RefreshAccountStatus().GetAwaiter().GetResult(); + summaryHealthChanged |= _unreadableSummaries.TryRemove(definition.Id, out _); refreshed++; // Persist every successful fetch because its refresh timestamp is the restart-safe freshness boundary. _indexerFactory.Update(definition); - _slotGuard.Reconcile(indexer, status); if (!string.Equals(previousUserClass, status.UserClass, StringComparison.Ordinal) || previousIsVip != status.IsVip || @@ -110,12 +123,23 @@ private void RefreshAccountStatuses(string source) status.UnsatisfiedLimit); } } + catch (MyAnonaMouseAccountSummaryException ex) + { + _unreadableSummaries[definition.Id] = DateTime.UtcNow; + summaryHealthChanged = true; + _logger.Warn("Failed to read MAM account summary for indexer '{0}': {1}", definition.Name, ex.Message); + } catch (Exception ex) { _logger.Warn("Failed to refresh MAM account status for indexer '{0}' ({1})", definition.Name, ex.GetType().Name); } } + if (summaryHealthChanged) + { + _eventAggregator.PublishEvent(new MyAnonaMouseAccountSummaryHealthChangedEvent()); + } + _logger.Debug("Refreshed MAM account status for {0} indexers; {1} changed", refreshed, changed); } diff --git a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseAccountSummaryException.cs b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseAccountSummaryException.cs new file mode 100644 index 000000000..67ba8bb8e --- /dev/null +++ b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseAccountSummaryException.cs @@ -0,0 +1,12 @@ +using System; + +namespace NzbDrone.Core.Indexers.MyAnonaMouse +{ + internal class MyAnonaMouseAccountSummaryException : InvalidOperationException + { + public MyAnonaMouseAccountSummaryException(string message) + : base(message) + { + } + } +} diff --git a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseAccountSummaryHealthChangedEvent.cs b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseAccountSummaryHealthChangedEvent.cs new file mode 100644 index 000000000..3e3675f8c --- /dev/null +++ b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseAccountSummaryHealthChangedEvent.cs @@ -0,0 +1,8 @@ +using NzbDrone.Common.Messaging; + +namespace NzbDrone.Core.Indexers.MyAnonaMouse +{ + internal class MyAnonaMouseAccountSummaryHealthChangedEvent : IEvent + { + } +} diff --git a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseRequestGenerator.cs b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseRequestGenerator.cs index b1306f715..0dd53a376 100644 --- a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseRequestGenerator.cs @@ -20,7 +20,7 @@ public class MyAnonaMouseRequestGenerator : IIndexerRequestGenerator private const int RecentPageSize = 500; private const int SearchPageSize = 100; private const int SearchMaxPages = 10; - private static readonly Regex BookNumberSuffixRegex = new Regex(@"\s*,?\s*book\s+\d+\s*$", RegexOptions.IgnoreCase | RegexOptions.Compiled); + private static readonly Regex BookNumberSuffixRegex = new Regex(@"\s*book\s+\d+\s*$", RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly Regex MultiWhitespaceRegex = new Regex(@"\s{2,}", RegexOptions.Compiled); public MyAnonaMouseSettings Settings { get; set; } @@ -78,7 +78,7 @@ private List BuildBookSearchTerms(BookSearchCriteria searchCriteria, str void AddSearchTerm(string term, string logMessage) { - var normalized = term?.Trim() ?? string.Empty; + var normalized = MultiWhitespaceRegex.Replace(term ?? string.Empty, " ").Trim(); if (string.IsNullOrWhiteSpace(normalized)) { return; @@ -101,44 +101,12 @@ void AddSearchTerm(string term, string logMessage) searchTerms.Add(normalized); } - // MAM expects raw text, not URL-encoded. Keep the primary behavior of including both title and author terms. - var decodedTitle = string.IsNullOrWhiteSpace(bookQuery) ? - string.Empty : - System.Web.HttpUtility.UrlDecode(bookQuery); - - // AuthorQuery is normalized via SearchCriteriaBase.GetQueryTitle (handles punctuation like "J.K." -> "J K") - var decodedAuthor = string.IsNullOrWhiteSpace(authorQuery) ? - string.Empty : - System.Web.HttpUtility.UrlDecode(authorQuery); - - // MAM search can be sensitive to different apostrophe characters. Normalize early so both the primary and - // fallback queries use the same representation without increasing request count. - var originalDecodedTitle = decodedTitle; - var originalDecodedAuthor = decodedAuthor; - decodedTitle = NormalizeApostrophes(decodedTitle); - decodedAuthor = NormalizeApostrophes(decodedAuthor); - if (!string.Equals(decodedTitle, originalDecodedTitle, StringComparison.Ordinal) || - !string.Equals(decodedAuthor, originalDecodedAuthor, StringComparison.Ordinal)) - { - Logger.Debug("MAM_SEARCH_APOSTROPHE_NORMALIZED: title '{0}' -> '{1}', author '{2}' -> '{3}'", - originalDecodedTitle, - decodedTitle, - originalDecodedAuthor, - decodedAuthor); - } + // MAM expects raw text, not URL-encoded. + var decodedTitle = System.Web.HttpUtility.UrlDecode(bookQuery); + var decodedAuthor = System.Web.HttpUtility.UrlDecode(authorQuery); + var decodedQuery = string.Join(" ", new[] { decodedTitle, decodedAuthor }.Where(term => !string.IsNullOrWhiteSpace(term))); - var decodedQuery = decodedTitle?.Trim() ?? string.Empty; - if (!string.IsNullOrWhiteSpace(decodedAuthor)) - { - if (!string.IsNullOrWhiteSpace(decodedQuery)) - { - decodedQuery += " "; - } - - decodedQuery += decodedAuthor.Trim(); - } - - var narratorQuery = NormalizeApostrophes(System.Web.HttpUtility.UrlDecode(searchCriteria.NarratorQuery)); + var narratorQuery = System.Web.HttpUtility.UrlDecode(searchCriteria.NarratorQuery); if (!string.IsNullOrWhiteSpace(narratorQuery)) { AddSearchTerm($"{decodedQuery} {narratorQuery}", "MAM_SEARCH_TERM: '{0}' (pinned narrator)"); @@ -146,21 +114,12 @@ void AddSearchTerm(string term, string logMessage) AddSearchTerm(decodedQuery, "MAM_SEARCH_TERM: '{0}' (title and author)"); - if (!string.IsNullOrWhiteSpace(decodedTitle) && - !string.Equals(decodedTitle.Trim(), decodedQuery, StringComparison.OrdinalIgnoreCase)) - { - AddSearchTerm(decodedTitle, "MAM_SEARCH_FALLBACK_TERM: '{0}' (title-only fallback)"); - } + AddSearchTerm(decodedTitle, "MAM_SEARCH_FALLBACK_TERM: '{0}' (title-only fallback)"); // Interactive search: add a fallback query for verbose titles like "... , Book 3" that can hurt recall. - if (searchCriteria.InteractiveSearch && !string.IsNullOrWhiteSpace(decodedTitle)) + if (searchCriteria.InteractiveSearch) { - var fallbackTitle = BookNumberSuffixRegex.Replace(decodedTitle, string.Empty).Trim(); - if (!string.IsNullOrWhiteSpace(fallbackTitle) && - !string.Equals(fallbackTitle, decodedTitle.Trim(), StringComparison.OrdinalIgnoreCase)) - { - AddSearchTerm(fallbackTitle, "MAM_SEARCH_FALLBACK_TERM: '{0}' (book-number fallback)"); - } + AddSearchTerm(BookNumberSuffixRegex.Replace(decodedTitle, string.Empty), "MAM_SEARCH_FALLBACK_TERM: '{0}' (book-number fallback)"); } return searchTerms; @@ -178,20 +137,6 @@ internal IEnumerable GetJsonApiRequests(string searchText, Searc } } - private static string NormalizeApostrophes(string title) - { - if (string.IsNullOrWhiteSpace(title)) - { - return title; - } - - // Normalize both straight and curly apostrophes. Replace with whitespace to keep token boundaries stable - // (e.g., "Sorcerer's" -> "Sorcerer s") across different search implementations. - var normalized = title.Replace("’", " ").Replace("'", " "); - normalized = MultiWhitespaceRegex.Replace(normalized, " ").Trim(); - return normalized; - } - private static string GetSafeBookQuery(BookSearchCriteria searchCriteria) { var title = BookSearchCriteria.GetMainSearchTitle(searchCriteria?.BookTitle, searchCriteria?.Author?.Name); diff --git a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseSettings.cs b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseSettings.cs index 4f6e0826e..341950371 100644 --- a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseSettings.cs +++ b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseSettings.cs @@ -99,6 +99,7 @@ public int UseFreeleechWedge public bool NeverMoveOnImport { get; set; } // Persisted provider snapshot used by the grab guard. These are not user-editable. + public string UserId { get; set; } public int? UnsatisfiedCount { get; set; } public int? UnsatisfiedLimit { get; set; } public DateTime? UnsatisfiedSnapshotUtc { get; set; } diff --git a/src/NzbDrone.Core/Localization/Core/en.json b/src/NzbDrone.Core/Localization/Core/en.json index 5c712f179..9cbd841a0 100644 --- a/src/NzbDrone.Core/Localization/Core/en.json +++ b/src/NzbDrone.Core/Localization/Core/en.json @@ -1281,6 +1281,7 @@ "MusicBrainzTrackID": "MusicBrainz Track ID", "MustContain": "Must Contain", "MustNotContain": "Must Not Contain", + "MyAnonaMouseAccountSummaryUnreadable": "Chaptarr can't read MyAnonaMouse's account reply for {0}, so its login isn't being renewed. With unsatisfied-slot protection on, grabs pause when the last valid summary expires. Please report this.", "MyAnonaMouseSeedTimeHelpText": "Seed-time goal in hours, where supported by the download client. Leave blank or enter 0 to use the client's defaults. MAM requires 72 hours within 30 days; positive values below 72 hours will warn. Preserve torrents takes priority; support for unlimited seeding depends on your download client.", "MyAnonaMouseStatus": "MyAnonaMouse {status}", "NETCore": ".NET Core", From cb590ef2e33596fd86fc314a15ae94ace79d54e8 Mon Sep 17 00:00:00 2001 From: robertlordhood <204023072+robertlordhood@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:48:56 +0000 Subject: [PATCH 4/6] fix(MyAnonaMouse): contact MAM only when needed Limit MAM's account summary to one request a minute across Chaptarr. Inside the minute, a repeat check on the same connection, or on the cookie MAM just issued, reuses the last reply and any other check waits. A failed check is never reused. Saving no longer tests MAM unless the URL, cookie, SSL setting or proxy is new, meaning it matches neither the saved one nor the last passed Test, including the cookie MAM issued during that Test. Priority or tag edits, re-enabling and slot protection changes send nothing. A Save after a passed Test keeps that Test's account status and cookie when they are newer than the saved ones, even if nothing else changed. Keep MAM's Test message. The indexer test overwrote it after the connection check, so the member class line and the account status warning never reached the Test dialog. Keep the stored VIP flag and member class when the settings form is saved, so a page opened before an account check can't overwrite them. Only strip a standalone "Book N" in the interactive search fallback, so "Spellbook 2" stays whole. --- .../Indexers/IndexerController.cs | 68 ++- src/Chaptarr.Api.V1/ProviderControllerBase.cs | 15 +- .../Indexers/IndexerSettingsTestFixture.cs | 444 +++++++++++++++++- .../MyAnonaMouseRequestGeneratorFixture.cs | 18 +- .../Indexers/MyAnonaMouseSeedTimeFixture.cs | 2 +- .../Indexers/MyAnonaMouseWedgeFixture.cs | 210 ++++++++- src/NzbDrone.Core/Indexers/IndexerFactory.cs | 2 + .../Indexers/MyAnonaMouse/MamConnection.cs | 12 + .../MyAnonaMouse/MamUnsatisfiedSlotGuard.cs | 4 +- .../Indexers/MyAnonaMouse/MyAnonaMouse.cs | 71 ++- .../MyAnonaMouseAccountSummaryThrottle.cs | 81 ++++ .../MyAnonaMouseRequestGenerator.cs | 2 +- .../MyAnonaMouse/MyAnonaMouseSettings.cs | 25 +- 13 files changed, 883 insertions(+), 71 deletions(-) create mode 100644 src/NzbDrone.Core/Indexers/MyAnonaMouse/MamConnection.cs create mode 100644 src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseAccountSummaryThrottle.cs diff --git a/src/Chaptarr.Api.V1/Indexers/IndexerController.cs b/src/Chaptarr.Api.V1/Indexers/IndexerController.cs index f33934103..b24c1f0e0 100644 --- a/src/Chaptarr.Api.V1/Indexers/IndexerController.cs +++ b/src/Chaptarr.Api.V1/Indexers/IndexerController.cs @@ -1,6 +1,8 @@ using Chaptarr.Http; using FluentValidation; +using NzbDrone.Common.Cache; using NzbDrone.Core.Indexers; +using NzbDrone.Core.Indexers.MyAnonaMouse; using NzbDrone.Core.Validation; namespace Chaptarr.Api.V1.Indexers @@ -11,11 +13,75 @@ public class IndexerController : ProviderControllerBase _mamTests; + + public IndexerController(IIndexerFactory indexerFactory, DownloadClientExistsValidator downloadClientExistsValidator, ICacheManager cacheManager) : base(indexerFactory, "indexer", ResourceMapper, BulkResourceMapper) { + _mamTests = cacheManager.GetCache(typeof(IndexerController)); SharedValidator.RuleFor(c => c.Priority).InclusiveBetween(1, 50); SharedValidator.RuleFor(c => c.DownloadClientId).SetValidator(downloadClientExistsValidator); } + + protected override void Test(IndexerDefinition definition, bool includeWarnings) + { + if (definition.Settings is not MyAnonaMouseSettings settings) + { + base.Test(definition, includeWarnings); + return; + } + + var connection = MamConnection.For(definition); + var key = definition.Id.ToString(); + _mamTests.Remove(key); + base.Test(definition, includeWarnings); + + _mamTests.Set(key, new MamTestResult(connection, settings)); + } + + protected override void PrepareForSave(IndexerDefinition definition, IndexerDefinition existing) + { + if (definition.Settings is not MyAnonaMouseSettings settings) + { + return; + } + + // Quickstart reads the hidden class field, but a form opened before a refresh can post its old value. + if (existing?.Settings is MyAnonaMouseSettings stored) + { + settings.UserClass = stored.UserClass; + } + + var tested = _mamTests.Find(definition.Id.ToString()); + if (tested?.Covers(MamConnection.For(definition)) == true && + tested.Settings.UnsatisfiedStatusRefreshedUtc is { } testedAt && + (settings.UnsatisfiedStatusRefreshedUtc is not { } storedAt || testedAt > storedAt)) + { + settings.CopyAccountStatusFrom(tested.Settings); + } + } + + protected override void TestOnSave(IndexerDefinition definition, IndexerDefinition existing, bool includeWarnings) + { + var connection = MamConnection.For(definition); + if (connection == null) + { + base.TestOnSave(definition, existing, includeWarnings); + return; + } + + if (connection == MamConnection.For(existing) || _mamTests.Find(definition.Id.ToString())?.Covers(connection) == true) + { + return; + } + + base.Test(definition, includeWarnings); + } + + private sealed record MamTestResult(MamConnection Connection, MyAnonaMouseSettings Settings) + { + public bool Covers(MamConnection connection) => + connection == Connection || connection == Connection with { MamId = Settings.MamId }; + } } } diff --git a/src/Chaptarr.Api.V1/ProviderControllerBase.cs b/src/Chaptarr.Api.V1/ProviderControllerBase.cs index 82128c263..718d60df2 100644 --- a/src/Chaptarr.Api.V1/ProviderControllerBase.cs +++ b/src/Chaptarr.Api.V1/ProviderControllerBase.cs @@ -76,13 +76,14 @@ public List GetAll() public ActionResult CreateProvider([FromBody] TProviderResource providerResource, [FromQuery] bool forceSave = false) { var providerDefinition = GetDefinition(providerResource, true, !forceSave, false, true); + PrepareForSave(providerDefinition, null); // Set provider characteristics (e.g., SupportsRss, SupportsSearch) before creation _providerFactory.SetProviderCharacteristics(providerDefinition); if (providerDefinition.Enable) { - Test(providerDefinition, !forceSave); + TestOnSave(providerDefinition, null, !forceSave); } providerDefinition = _providerFactory.Create(providerDefinition); @@ -97,6 +98,7 @@ public ActionResult UpdateProvider([FromBody] TProviderResour { var existing = _providerFactory.Get(providerResource.Id); var providerDefinition = GetDefinition(providerResource, true, !forceSave, false, !forceSave, existing); + PrepareForSave(providerDefinition, existing); var comparison = _resourceMapper.ToModel(STJson.Deserialize(STJson.ToJson(_resourceMapper.ToResource(existing)))); comparison.Settings = existing.Settings; _providerFactory.SetProviderCharacteristics(comparison); @@ -110,7 +112,7 @@ public ActionResult UpdateProvider([FromBody] TProviderResour // Test enabled definitions unless explicitly bypassed. if (providerDefinition.Enable && !forceSave) { - Test(providerDefinition, true); + TestOnSave(providerDefinition, existing, true); } _providerFactory.Update(providerDefinition); @@ -304,6 +306,15 @@ protected virtual void Validate(TProviderDefinition definition, bool includeWarn VerifyValidationResult(validationResult, includeWarnings); } + protected virtual void PrepareForSave(TProviderDefinition definition, TProviderDefinition existing) + { + } + + protected virtual void TestOnSave(TProviderDefinition definition, TProviderDefinition existing, bool includeWarnings) + { + Test(definition, includeWarnings); + } + protected virtual void Test(TProviderDefinition definition, bool includeWarnings) { var validationResult = _providerFactory.Test(definition); diff --git a/src/Chaptarr.Core.Test/Indexers/IndexerSettingsTestFixture.cs b/src/Chaptarr.Core.Test/Indexers/IndexerSettingsTestFixture.cs index a0675eb8c..c310ba714 100644 --- a/src/Chaptarr.Core.Test/Indexers/IndexerSettingsTestFixture.cs +++ b/src/Chaptarr.Core.Test/Indexers/IndexerSettingsTestFixture.cs @@ -1,20 +1,26 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Net; using System.Reflection; -using Chaptarr.Api.V1; +using System.Threading.Tasks; using Chaptarr.Api.V1.Indexers; using Chaptarr.Http.ClientSchema; using Chaptarr.Core.Test.Common; using NzbDrone.Core.Messaging.Events; using FluentValidation.Results; using Newtonsoft.Json.Linq; +using NLog; using NUnit.Framework; +using NzbDrone.Common.Cache; +using NzbDrone.Common.Http; using NzbDrone.Common.Serializer; +using NzbDrone.Core.Annotations; using NzbDrone.Core.Indexers; +using NzbDrone.Core.Indexers.MyAnonaMouse; using NzbDrone.Core.Indexers.Newznab; using NzbDrone.Core.Localization; -using NzbDrone.Core.ThingiProvider; +using NzbDrone.Core.Validation; using static Chaptarr.Core.Test.Common.InterfaceProxy; namespace Chaptarr.Core.Test.Indexers @@ -22,19 +28,18 @@ namespace Chaptarr.Core.Test.Indexers [TestFixture] public class IndexerSettingsTestFixture { - private sealed class Controller : ProviderControllerBase - { - public Controller(IProviderFactory factory) - : base(factory, "indexer", new IndexerResourceMapper(), new IndexerBulkResourceMapper()) { } - } - private IndexerDefinition _saved; - private Controller _controller; + private IndexerController _controller; + private IIndexerFactory _factory; + private CacheManager _cache; private int _tests; private int _writes; private bool _failTest; + private Func _testMamConnection; private readonly IndexerResourceMapper _mapper = new(); - private IndexerResource Request() => STJson.Deserialize(STJson.ToJson(_mapper.ToResource(_saved))); + private IndexerResource Request() => AsApiPayload(_mapper.ToResource(_saved)); + + private static IndexerResource AsApiPayload(IndexerResource resource) => STJson.Deserialize(STJson.ToJson(resource)); [SetUp] public void SetUp() @@ -49,7 +54,9 @@ public void SetUp() EnableRss = true, SupportsSearch = true, SupportsRss = true, Settings = new NewznabSettings { BaseUrl = "https://indexer.example", ApiKey = "saved-secret", EnableNarratorMetadata = true } }; - var factory = Proxy>((method, args) => + _testMamConnection = null; + _cache = new CacheManager(); + _factory = Proxy((method, args) => { switch (method.Name) { @@ -58,7 +65,25 @@ public void SetUp() case "SetProviderCharacteristics": return null; case "Test": _tests++; - ((IndexerDefinition)args[0]).SupportsNarratorMetadata = false; + var definition = (IndexerDefinition)args[0]; + definition.SupportsNarratorMetadata = false; + if (definition.Settings is MyAnonaMouseSettings && _testMamConnection != null) + { + return _testMamConnection(definition); + } + + if (definition.Settings is MyAnonaMouseSettings settings && !_failTest) + { + settings.MamId = "rotated-cookie"; + settings.UserId = "42"; + settings.UserClass = "VIP"; + settings.IsVip = true; + settings.UnsatisfiedCount = 3; + settings.UnsatisfiedLimit = 50; + settings.UnsatisfiedSnapshotUtc = DateTime.UtcNow; + settings.UnsatisfiedStatusRefreshedUtc = DateTime.UtcNow; + } + return _failTest ? new ValidationResult(new[] { new ValidationFailure("", "Connection unavailable") }) : new ValidationResult(); case "Create": _writes++; @@ -72,7 +97,18 @@ public void SetUp() default: throw new NotImplementedException(method.Name); } }); - _controller = new Controller(factory); + _controller = NewController(); + } + + private IndexerController NewController() => new(_factory, new DownloadClientExistsValidator(null), _cache); + + private MyAnonaMouseSettings UseMamIndexer() + { + var settings = new MyAnonaMouseSettings { BaseUrl = "https://mam.example", MamId = "saved-cookie" }; + _saved.Implementation = "MyAnonaMouse"; + _saved.ImplementationName = "MyAnonaMouse"; + _saved.Settings = settings; + return settings; } [TestCase(false)] @@ -177,5 +213,387 @@ public void new_enabled_indexer_is_tested_on_save() Assert.That(_tests, Is.EqualTo(1)); Assert.That(_writes, Is.EqualTo(1)); } + + [TestCase(false)] + [TestCase(true)] + public void mam_save_reuses_successful_test_for_the_same_connection(bool creating) + { + UseMamIndexer().UnsatisfiedStatusRefreshedUtc = DateTime.UtcNow.AddHours(-1); + var resource = Request(); + resource.Id = creating ? 0 : _saved.Id; + resource.Name = creating ? "New MAM" : _saved.Name; + resource.Fields.Single(field => field.Name == "mamId").Value = "new-cookie"; + var result = JObject.FromObject(_controller.Test(AsApiPayload(resource))); + Assert.That(result.ToString(), Does.Not.Contain("rotated-cookie")); + Assert.That(((MyAnonaMouseSettings)_saved.Settings).MamId, Is.EqualTo("saved-cookie")); + Assert.That(_writes, Is.Zero); + + resource.Fields.Single(field => field.Name == "unsatisfiedSlotReserve").Value = 2; + _failTest = true; + if (creating) + { + NewController().CreateProvider(AsApiPayload(resource)); + } + else + { + NewController().UpdateProvider(AsApiPayload(resource)); + } + + var stored = (MyAnonaMouseSettings)_saved.Settings; + Assert.Multiple(() => + { + Assert.That(_tests, Is.EqualTo(1)); + Assert.That(_writes, Is.EqualTo(1)); + Assert.That(stored.MamId, Is.EqualTo("rotated-cookie")); + Assert.That(stored.UserId, Is.EqualTo("42")); + Assert.That(stored.UnsatisfiedCount, Is.EqualTo(3)); + Assert.That(stored.UnsatisfiedSlotReserve, Is.EqualTo(2)); + }); + } + + [TestCase("mamId", "other-cookie")] + [TestCase("baseUrl", "https://other.example")] + [TestCase("mamSsl", false)] + [TestCase("proxyId", 5)] + public void mam_save_retests_if_the_connection_changes_after_a_successful_test(string field, object value) + { + UseMamIndexer(); + var resource = Request(); + resource.Fields.Single(item => item.Name == "mamId").Value = "new-cookie"; + _controller.Test(AsApiPayload(resource)); + + if (field == "proxyId") + { + resource.ProxyId = (int)value; + } + else + { + resource.Fields.Single(item => item.Name == field).Value = value; + } + + _failTest = true; + Assert.Throws(() => NewController().UpdateProvider(AsApiPayload(resource))); + Assert.That(_tests, Is.EqualTo(2)); + Assert.That(_writes, Is.Zero); + } + + [Test] + public void mam_unchanged_save_stores_a_newer_test_result_once() + { + var settings = UseMamIndexer(); + settings.UserClass = "User"; + settings.UnsatisfiedCount = 45; + settings.UnsatisfiedLimit = 50; + settings.UnsatisfiedSnapshotUtc = settings.UnsatisfiedStatusRefreshedUtc = DateTime.UtcNow.AddHours(-3); + var resource = Request(); + Assert.That(resource.Fields.Single(field => field.Name == "mamId").Value.ToString(), Is.EqualTo("********")); + + _controller.Test(AsApiPayload(resource)); + Assert.That(_writes, Is.Zero); + _failTest = true; + NewController().UpdateProvider(AsApiPayload(resource)); + + var stored = (MyAnonaMouseSettings)_saved.Settings; + Assert.Multiple(() => + { + Assert.That(_tests, Is.EqualTo(1)); + Assert.That(_writes, Is.EqualTo(1)); + Assert.That(stored.MamId, Is.EqualTo("rotated-cookie")); + Assert.That(stored.UserId, Is.EqualTo("42")); + Assert.That(stored.UserClass, Is.EqualTo("VIP")); + Assert.That(stored.IsVip, Is.True); + Assert.That(stored.UnsatisfiedCount, Is.EqualTo(3)); + Assert.That(stored.UnsatisfiedLimit, Is.EqualTo(50)); + Assert.That(stored.UnsatisfiedSnapshotUtc, Is.GreaterThan(settings.UnsatisfiedSnapshotUtc)); + Assert.That(stored.UnsatisfiedStatusRefreshedUtc, Is.GreaterThan(settings.UnsatisfiedStatusRefreshedUtc)); + }); + + NewController().UpdateProvider(AsApiPayload(resource)); + Assert.That(_tests, Is.EqualTo(1)); + Assert.That(_writes, Is.EqualTo(1)); + } + + [Test] + public void mam_disabled_save_keeps_a_passed_test_without_retesting() + { + UseMamIndexer(); + _saved.EnableRss = false; + var resource = Request(); + + _controller.Test(AsApiPayload(resource)); + NewController().UpdateProvider(AsApiPayload(resource)); + + var stored = (MyAnonaMouseSettings)_saved.Settings; + Assert.Multiple(() => + { + Assert.That(_tests, Is.EqualTo(1)); + Assert.That(_writes, Is.EqualTo(1)); + Assert.That(_saved.Enable, Is.False); + Assert.That(stored.MamId, Is.EqualTo("rotated-cookie")); + Assert.That(stored.UnsatisfiedCount, Is.EqualTo(3)); + Assert.That(stored.UnsatisfiedStatusRefreshedUtc, Is.Not.Null); + }); + } + + [TestCase(5)] + [TestCase(180)] + [TestCase(null)] + public void mam_save_can_enable_protection_without_testing(int? summaryAgeMinutes) + { + var settings = UseMamIndexer(); + settings.ProtectUnsatisfiedSlots = false; + if (summaryAgeMinutes is { } age) + { + settings.UnsatisfiedCount = 4; + settings.UnsatisfiedLimit = 50; + settings.UnsatisfiedSnapshotUtc = settings.UnsatisfiedStatusRefreshedUtc = DateTime.UtcNow.AddMinutes(-age); + } + + var resource = Request(); + resource.Fields.Single(field => field.Name == "protectUnsatisfiedSlots").Value = true; + + NewController().UpdateProvider(AsApiPayload(resource)); + + Assert.That(_tests, Is.Zero); + Assert.That(_writes, Is.EqualTo(1)); + Assert.That(((MyAnonaMouseSettings)_saved.Settings).ProtectUnsatisfiedSlots, Is.True); + } + + [TestCase("new-tested")] + [TestCase("edited-tested")] + [TestCase("priority-only")] + [TestCase("new-cookie-untested")] + [TestCase("reenable")] + [TestCase("summary-warning")] + public void mam_save_contacts_only_the_endpoints_needed_for_the_current_connection(string scenario) + { + UseMamIndexer(); + var requests = new List(); + var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + var summary = scenario == "summary-warning" + ? "not-json" + : $"{{\"uid\":42,\"classname\":\"User\",\"created\":{now},\"unsat\":{{\"count\":3,\"limit\":50}}}}"; + var client = Proxy((_, args) => + { + var request = (HttpRequest)args[0]; + var path = ((Uri)request.Url).AbsolutePath; + requests.Add(path); + Assert.That(request.Cookies["mam_id"], Is.EqualTo("new-cookie")); + var content = path == "/jsonLoad.php" ? summary : "{\"data\":[]}"; + return Task.FromResult(new HttpResponse(request, new HttpHeader { ContentType = "application/json" }, content, HttpStatusCode.OK)); + }); + var clientFactory = Proxy((_, _) => client); + var logger = LogManager.GetCurrentClassLogger(); + var indexer = new MyAnonaMouse(clientFactory, null, null, null, new MyAnonaMouseAccountSummaryThrottle(logger), logger); + _testMamConnection = definition => + { + indexer.Definition = definition; + return indexer.Test(); + }; + + _saved.EnableRss = scenario != "reenable"; + var resource = Request(); + if (scenario == "priority-only") + { + resource.Priority++; + } + else if (scenario == "reenable") + { + resource.EnableRss = true; + } + else + { + resource.Fields.Single(item => item.Name == "mamId").Value = "new-cookie"; + } + + if (scenario == "new-tested") + { + resource.Id = 0; + } + + if (scenario == "summary-warning") + { + resource.Fields.Single(item => item.Name == "protectUnsatisfiedSlots").Value = false; + } + + if (scenario is "new-tested" or "edited-tested" or "summary-warning") + { + _controller.Test(AsApiPayload(resource)); + Assert.That(requests, Is.EqualTo(new[] { "/tor/js/loadSearchJSONbasic.php", "/jsonLoad.php" })); + } + + if (resource.Id == 0) + { + NewController().CreateProvider(AsApiPayload(resource)); + } + else + { + NewController().UpdateProvider(AsApiPayload(resource)); + } + + var expected = scenario is "priority-only" or "reenable" + ? Array.Empty() + : new[] { "/tor/js/loadSearchJSONbasic.php", "/jsonLoad.php" }; + Assert.That(requests, Is.EqualTo(expected)); + Assert.That(_writes, Is.EqualTo(1)); + var stored = (MyAnonaMouseSettings)_saved.Settings; + if (scenario == "new-tested") + { + Assert.That(stored.UserId, Is.EqualTo("42")); + Assert.That(stored.UnsatisfiedCount, Is.EqualTo(3)); + Assert.That(stored.UnsatisfiedLimit, Is.EqualTo(50)); + Assert.That(stored.UnsatisfiedStatusRefreshedUtc, Is.Not.Null); + } + else if (scenario == "summary-warning") + { + Assert.That(stored.UnsatisfiedStatusRefreshedUtc, Is.Null); + } + } + + [TestCase(false)] + [TestCase(true)] + public void forced_cookie_update_preserves_mam_account_status(bool testedFirst) + { + var settings = UseMamIndexer(); + settings.UserId = "42"; + settings.IsVip = true; + settings.UnsatisfiedCount = 4; + settings.UnsatisfiedLimit = 50; + settings.UnsatisfiedSnapshotUtc = settings.UnsatisfiedStatusRefreshedUtc = + DateTimeOffset.FromUnixTimeSeconds(DateTimeOffset.UtcNow.ToUnixTimeSeconds()).UtcDateTime; + var resource = Request(); + if (testedFirst) + { + _controller.Test(AsApiPayload(resource)); + } + + resource.Fields.Single(field => field.Name == "mamId").Value = "mousetrap-cookie"; + + NewController().UpdateProvider(AsApiPayload(resource), forceSave: true); + + var stored = (MyAnonaMouseSettings)_saved.Settings; + Assert.Multiple(() => + { + Assert.That(_tests, Is.EqualTo(testedFirst ? 1 : 0)); + Assert.That(_writes, Is.EqualTo(1)); + Assert.That(stored.MamId, Is.EqualTo("mousetrap-cookie")); + Assert.That(stored.UserId, Is.EqualTo(settings.UserId)); + Assert.That(stored.IsVip, Is.True); + Assert.That(stored.UnsatisfiedCount, Is.EqualTo(settings.UnsatisfiedCount)); + Assert.That(stored.UnsatisfiedLimit, Is.EqualTo(settings.UnsatisfiedLimit)); + Assert.That(stored.UnsatisfiedSnapshotUtc, Is.EqualTo(settings.UnsatisfiedSnapshotUtc)); + Assert.That(stored.UnsatisfiedStatusRefreshedUtc, Is.EqualTo(settings.UnsatisfiedStatusRefreshedUtc)); + }); + } + + [TestCase(false)] + [TestCase(true)] + public void mam_save_keeps_the_newer_server_summary_when_only_local_settings_change(bool testedFirst) + { + var settings = UseMamIndexer(); + var resource = Request(); + if (testedFirst) + { + _controller.Test(resource); + } + + // The background refresh can complete after the user opens the modal. + if (!testedFirst) + { + settings.MamId = "background-cookie"; + } + settings.UserId = "42"; + settings.UserClass = "VIP"; + settings.IsVip = true; + settings.UnsatisfiedCount = 4; + settings.UnsatisfiedLimit = 50; + settings.UnsatisfiedSnapshotUtc = DateTime.UtcNow; + settings.UnsatisfiedStatusRefreshedUtc = DateTime.UtcNow.AddSeconds(1); + _failTest = true; + + Assert.That(resource.Fields.Any(field => field.Name == "isVip"), Is.False); + resource.Fields.Add(new Field { Name = "isVip", Value = false }); + resource.Fields.Single(field => field.Name == "manualGrabBuffer").Value = 2; + NewController().UpdateProvider(AsApiPayload(resource)); + var stored = (MyAnonaMouseSettings)_saved.Settings; + Assert.Multiple(() => + { + Assert.That(_tests, Is.EqualTo(testedFirst ? 1 : 0)); + Assert.That(_writes, Is.EqualTo(1)); + Assert.That(stored.MamId, Is.EqualTo(testedFirst ? "saved-cookie" : "background-cookie")); + Assert.That(stored.IsVip, Is.True); + Assert.That(stored.UserClass, Is.EqualTo("VIP")); + Assert.That(stored.UserId, Is.EqualTo("42")); + Assert.That(stored.UnsatisfiedCount, Is.EqualTo(4)); + Assert.That(stored.ManualGrabBuffer, Is.EqualTo(2)); + }); + } + + [Test] + public void mam_failed_test_does_not_authorize_save_with_changed_settings() + { + UseMamIndexer(); + var resource = Request(); + resource.Fields.Single(field => field.Name == "mamId").Value = "new-cookie"; + _controller.Test(AsApiPayload(resource)); + _failTest = true; + + Assert.Throws(() => NewController().Test(AsApiPayload(resource))); + Assert.Throws(() => NewController().UpdateProvider(AsApiPayload(resource))); + Assert.That(_tests, Is.EqualTo(3)); + Assert.That(_writes, Is.Zero); + } + + [Test] + public void mam_status_applies_and_copies_every_persisted_account_field() + { + var status = new MyAnonaMouseAccountStatus + { + UserId = "42", + UserClass = "VIP", + IsVip = true, + UnsatisfiedCount = 3, + UnsatisfiedLimit = 50, + SnapshotCreatedUtc = DateTime.UnixEpoch.AddMinutes(1), + RefreshedUtc = DateTime.UnixEpoch.AddMinutes(2), + RotatedMamId = "rotated-cookie" + }; + var expected = new Dictionary + { + [nameof(MyAnonaMouseSettings.UserId)] = status.UserId, + [nameof(MyAnonaMouseSettings.UserClass)] = status.UserClass, + [nameof(MyAnonaMouseSettings.IsVip)] = status.IsVip, + [nameof(MyAnonaMouseSettings.UnsatisfiedCount)] = status.UnsatisfiedCount, + [nameof(MyAnonaMouseSettings.UnsatisfiedLimit)] = status.UnsatisfiedLimit, + [nameof(MyAnonaMouseSettings.UnsatisfiedSnapshotUtc)] = status.SnapshotCreatedUtc, + [nameof(MyAnonaMouseSettings.UnsatisfiedStatusRefreshedUtc)] = status.RefreshedUtc + }; + var nonStatus = new[] + { + nameof(MyAnonaMouseSettings.SeedCriteria), + nameof(MyAnonaMouseSettings.RejectBlocklistedTorrentHashesWhileGrabbing) + }; + var properties = typeof(MyAnonaMouseSettings).GetProperties(); + var serverOnly = properties + .Where(property => property.SetMethod?.IsPublic == true && property.GetCustomAttribute() == null) + .Select(property => property.Name); + Assert.That(serverOnly.Except(expected.Keys.Concat(nonStatus)), Is.Empty, "Classify each server-only property."); + + var source = new MyAnonaMouseSettings { MamId = "current-cookie", ManualGrabBuffer = 2 }; + source.ApplyAccountStatus(status); + Assert.Multiple(() => + { + foreach (var property in properties.Where(property => expected.ContainsKey(property.Name))) + { + Assert.That(property.GetValue(source), Is.EqualTo(expected[property.Name]), property.Name); + } + + Assert.That(source.MamId, Is.EqualTo("current-cookie")); + }); + + var target = new MyAnonaMouseSettings { MamId = "old-cookie", ManualGrabBuffer = 2 }; + target.CopyAccountStatusFrom(source); + Assert.That(JToken.DeepEquals(JToken.Parse(STJson.ToJson(target)), JToken.Parse(STJson.ToJson(source))), Is.True); + } } } diff --git a/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseRequestGeneratorFixture.cs b/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseRequestGeneratorFixture.cs index 75cdc68db..9d83ac148 100644 --- a/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseRequestGeneratorFixture.cs +++ b/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseRequestGeneratorFixture.cs @@ -91,23 +91,27 @@ public void should_normalize_spacing_when_the_shared_search_keeps_a_punctuation_ Assert.That(GetRequestPayloadObject(chain, 1)["tor"]?["text"]?.Value(), Is.EqualTo("?! …")); } - [Test] - public void should_add_book_number_fallback_as_last_tier_for_interactive_search() + [TestCase("The Trouble With Peace, Book 2", "Trouble With Peace Book 2", "Trouble With Peace")] + [TestCase("Spellbook 2", "Spellbook 2", null)] + public void should_add_only_standalone_book_number_fallbacks(string title, string query, string fallback) { var generator = CreateGenerator(); var searchCriteria = new BookSearchCriteria { Author = new Author { Name = "Joe Abercrombie" }, - BookTitle = "The Trouble With Peace, Book 2", + BookTitle = title, InteractiveSearch = true }; var chain = generator.GetSearchRequests(searchCriteria); - Assert.That(chain.Tiers, Is.EqualTo(3)); - Assert.That(GetRequestPayload(chain, 0), Does.Contain("\"text\":\"Trouble With Peace Book 2 Joe Abercrombie\"")); - Assert.That(GetRequestPayload(chain, 1), Does.Contain("\"text\":\"Trouble With Peace Book 2\"")); - Assert.That(GetRequestPayload(chain, 2), Does.Contain("\"text\":\"Trouble With Peace\"")); + Assert.That(GetRequestPayloadObject(chain, 0)["tor"]?["text"]?.Value(), Is.EqualTo($"{query} Joe Abercrombie")); + Assert.That(GetRequestPayloadObject(chain, 1)["tor"]?["text"]?.Value(), Is.EqualTo(query)); + Assert.That(chain.Tiers, Is.EqualTo(fallback == null ? 2 : 3)); + if (fallback != null) + { + Assert.That(GetRequestPayloadObject(chain, 2)["tor"]?["text"]?.Value(), Is.EqualTo(fallback)); + } } [Test] diff --git a/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseSeedTimeFixture.cs b/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseSeedTimeFixture.cs index d8c18eae2..e7d057301 100644 --- a/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseSeedTimeFixture.cs +++ b/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseSeedTimeFixture.cs @@ -31,7 +31,7 @@ public void should_allow_seed_time_to_be_cleared_and_persist_as_null() public void default_definition_should_set_seed_time_hours_to_72() { var logger = LogManager.GetCurrentClassLogger(); - var indexer = new MyAnonaMouse(null, null, null, null, logger); + var indexer = new MyAnonaMouse(null, null, null, null, null, logger); var definition = (IndexerDefinition)indexer.DefaultDefinitions.Single(); var settings = (MyAnonaMouseSettings)definition.Settings; diff --git a/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseWedgeFixture.cs b/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseWedgeFixture.cs index 738fc848e..4d8b5ea03 100644 --- a/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseWedgeFixture.cs +++ b/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseWedgeFixture.cs @@ -19,6 +19,7 @@ using NzbDrone.Core.HealthCheck.Checks; using NzbDrone.Core.Indexers; using NzbDrone.Core.Indexers.MyAnonaMouse; +using NzbDrone.Core.Indexers.Newznab; using NzbDrone.Core.Localization; using NzbDrone.Core.Messaging.Events; using NzbDrone.Core.Parser; @@ -34,6 +35,20 @@ public class MyAnonaMouseWedgeFixture { private const string MinimalTorrent = "d8:announce14:http://tracker4:infod6:lengthi1e4:name1:x12:piece lengthi16384e6:pieces20:12345678901234567890ee"; + private sealed class ImmediateSummaryThrottle : IMyAnonaMouseAccountSummaryThrottle + { + public Task SendAsync(MamConnection connection, Func> send) => send(); + } + + private sealed class SummaryClock : TimeProvider + { + private long _ticks; + + public override long TimestampFrequency => TimeSpan.TicksPerSecond; + public override long GetTimestamp() => _ticks; + public void Advance(TimeSpan elapsed) => _ticks += elapsed.Ticks; + } + private class IndexerHttpClientProxy : DispatchProxy { public Queue> Responses { get; } = new Queue>(); @@ -68,8 +83,8 @@ protected override object Invoke(MethodInfo targetMethod, object[] args) private sealed class TestableMyAnonaMouse : MyAnonaMouse { - public TestableMyAnonaMouse(IIndexerHttpClientFactory httpClientFactory, Logger logger) - : base(httpClientFactory, null, null, null, logger) + public TestableMyAnonaMouse(IIndexerHttpClientFactory httpClientFactory, IMyAnonaMouseAccountSummaryThrottle throttle, Logger logger) + : base(httpClientFactory, null, null, null, throttle, logger) { } @@ -543,8 +558,10 @@ public void account_status_warning_should_identify_indexer_without_exposing_resp [TestCase("unreadable-private-content")] [TestCase("{\"uid\":42,\"created\":1785171600,\"unsat\":{\"count\":1,\"limit\":50}}")] [TestCase("{\"classname\":\"User\",\"created\":1785171600}")] + [TestCase("{\"classname\":\"User\",\"created\":1785171600,\"unsat\":{\"count\":1,\"limit\":0}}")] + [TestCase("{\"classname\":\"User\",\"unsat\":{\"count\":1,\"limit\":50}}")] [TestCase("{\"classname\":\"User\",\"created\":9223372036854775807,\"unsat\":{\"count\":1,\"limit\":50}}")] - [TestCase(null)] + [TestCase(null)] // HTTP 404 public void account_summary_health_warning_follows_refresh_results(string unreadableReply) { const string privateResponse = "fixture-private-response"; @@ -660,6 +677,28 @@ void Refresh() }); } + [Test] + public void account_summary_warning_should_clear_if_the_same_id_is_now_a_different_indexer_type() + { + var definition = new IndexerDefinition + { + Id = 9, + Name = "Fixture indexer", + EnableAutomaticSearch = true, + Settings = new MyAnonaMouseSettings() + }; + var check = new MyAnonaMouseAccountSummaryCheck( + Proxy((_, _) => new List { definition }), + Proxy((_, _) => new Dictionary { [definition.Id] = DateTime.UtcNow }), + Proxy((_, _) => "Unreadable summary for {0}")); + + Assert.That(check.Check().Type, Is.EqualTo(HealthCheckResult.Warning)); + + definition.Settings = new NewznabSettings(); + + Assert.That(check.Check().Type, Is.EqualTo(HealthCheckResult.Ok)); + } + [Test] public void unsatisfied_slot_protection_should_default_on_for_legacy_settings_json() { @@ -673,6 +712,163 @@ public void unsatisfied_slot_protection_should_default_on_for_legacy_settings_js }); } + [TestCase("timeout")] + [TestCase("http-403")] + [TestCase("malformed")] + [TestCase("stale")] + public void a_failed_manual_check_waits_then_fetches_a_new_summary(string failure) + { + var clock = new SummaryClock(); + var waits = new List(); + var throttle = CreateSummaryThrottle(clock, waits); + var client = CreateClient(request => ValidSummaryResponse(request)); + var clientState = (IndexerHttpClientProxy)(object)client; + clientState.Responses.Enqueue(request => failure switch + { + "timeout" => throw new TimeoutException(), + "http-403" => new HttpResponse(request, new HttpHeader(), "", HttpStatusCode.Forbidden), + "stale" => JsonResponse(request, "{\"uid\":42,\"classname\":\"User\",\"created\":1600000000,\"unsat\":{\"count\":3,\"limit\":50}}"), + _ => JsonResponse(request, "not-json") + }); + clientState.Responses.Enqueue(request => ValidSummaryResponse(request)); + var indexer = CreateTestIndexer(new MyAnonaMouseSettings { MamId = "fixture-token" }, client, throttle: throttle); + + Assert.That(indexer.Test().IsValid, Is.True); + clock.Advance(TimeSpan.FromHours(1)); + Assert.That(indexer.Test().IsValid, Is.False); + clock.Advance(TimeSpan.FromSeconds(18)); + if (failure == "stale") + { + Assert.That(indexer.Test().IsValid, Is.False); + Assert.That(waits, Is.Empty); + Assert.That(clientState.Requests, Has.Count.EqualTo(2)); + clock.Advance(TimeSpan.FromSeconds(42)); + } + + Assert.That(indexer.Test().IsValid, Is.True); + Assert.That(waits, Is.EqualTo(failure == "stale" ? Array.Empty() : new[] { TimeSpan.FromSeconds(42) })); + Assert.That(clientState.Requests, Has.Count.EqualTo(3)); + } + + [TestCase(true, ProviderMessageType.Info, "User Class: User")] + [TestCase(false, ProviderMessageType.Warning, "account status is unavailable or stale")] + public void indexer_factory_keeps_the_mam_test_message(bool validSummary, ProviderMessageType type, string message) + { + var logger = LogManager.GetCurrentClassLogger(); + var indexer = CreateTestIndexer(new MyAnonaMouseSettings { MamId = "fixture-token", ProtectUnsatisfiedSlots = false }, + CreateSummaryClient(validSummary ? "fresh" : "malformed")); + var definition = (IndexerDefinition)indexer.Definition; + definition.Id = 0; + definition.Implementation = nameof(TestableMyAnonaMouse); + var factory = new IndexerFactory(null, null, new[] { indexer }, Proxy((_, _) => indexer), null, logger); + + Assert.That(factory.Test(definition).IsValid, Is.True); + Assert.That(definition.Message?.Type, Is.EqualTo(type)); + Assert.That(definition.Message?.Message, Does.Contain(message)); + } + + [Test] + public void background_refresh_reuses_a_recent_success_without_changing_its_fetch_time() + { + var clock = new SummaryClock(); + var throttle = new MyAnonaMouseAccountSummaryThrottle(clock, _ => throw new InvalidOperationException("Unexpected wait")); + var client = CreateClient(request => + { + Assert.That(request.RateLimitKey, Is.EqualTo("9")); + Assert.That(request.AllowAutoRedirect, Is.False); + return ValidSummaryResponse(request, "mam_id=rotated-token; path=/"); + }); + var tested = new MyAnonaMouseSettings { MamId = "fixture-token" }; + Assert.That(CreateTestIndexer(tested, client, throttle: throttle).Test().IsValid, Is.True); + clock.Advance(TimeSpan.FromSeconds(18)); + var factory = DispatchProxy.Create(); + var factoryState = (IndexerFactoryProxy)(object)factory; + var stored = new MyAnonaMouseSettings { MamId = "fixture-token" }; + factoryState.Indexer = CreateIndexer(stored, client, throttle); + new MyAnonaMouseAccountStatusService(factory, Proxy((_, _) => null), LogManager.GetCurrentClassLogger()) + .Execute(new RefreshMyAnonaMouseAccountStatusCommand()); + + Assert.That(((IndexerHttpClientProxy)(object)client).Requests, Has.Count.EqualTo(1)); + Assert.That(stored.UnsatisfiedStatusRefreshedUtc, Is.EqualTo(tested.UnsatisfiedStatusRefreshedUtc)); + Assert.That(factoryState.PersistedMamIds, Is.EqualTo(new[] { "rotated-token" })); + } + + [TestCase("cookie")] + [TestCase("proxy")] + public async Task a_changed_connection_waits_then_fetches_an_independent_summary(string changedField) + { + var clock = new SummaryClock(); + var waits = new List(); + var throttle = CreateSummaryThrottle(clock, waits); + var client = CreateClient(request => ValidSummaryResponse(request)); + var clientState = (IndexerHttpClientProxy)(object)client; + clientState.Responses.Enqueue(request => + { + Assert.That(request.Cookies["mam_id"], Is.EqualTo(changedField == "cookie" ? "different-token" : "fixture-token")); + return ValidSummaryResponse(request); + }); + var first = CreateIndexer(new MyAnonaMouseSettings { MamId = "fixture-token" }, client, throttle); + await first.RefreshAccountStatus(); + clock.Advance(TimeSpan.FromSeconds(25)); + + var next = CreateIndexer(new MyAnonaMouseSettings { MamId = changedField == "cookie" ? "different-token" : "fixture-token" }, client, throttle); + ((IndexerDefinition)next.Definition).ProxyId = changedField == "proxy" ? 5 : null; + await next.RefreshAccountStatus(); + Assert.That(waits, Is.EqualTo(new[] { TimeSpan.FromSeconds(35) })); + Assert.That(clientState.Requests, Has.Count.EqualTo(2)); + } + + [Test] + public async Task refresh_with_the_issued_cookie_reuses_the_recent_reply() + { + var clock = new SummaryClock(); + var throttle = new MyAnonaMouseAccountSummaryThrottle(clock, _ => throw new InvalidOperationException("Unexpected wait")); + var client = CreateClient(request => + { + Assert.That(request.Cookies["mam_id"], Is.EqualTo("fixture-token")); + return ValidSummaryResponse(request, "mam_id=rotated-token; path=/"); + }); + var stored = new MyAnonaMouseSettings { MamId = "fixture-token" }; + var indexer = CreateIndexer(stored, client, throttle); + + var first = await indexer.RefreshAccountStatus(); + clock.Advance(TimeSpan.FromSeconds(20)); + Assert.That(stored.MamId, Is.EqualTo("rotated-token")); + var second = await indexer.RefreshAccountStatus(); + + Assert.That(second, Is.SameAs(first)); + Assert.That(stored.UnsatisfiedStatusRefreshedUtc, Is.EqualTo(first.RefreshedUtc)); + Assert.That(((IndexerHttpClientProxy)(object)client).Requests, Has.Count.EqualTo(1)); + } + + [Test] + public async Task the_cooldown_runs_from_completion_of_a_slow_request() + { + var clock = new SummaryClock(); + var waits = new List(); + var throttle = CreateSummaryThrottle(clock, waits); + var response = new TaskCompletionSource(); + var connection = new MamConnection("https://mam.example", "fixture-token", true, null); + var first = throttle.SendAsync(connection, () => response.Task); + clock.Advance(TimeSpan.FromSeconds(75)); + var second = throttle.SendAsync(connection with { MamId = "other-token" }, () => response.Task); + Assert.That(second.IsCompleted, Is.False); + response.SetResult(new MyAnonaMouseAccountStatus()); + await first; + await second; + Assert.That(waits, Is.EqualTo(new[] { TimeSpan.FromMinutes(1) })); + } + + private static MyAnonaMouseAccountSummaryThrottle CreateSummaryThrottle(SummaryClock clock, List waits) + { + return new MyAnonaMouseAccountSummaryThrottle(clock, remaining => + { + waits.Add(remaining); + clock.Advance(remaining); + return Task.CompletedTask; + }); + } + [Test] public void unsatisfied_slot_protection_should_preserve_an_explicit_advanced_opt_out() { @@ -686,12 +882,12 @@ internal static MyAnonaMouse CreateIndexerWithAccountSummary(MyAnonaMouseSetting return CreateIndexer(settings, CreateClient(request => ValidSummaryResponse(request, setCookie))); } - private static MyAnonaMouse CreateIndexer(MyAnonaMouseSettings settings, IIndexerHttpClient client = null) + private static MyAnonaMouse CreateIndexer(MyAnonaMouseSettings settings, IIndexerHttpClient client = null, IMyAnonaMouseAccountSummaryThrottle throttle = null) { var factory = DispatchProxy.Create(); ((IndexerHttpClientFactoryProxy)(object)factory).Client = client; - return new MyAnonaMouse(factory, null, null, null, LogManager.GetCurrentClassLogger()) + return new MyAnonaMouse(factory, null, null, null, throttle ?? new ImmediateSummaryThrottle(), LogManager.GetCurrentClassLogger()) { Definition = new IndexerDefinition { @@ -703,11 +899,11 @@ private static MyAnonaMouse CreateIndexer(MyAnonaMouseSettings settings, IIndexe }; } - private static TestableMyAnonaMouse CreateTestIndexer(MyAnonaMouseSettings settings, IIndexerHttpClient client, Logger logger = null) + private static TestableMyAnonaMouse CreateTestIndexer(MyAnonaMouseSettings settings, IIndexerHttpClient client, Logger logger = null, IMyAnonaMouseAccountSummaryThrottle throttle = null) { var factory = DispatchProxy.Create(); ((IndexerHttpClientFactoryProxy)(object)factory).Client = client; - return new TestableMyAnonaMouse(factory, logger ?? LogManager.GetCurrentClassLogger()) + return new TestableMyAnonaMouse(factory, throttle ?? new ImmediateSummaryThrottle(), logger ?? LogManager.GetCurrentClassLogger()) { Definition = new IndexerDefinition { diff --git a/src/NzbDrone.Core/Indexers/IndexerFactory.cs b/src/NzbDrone.Core/Indexers/IndexerFactory.cs index 5cc2ed2ad..fa393696a 100644 --- a/src/NzbDrone.Core/Indexers/IndexerFactory.cs +++ b/src/NzbDrone.Core/Indexers/IndexerFactory.cs @@ -102,7 +102,9 @@ private IEnumerable FilterBlockedIndexers(IEnumerable indexe public override ValidationResult Test(IndexerDefinition definition) { var result = base.Test(definition); + var testMessage = definition.Message; SetProviderCharacteristics(definition); + definition.Message = testMessage; // Keep the message the Test set. var success = result == null || result.IsValid; diff --git a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MamConnection.cs b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MamConnection.cs new file mode 100644 index 000000000..c1123413c --- /dev/null +++ b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MamConnection.cs @@ -0,0 +1,12 @@ +namespace NzbDrone.Core.Indexers.MyAnonaMouse +{ + public sealed record MamConnection(string BaseUrl, string MamId, bool MamSsl, int? ProxyId) + { + public static MamConnection For(IndexerDefinition definition) => + definition?.Settings is MyAnonaMouseSettings settings + ? new MamConnection(settings.BaseUrl?.TrimEnd('/'), settings.MamId, settings.MamSsl, definition.ProxyId) + : null; + + public override string ToString() => BaseUrl; + } +} diff --git a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MamUnsatisfiedSlotGuard.cs b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MamUnsatisfiedSlotGuard.cs index f775e8e6e..40804216a 100644 --- a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MamUnsatisfiedSlotGuard.cs +++ b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MamUnsatisfiedSlotGuard.cs @@ -37,7 +37,7 @@ public static MamUnsatisfiedSlotAvailability Reject(string reason) public class MamUnsatisfiedSlotGuard : IMamUnsatisfiedSlotGuard { - // Covers delayed accounting and clock skew. Revisit 5 minutes after more timing tests. + // Covers MAM's accounting lag and clock skew. I may drop this to 5 minutes after more testing. internal static readonly TimeSpan SummaryAccountingLag = TimeSpan.FromMinutes(10); private static readonly TimeSpan MaximumStatusAge = TimeSpan.FromHours(2); @@ -107,7 +107,7 @@ private MamUnsatisfiedSlotAvailability Evaluate(RemoteBook remoteBook, bool rese var now = DateTime.UtcNow; if (!HasFreshStatus(settings, now)) { - return MamUnsatisfiedSlotAvailability.Reject("MAM safety pause: the unsatisfied-slot status is unavailable or stale; test the indexer and try again"); + return MamUnsatisfiedSlotAvailability.Reject("MAM safety pause: the unsatisfied-slot status is unavailable or stale. Chaptarr rechecks every hour; to recheck now, test the indexer and save it."); } // MAM's count at the last check plus the other torrents grabbed on that account since then. diff --git a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouse.cs b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouse.cs index d2f9413e1..45f673eb8 100644 --- a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouse.cs +++ b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouse.cs @@ -17,6 +17,8 @@ namespace NzbDrone.Core.Indexers.MyAnonaMouse { public class MyAnonaMouse : HttpIndexerBase { + private readonly IMyAnonaMouseAccountSummaryThrottle _accountSummaryThrottle; + public override string Name => "MyAnonaMouse"; public override DownloadProtocol Protocol => DownloadProtocol.Torrent; @@ -24,9 +26,11 @@ public class MyAnonaMouse : HttpIndexerBase public override bool SupportsSearch => true; public override int PageSize => 100; - public MyAnonaMouse(IIndexerHttpClientFactory httpClientFactory, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, Logger logger) + public MyAnonaMouse(IIndexerHttpClientFactory httpClientFactory, IIndexerStatusService indexerStatusService, IConfigService configService, IParsingService parsingService, + IMyAnonaMouseAccountSummaryThrottle accountSummaryThrottle, Logger logger) : base(httpClientFactory, indexerStatusService, configService, parsingService, logger) { + _accountSummaryThrottle = accountSummaryThrottle; } public override IEnumerable DefaultDefinitions @@ -179,7 +183,7 @@ protected override async Task TestConnection() _logger.Trace("MAM_TEST_SUCCESS: JSON API test successful, found {0} results", releases.Count); - // The test result must not present cached counts as if this refresh verified them. + // The test result must not present previously stored counts as verified. try { await RefreshAccountStatus(); @@ -235,32 +239,35 @@ protected override async Task TestConnection() } } - // Requests always send Settings.MamId, so adopt MAM's rotated cookie or the original expires after - // ~30 days. MyAnonaMouseAccountStatusService saves Settings after each successful refresh. - private void PersistRefreshedMamId(HttpResponse response) + public async Task RefreshAccountStatus() { - if (!response.GetCookies().TryGetValue("mam_id", out var refreshedMamId) || - string.IsNullOrWhiteSpace(refreshedMamId) || - string.Equals(refreshedMamId, Settings.MamId, StringComparison.Ordinal)) + var connection = MamConnection.For((IndexerDefinition)Definition); + var status = await _accountSummaryThrottle.SendAsync(connection, () => FetchAccountStatus(connection)); + + Settings.ApplyAccountStatus(status); + + // Requests send the configured cookie, so adopt MAM's rotation before the original expires. + if (!string.IsNullOrWhiteSpace(status.RotatedMamId) && Settings.MamId != status.RotatedMamId) { - return; + _logger.Debug("MAM issued a refreshed mam_id for indexer '{0}'", Definition?.Name); + Settings.MamId = status.RotatedMamId; } - _logger.Debug("MAM issued a refreshed mam_id for indexer '{0}'", Definition?.Name); - Settings.MamId = refreshedMamId; + _logger.Debug("MAM account status detected: {0} (VIP: {1}), unsatisfied {2}/{3}", status.UserClass, status.IsVip, status.UnsatisfiedCount, status.UnsatisfiedLimit); + return status; } - public async Task RefreshAccountStatus() + private async Task FetchAccountStatus(MamConnection connection) { - var request = new HttpRequestBuilder($"{Settings.BaseUrl.TrimEnd('/')}/jsonLoad.php?snatch_summary&pretty") + var request = new HttpRequestBuilder($"{connection.BaseUrl}/jsonLoad.php?snatch_summary&pretty") .Accept(HttpAccept.Json) .SetHeader("User-Agent", $"{BuildInfo.AppName}/{BuildInfo.Version}") .Build(); request.SuppressHttpErrorStatusCodes = new[] { HttpStatusCode.NotFound }; request.RateLimitKey = Definition?.Id > 0 ? Definition.Id.ToString() : null; - request.Cookies["mam_id"] = Settings.MamId; - if (Settings.MamSsl) + request.Cookies["mam_id"] = connection.MamId; + if (connection.MamSsl) { request.Cookies["mam_ssl"] = "1"; } @@ -312,32 +319,22 @@ public async Task RefreshAccountStatus() throw new MyAnonaMouseAccountSummaryException("MAM user data response included an invalid summary timestamp"); } - var refreshedUtc = DateTime.UtcNow; - var isVip = IsVipClass(className); if (string.IsNullOrWhiteSpace(userId)) { _logger.Debug("MAM account response for indexer '{0}' had no user ID, so other MAM indexers' grabs count toward its limit", Definition?.Name); } - Settings.UserId = userId; - Settings.UserClass = className; - Settings.IsVip = isVip; - Settings.UnsatisfiedCount = userData.Unsatisfied.Count; - Settings.UnsatisfiedLimit = userData.Unsatisfied.Limit; - Settings.UnsatisfiedSnapshotUtc = snapshotCreatedUtc; - Settings.UnsatisfiedStatusRefreshedUtc = refreshedUtc; - PersistRefreshedMamId(response); - - _logger.Debug("MAM account status detected: {0} (VIP: {1}), unsatisfied {2}/{3}", className, isVip, userData.Unsatisfied.Count, userData.Unsatisfied.Limit); - + response.GetCookies().TryGetValue("mam_id", out var rotatedMamId); return new MyAnonaMouseAccountStatus { + UserId = userId, UserClass = className, - IsVip = isVip, + IsVip = IsVipClass(className), UnsatisfiedCount = userData.Unsatisfied.Count, UnsatisfiedLimit = userData.Unsatisfied.Limit, SnapshotCreatedUtc = snapshotCreatedUtc, - RefreshedUtc = refreshedUtc + RefreshedUtc = DateTime.UtcNow, + RotatedMamId = rotatedMamId }; } @@ -396,12 +393,14 @@ private static bool IsTorrentResponse(HttpResponse response) public class MyAnonaMouseAccountStatus { - public string UserClass { get; set; } - public bool IsVip { get; set; } - public int UnsatisfiedCount { get; set; } - public int UnsatisfiedLimit { get; set; } - public DateTime SnapshotCreatedUtc { get; set; } - public DateTime RefreshedUtc { get; set; } + internal string UserId { get; init; } + internal string RotatedMamId { get; init; } + public string UserClass { get; init; } + public bool IsVip { get; init; } + public int UnsatisfiedCount { get; init; } + public int UnsatisfiedLimit { get; init; } + public DateTime SnapshotCreatedUtc { get; init; } + public DateTime RefreshedUtc { get; init; } } public class MyAnonaMouseUserDataResponse diff --git a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseAccountSummaryThrottle.cs b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseAccountSummaryThrottle.cs new file mode 100644 index 000000000..f63270309 --- /dev/null +++ b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseAccountSummaryThrottle.cs @@ -0,0 +1,81 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using NLog; + +namespace NzbDrone.Core.Indexers.MyAnonaMouse +{ + public interface IMyAnonaMouseAccountSummaryThrottle + { + Task SendAsync(MamConnection connection, Func> send); + } + + public class MyAnonaMouseAccountSummaryThrottle : IMyAnonaMouseAccountSummaryThrottle + { + private static readonly TimeSpan Cooldown = TimeSpan.FromMinutes(1); + + private readonly SemaphoreSlim _gate = new(1, 1); + private readonly TimeProvider _clock; + private readonly Func _delay; + private readonly Logger _logger; + private long? _lastAttempt; + private MamConnection _lastConnection; + private MyAnonaMouseAccountStatus _lastStatus; + + public MyAnonaMouseAccountSummaryThrottle(Logger logger) + : this(TimeProvider.System, Task.Delay, logger) + { + } + + internal MyAnonaMouseAccountSummaryThrottle(TimeProvider clock, Func delay, Logger logger = null) + { + _clock = clock; + _delay = delay; + _logger = logger ?? LogManager.GetCurrentClassLogger(); + } + + public async Task SendAsync(MamConnection connection, Func> send) + { + await _gate.WaitAsync(); + try + { + while (_lastAttempt is { } lastAttempt) + { + var remaining = Cooldown - _clock.GetElapsedTime(lastAttempt); + if (remaining <= TimeSpan.Zero) + { + break; + } + + if (_lastStatus != null && + (connection == _lastConnection || + (!string.IsNullOrWhiteSpace(_lastStatus.RotatedMamId) && + connection == _lastConnection with { MamId = _lastStatus.RotatedMamId }))) + { + return _lastStatus; + } + + _logger.Debug("Waiting {0}s for MyAnonaMouse's one-a-minute account check", Math.Ceiling(remaining.TotalSeconds)); + await _delay(remaining); + } + + _lastConnection = connection; + _lastStatus = null; + try + { + _lastStatus = await send(); + return _lastStatus; + } + finally + { + // Measure from completion so time spent reaching MAM cannot shorten the gap. + _lastAttempt = _clock.GetTimestamp(); + } + } + finally + { + _gate.Release(); + } + } + } +} diff --git a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseRequestGenerator.cs b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseRequestGenerator.cs index 0dd53a376..7357d2043 100644 --- a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseRequestGenerator.cs +++ b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseRequestGenerator.cs @@ -20,7 +20,7 @@ public class MyAnonaMouseRequestGenerator : IIndexerRequestGenerator private const int RecentPageSize = 500; private const int SearchPageSize = 100; private const int SearchMaxPages = 10; - private static readonly Regex BookNumberSuffixRegex = new Regex(@"\s*book\s+\d+\s*$", RegexOptions.IgnoreCase | RegexOptions.Compiled); + private static readonly Regex BookNumberSuffixRegex = new Regex(@"\s*\bbook\s+\d+\s*$", RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly Regex MultiWhitespaceRegex = new Regex(@"\s{2,}", RegexOptions.Compiled); public MyAnonaMouseSettings Settings { get; set; } diff --git a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseSettings.cs b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseSettings.cs index 341950371..44b508f04 100644 --- a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseSettings.cs +++ b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseSettings.cs @@ -83,7 +83,6 @@ public int UseFreeleechWedge [FieldDefinition(9, Type = FieldType.Textbox, Label = "MAM User Class", HelpText = "Detected on connection test", Hidden = HiddenType.Hidden)] public string UserClass { get; set; } - [FieldDefinition(10, Type = FieldType.Checkbox, Label = "VIP Member", HelpText = "Detected on connection test", Hidden = HiddenType.Hidden)] public bool IsVip { get; set; } [FieldDefinition(11, Type = FieldType.Checkbox, Label = "Protect Unsatisfied Slots", HelpText = "Pause MAM grabs before your unsatisfied-torrent limit is reached. Disabling this can trigger MAM's 24-hour download suspension.", Advanced = true)] @@ -105,6 +104,30 @@ public int UseFreeleechWedge public DateTime? UnsatisfiedSnapshotUtc { get; set; } public DateTime? UnsatisfiedStatusRefreshedUtc { get; set; } + public void CopyAccountStatusFrom(MyAnonaMouseSettings source) + { + // MAM can issue a new cookie with the account status. + MamId = source.MamId; + UserId = source.UserId; + UserClass = source.UserClass; + IsVip = source.IsVip; + UnsatisfiedCount = source.UnsatisfiedCount; + UnsatisfiedLimit = source.UnsatisfiedLimit; + UnsatisfiedSnapshotUtc = source.UnsatisfiedSnapshotUtc; + UnsatisfiedStatusRefreshedUtc = source.UnsatisfiedStatusRefreshedUtc; + } + + public void ApplyAccountStatus(MyAnonaMouseAccountStatus status) + { + UserId = status.UserId; + UserClass = status.UserClass; + IsVip = status.IsVip; + UnsatisfiedCount = status.UnsatisfiedCount; + UnsatisfiedLimit = status.UnsatisfiedLimit; + UnsatisfiedSnapshotUtc = status.SnapshotCreatedUtc; + UnsatisfiedStatusRefreshedUtc = status.RefreshedUtc; + } + // Required by ITorrentIndexerSettings but hidden from UI public SeedCriteriaSettings SeedCriteria { From 3ac6404999c8ddbe9db33f4e64fdaaa890130d18 Mon Sep 17 00:00:00 2001 From: robertlordhood <204023072+robertlordhood@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:36:13 +0000 Subject: [PATCH 5/6] test(MyAnonaMouse): prove a cross-indexer grab counts once --- .../Indexers/MamUnsatisfiedSlotGuardFixture.cs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/Chaptarr.Core.Test/Indexers/MamUnsatisfiedSlotGuardFixture.cs b/src/Chaptarr.Core.Test/Indexers/MamUnsatisfiedSlotGuardFixture.cs index c1a39819d..02321a7cd 100644 --- a/src/Chaptarr.Core.Test/Indexers/MamUnsatisfiedSlotGuardFixture.cs +++ b/src/Chaptarr.Core.Test/Indexers/MamUnsatisfiedSlotGuardFixture.cs @@ -212,8 +212,8 @@ public void a_retry_after_a_check_counts_until_the_next_check() [Test] public void a_torrent_grabbed_through_two_indexers_should_count_once() { - var first = FreshSettings(count: 3, limit: 50, safetyReserve: 45); - var second = FreshSettings(count: 3, limit: 50, safetyReserve: 45); + var first = FreshSettings(count: 3, limit: 50, safetyReserve: 46); + var second = FreshSettings(count: 3, limit: 50, safetyReserve: 46); var repository = CreateRepository(out var state); var guard = CreateGuard(CreateFactory(Definition(first), Definition(second, 10, "MAM ebooks")), repository); @@ -223,7 +223,11 @@ public void a_torrent_grabbed_through_two_indexers_should_count_once() var next = guard.Check(Release("100")); - Assert.That(next.Accepted, Is.True); + Assert.Multiple(() => + { + Assert.That(next.Accepted, Is.False); + Assert.That(next.Reason, Does.Contain("4 of 50")); + }); } [Test] From 87c33fbb3ec6465738925c85427f8009db7e326a Mon Sep 17 00:00:00 2001 From: robertlordhood <204023072+robertlordhood@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:36:14 +0000 Subject: [PATCH 6/6] fix(MyAnonaMouse): keep user edits when the hourly check saves The hourly account check saved the indexer it loaded before asking MAM, so any change saved while it waited was put back. It now re-reads the indexer after MAM answers, applies the account fields, and saves only the settings column. A renewed cookie is taken only while the stored cookie is still the one that was sent. --- .../Indexers/IndexerSettingsTestFixture.cs | 2 +- .../Indexers/MyAnonaMouseWedgeFixture.cs | 175 ++++++++++++++++-- .../Indexers/IndexerRepository.cs | 6 + .../Indexers/MyAnonaMouse/MyAnonaMouse.cs | 13 +- .../MyAnonaMouseAccountStatusService.cs | 39 ++-- .../MyAnonaMouse/MyAnonaMouseSettings.cs | 12 +- 6 files changed, 203 insertions(+), 44 deletions(-) diff --git a/src/Chaptarr.Core.Test/Indexers/IndexerSettingsTestFixture.cs b/src/Chaptarr.Core.Test/Indexers/IndexerSettingsTestFixture.cs index c310ba714..8a7cdb14a 100644 --- a/src/Chaptarr.Core.Test/Indexers/IndexerSettingsTestFixture.cs +++ b/src/Chaptarr.Core.Test/Indexers/IndexerSettingsTestFixture.cs @@ -580,7 +580,7 @@ public void mam_status_applies_and_copies_every_persisted_account_field() Assert.That(serverOnly.Except(expected.Keys.Concat(nonStatus)), Is.Empty, "Classify each server-only property."); var source = new MyAnonaMouseSettings { MamId = "current-cookie", ManualGrabBuffer = 2 }; - source.ApplyAccountStatus(status); + source.ApplyAccountStatus(status, "superseded-cookie"); Assert.Multiple(() => { foreach (var property in properties.Where(property => expected.ContainsKey(property.Name))) diff --git a/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseWedgeFixture.cs b/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseWedgeFixture.cs index 4d8b5ea03..9c1cdbff6 100644 --- a/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseWedgeFixture.cs +++ b/src/Chaptarr.Core.Test/Indexers/MyAnonaMouseWedgeFixture.cs @@ -5,6 +5,7 @@ using System.Reflection; using System.Text; using System.Threading.Tasks; +using Chaptarr.Core.Test.Common; using Chaptarr.Http.ClientSchema; using Newtonsoft.Json; using NLog; @@ -98,6 +99,14 @@ private class IndexerFactoryProxy : DispatchProxy { public IIndexer Indexer { get; set; } public List PersistedMamIds { get; } = new List(); + public IIndexerRepository Repository { get; set; } + + public IIndexerRepository AccountStatusRepository() => Proxy((_, args) => + { + var settings = (MyAnonaMouseSettings)((IndexerDefinition)args[0]).Settings; + PersistedMamIds.Add(settings.MamId); + return null; + }); protected override object Invoke(MethodInfo targetMethod, object[] args) { @@ -107,9 +116,8 @@ protected override object Invoke(MethodInfo targetMethod, object[] args) return new List { Indexer }; case nameof(IIndexerFactory.All): return new List { (IndexerDefinition)Indexer.Definition }; - case nameof(IIndexerFactory.Update): - PersistedMamIds.Add(((MyAnonaMouseSettings)((IndexerDefinition)args[0]).Settings).MamId); - return null; + case nameof(IIndexerFactory.Find): + return Repository == null ? (IndexerDefinition)Indexer.Definition : Repository.Find((int)args[0]); default: throw new NotImplementedException(targetMethod?.Name); } @@ -387,18 +395,146 @@ public async Task account_status_should_send_a_rotated_mam_id_on_the_next_reques }); } - [Test] - public void account_status_refresh_should_persist_a_rotated_mam_id() + [TestCase(false, "unchanged")] + [TestCase(true, "unchanged")] + [TestCase(false, "no-renewal")] + [TestCase(true, "no-renewal")] + [TestCase(false, "edited")] + [TestCase(true, "edited")] + [TestCase(false, "deleted")] + [TestCase(true, "deleted")] + [TestCase(false, "replaced")] + [TestCase(true, "replaced")] + public void account_status_refresh_should_only_update_mam_fields_on_the_current_indexer(bool postgres, string scenario) { - var indexer = CreateIndexerWithAccountSummary(new MyAnonaMouseSettings { MamId = "original-token" }, "mam_id=rotated-token; path=/"); - var factory = DispatchProxy.Create(); - var factoryState = (IndexerFactoryProxy)(object)factory; - factoryState.Indexer = indexer; + DualDatabaseFixture.Run(postgres, database => + { + var events = Proxy((_, _) => null); + var repository = new IndexerRepository(database, events); + var noRenewal = scenario == "no-renewal"; + var summaryCreated = DateTimeOffset.UtcNow.AddMinutes(-1).ToUnixTimeSeconds(); + var snapshotUtc = DateTimeOffset.FromUnixTimeSeconds(summaryCreated).UtcDateTime; + var previousRefreshUtc = snapshotUtc.AddHours(-1); + var initialSettings = new MyAnonaMouseSettings { MamId = "original-token", SeedTimeHours = 10 }; + if (noRenewal) + { + initialSettings.UserId = "42"; + initialSettings.UserClass = "User"; + initialSettings.UnsatisfiedCount = 3; + initialSettings.UnsatisfiedLimit = 50; + initialSettings.UnsatisfiedSnapshotUtc = snapshotUtc; + initialSettings.UnsatisfiedStatusRefreshedUtc = previousRefreshUtc; + } - new MyAnonaMouseAccountStatusService(factory, Proxy((_, _) => null), LogManager.GetCurrentClassLogger()) - .Execute(new RefreshMyAnonaMouseAccountStatusCommand()); + var definition = repository.Insert(new IndexerDefinition + { + Name = "Fixture MAM", + Implementation = nameof(MyAnonaMouse), + EnableAutomaticSearch = true, + ProxyId = 4, + Priority = 20, + Settings = initialSettings + }); + string sentMamId = null; + var client = CreateClient(request => + { + sentMamId = request.Cookies["mam_id"]; + if (scenario == "deleted") + { + repository.Delete(definition.Id); + } + else if (scenario is "edited" or "replaced") + { + var current = repository.Get(definition.Id); + if (scenario == "replaced") + { + current.Implementation = nameof(Newznab); + current.Settings = new NewznabSettings { BaseUrl = "https://replacement.invalid" }; + } + else + { + current.ProxyId = 9; + current.Priority = 10; + var settings = (MyAnonaMouseSettings)current.Settings; + settings.SeedTimeHours = 5; + settings.MamId = "user-pasted-token"; + } + + repository.Update(current); + } + + var setCookie = noRenewal ? null : "mam_id=rotated-token; path=/"; + return ValidSummaryResponse(request, setCookie, summaryCreated); + }); + var indexer = CreateIndexer((MyAnonaMouseSettings)definition.Settings, client); + indexer.Definition = definition; + var factory = DispatchProxy.Create(); + var factoryState = (IndexerFactoryProxy)(object)factory; + factoryState.Indexer = indexer; + factoryState.Repository = repository; + var messages = new MemoryTarget { Layout = "${level}|${message}" }; + var configuration = new LoggingConfiguration(); + configuration.AddRule(LogLevel.Debug, LogLevel.Fatal, messages); + using var logs = new LogFactory { Configuration = configuration }; + + new MyAnonaMouseAccountStatusService(factory, repository, events, logs.GetLogger("AccountStatusWrite")) + .Execute(new RefreshMyAnonaMouseAccountStatusCommand()); - Assert.That(factoryState.PersistedMamIds, Is.EqualTo(new[] { "rotated-token" })); + Assert.That(sentMamId, Is.EqualTo("original-token")); + var saved = repository.Find(definition.Id); + if (scenario is "deleted" or "replaced") + { + Assert.That(messages.Logs, Has.Some.Contains("because its configuration was removed or replaced")); + if (scenario == "deleted") + { + Assert.That(saved, Is.Null); + } + else + { + Assert.That(((NewznabSettings)saved.Settings).BaseUrl, Is.EqualTo("https://replacement.invalid")); + } + + return; + } + + var edited = scenario == "edited"; + var expectedMamId = scenario switch + { + "edited" => "user-pasted-token", + "no-renewal" => "original-token", + _ => "rotated-token" + }; + var settingsAfterRefresh = (MyAnonaMouseSettings)saved.Settings; + Assert.Multiple(() => + { + Assert.That(saved.ProxyId, Is.EqualTo(edited ? 9 : 4)); + Assert.That(saved.Priority, Is.EqualTo(edited ? 10 : 20)); + Assert.That(settingsAfterRefresh.SeedTimeHours, Is.EqualTo(edited ? 5 : 10)); + Assert.That(settingsAfterRefresh.MamId, Is.EqualTo(expectedMamId)); + Assert.That(settingsAfterRefresh.UserId, Is.EqualTo("42")); + Assert.That(settingsAfterRefresh.UnsatisfiedCount, Is.EqualTo(3)); + Assert.That(settingsAfterRefresh.UnsatisfiedLimit, Is.EqualTo(50)); + Assert.That(settingsAfterRefresh.UnsatisfiedSnapshotUtc, Is.EqualTo(snapshotUtc)); + Assert.That(settingsAfterRefresh.UnsatisfiedStatusRefreshedUtc, Is.GreaterThan(previousRefreshUtc)); + if (noRenewal) + { + Assert.That(messages.Logs, Has.None.Contains("Updated MAM account status")); + } + else + { + Assert.That(messages.Logs, Has.Some.Contains("Info|Updated MAM account status")); + } + + if (scenario == "unchanged") + { + Assert.That(messages.Logs, Has.Some.Contains("Debug|MAM issued a refreshed mam_id for indexer")); + } + else + { + Assert.That(messages.Logs, Has.None.Contains("MAM issued a refreshed mam_id")); + } + }); + }); } [TestCase(null)] @@ -433,7 +569,7 @@ public void failed_account_status_refresh_should_not_persist_a_rotated_mam_id(st var factoryState = (IndexerFactoryProxy)(object)factory; factoryState.Indexer = indexer; - new MyAnonaMouseAccountStatusService(factory, Proxy((_, _) => null), LogManager.GetCurrentClassLogger()) + new MyAnonaMouseAccountStatusService(factory, factoryState.AccountStatusRepository(), Proxy((_, _) => null), LogManager.GetCurrentClassLogger()) .Execute(new RefreshMyAnonaMouseAccountStatusCommand()); Assert.That(factoryState.PersistedMamIds, Is.Empty); @@ -535,8 +671,9 @@ public void account_status_warning_should_identify_indexer_without_exposing_resp if (background) { var factory = DispatchProxy.Create(); - ((IndexerFactoryProxy)(object)factory).Indexer = indexer; - new MyAnonaMouseAccountStatusService(factory, Proxy((_, _) => null), logger) + var factoryState = (IndexerFactoryProxy)(object)factory; + factoryState.Indexer = indexer; + new MyAnonaMouseAccountStatusService(factory, factoryState.AccountStatusRepository(), Proxy((_, _) => null), logger) .Execute(new RefreshMyAnonaMouseAccountStatusCommand()); } else @@ -612,7 +749,7 @@ HttpResponse UnreadableResponse(HttpRequest request) return null; }); - refresh = new MyAnonaMouseAccountStatusService(factory, events, logger); + refresh = new MyAnonaMouseAccountStatusService(factory, factoryState.AccountStatusRepository(), events, logger); var cache = new CacheManager(); var localization = new LocalizationService( Proxy((_, _) => (int)NzbDrone.Core.Languages.Language.English), @@ -785,7 +922,7 @@ public void background_refresh_reuses_a_recent_success_without_changing_its_fetc var factoryState = (IndexerFactoryProxy)(object)factory; var stored = new MyAnonaMouseSettings { MamId = "fixture-token" }; factoryState.Indexer = CreateIndexer(stored, client, throttle); - new MyAnonaMouseAccountStatusService(factory, Proxy((_, _) => null), LogManager.GetCurrentClassLogger()) + new MyAnonaMouseAccountStatusService(factory, factoryState.AccountStatusRepository(), Proxy((_, _) => null), LogManager.GetCurrentClassLogger()) .Execute(new RefreshMyAnonaMouseAccountStatusCommand()); Assert.That(((IndexerHttpClientProxy)(object)client).Requests, Has.Count.EqualTo(1)); @@ -944,9 +1081,9 @@ private static HttpResponse JsonResponse(HttpRequest request, string content) return new HttpResponse(request, new HttpHeader { ContentType = "application/json" }, content, HttpStatusCode.OK); } - private static HttpResponse ValidSummaryResponse(HttpRequest request, string setCookie = null) + private static HttpResponse ValidSummaryResponse(HttpRequest request, string setCookie = null, long? created = null) { - var created = DateTimeOffset.UtcNow.AddMinutes(-1).ToUnixTimeSeconds(); + created ??= DateTimeOffset.UtcNow.AddMinutes(-1).ToUnixTimeSeconds(); var response = JsonResponse(request, $"{{\"uid\":42,\"classname\":\"User\",\"created\":{created},\"unsat\":{{\"count\":3,\"limit\":50}}}}"); if (setCookie != null) { diff --git a/src/NzbDrone.Core/Indexers/IndexerRepository.cs b/src/NzbDrone.Core/Indexers/IndexerRepository.cs index ace52631d..e9544810e 100644 --- a/src/NzbDrone.Core/Indexers/IndexerRepository.cs +++ b/src/NzbDrone.Core/Indexers/IndexerRepository.cs @@ -6,6 +6,7 @@ namespace NzbDrone.Core.Indexers { public interface IIndexerRepository : IProviderRepository { + void UpdateSettings(IndexerDefinition model); } public class IndexerRepository : ProviderRepository, IIndexerRepository @@ -14,5 +15,10 @@ public IndexerRepository(IMainDatabase database, IEventAggregator eventAggregato : base(database, eventAggregator) { } + + public void UpdateSettings(IndexerDefinition model) + { + SetFields(model, m => m.Settings); + } } } diff --git a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouse.cs b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouse.cs index 45f673eb8..ebdb070a8 100644 --- a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouse.cs +++ b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouse.cs @@ -242,21 +242,22 @@ protected override async Task TestConnection() public async Task RefreshAccountStatus() { var connection = MamConnection.For((IndexerDefinition)Definition); - var status = await _accountSummaryThrottle.SendAsync(connection, () => FetchAccountStatus(connection)); + var status = await GetAccountStatus(connection); - Settings.ApplyAccountStatus(status); - - // Requests send the configured cookie, so adopt MAM's rotation before the original expires. - if (!string.IsNullOrWhiteSpace(status.RotatedMamId) && Settings.MamId != status.RotatedMamId) + var previousMamId = Settings.MamId; + Settings.ApplyAccountStatus(status, connection.MamId); + if (Settings.MamId != previousMamId) { _logger.Debug("MAM issued a refreshed mam_id for indexer '{0}'", Definition?.Name); - Settings.MamId = status.RotatedMamId; } _logger.Debug("MAM account status detected: {0} (VIP: {1}), unsatisfied {2}/{3}", status.UserClass, status.IsVip, status.UnsatisfiedCount, status.UnsatisfiedLimit); return status; } + internal Task GetAccountStatus(MamConnection connection) => + _accountSummaryThrottle.SendAsync(connection, () => FetchAccountStatus(connection)); + private async Task FetchAccountStatus(MamConnection connection) { var request = new HttpRequestBuilder($"{connection.BaseUrl}/jsonLoad.php?snatch_summary&pretty") diff --git a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseAccountStatusService.cs b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseAccountStatusService.cs index ab9299172..39353eb88 100644 --- a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseAccountStatusService.cs +++ b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseAccountStatusService.cs @@ -22,6 +22,7 @@ public class MyAnonaMouseAccountStatusService : IMyAnonaMouseAccountStatusServic IExecute { private readonly IIndexerFactory _indexerFactory; + private readonly IIndexerRepository _indexerRepository; private readonly IEventAggregator _eventAggregator; private readonly Logger _logger; private readonly object _refreshLock = new object(); @@ -32,9 +33,10 @@ public class MyAnonaMouseAccountStatusService : IMyAnonaMouseAccountStatusServic private static readonly TimeSpan RefreshInterval = TimeSpan.FromHours(1); - public MyAnonaMouseAccountStatusService(IIndexerFactory indexerFactory, IEventAggregator eventAggregator, Logger logger) + public MyAnonaMouseAccountStatusService(IIndexerFactory indexerFactory, IIndexerRepository indexerRepository, IEventAggregator eventAggregator, Logger logger) { _indexerFactory = indexerFactory; + _indexerRepository = indexerRepository; _eventAggregator = eventAggregator; _logger = logger; } @@ -87,32 +89,35 @@ private void RefreshAccountStatuses(string source) foreach (var indexer in _indexerFactory.GetAvailableProviders().OfType()) { - if (indexer.Definition is not IndexerDefinition definition || - definition.Settings is not MyAnonaMouseSettings settings) + if (indexer.Definition is not IndexerDefinition definition || MamConnection.For(definition) is not { } connection) { continue; } - var previousUserClass = settings.UserClass; - var previousIsVip = settings.IsVip; - var previousUnsatisfiedCount = settings.UnsatisfiedCount; - var previousUnsatisfiedLimit = settings.UnsatisfiedLimit; - var previousSnapshotUtc = settings.UnsatisfiedSnapshotUtc; - try { - var status = indexer.RefreshAccountStatus().GetAwaiter().GetResult(); + var status = indexer.GetAccountStatus(connection).GetAwaiter().GetResult(); summaryHealthChanged |= _unreadableSummaries.TryRemove(definition.Id, out _); refreshed++; - // Persist every successful fetch because its refresh timestamp is the restart-safe freshness boundary. - _indexerFactory.Update(definition); + var stored = _indexerFactory.Find(definition.Id); + if (stored?.Settings is not MyAnonaMouseSettings settings) + { + _logger.Debug("Skipped saving MAM account status for indexer '{0}' because its configuration was removed or replaced", definition.Name); + continue; + } + + // Persist the refresh timestamp even when the counts are unchanged. + var previousMamId = settings.MamId; + var statusChanged = settings.ApplyAccountStatus(status, connection.MamId); + _indexerRepository.UpdateSettings(stored); + + if (settings.MamId != previousMamId) + { + _logger.Debug("MAM issued a refreshed mam_id for indexer '{0}'", stored.Name); + } - if (!string.Equals(previousUserClass, status.UserClass, StringComparison.Ordinal) || - previousIsVip != status.IsVip || - previousUnsatisfiedCount != status.UnsatisfiedCount || - previousUnsatisfiedLimit != status.UnsatisfiedLimit || - previousSnapshotUtc != status.SnapshotCreatedUtc) + if (statusChanged) { changed++; _logger.Info("Updated MAM account status for indexer '{0}': {1} (VIP: {2}), unsatisfied {3}/{4}", diff --git a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseSettings.cs b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseSettings.cs index 44b508f04..43a24e063 100644 --- a/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseSettings.cs +++ b/src/NzbDrone.Core/Indexers/MyAnonaMouse/MyAnonaMouseSettings.cs @@ -117,8 +117,17 @@ public void CopyAccountStatusFrom(MyAnonaMouseSettings source) UnsatisfiedStatusRefreshedUtc = source.UnsatisfiedStatusRefreshedUtc; } - public void ApplyAccountStatus(MyAnonaMouseAccountStatus status) + public bool ApplyAccountStatus(MyAnonaMouseAccountStatus status, string sentMamId) { + var changed = UserClass != status.UserClass || IsVip != status.IsVip || + UnsatisfiedCount != status.UnsatisfiedCount || UnsatisfiedLimit != status.UnsatisfiedLimit || + UnsatisfiedSnapshotUtc != status.SnapshotCreatedUtc; + + if (MamId == sentMamId && !string.IsNullOrWhiteSpace(status.RotatedMamId)) + { + MamId = status.RotatedMamId; + } + UserId = status.UserId; UserClass = status.UserClass; IsVip = status.IsVip; @@ -126,6 +135,7 @@ public void ApplyAccountStatus(MyAnonaMouseAccountStatus status) UnsatisfiedLimit = status.UnsatisfiedLimit; UnsatisfiedSnapshotUtc = status.SnapshotCreatedUtc; UnsatisfiedStatusRefreshedUtc = status.RefreshedUtc; + return changed; } // Required by ITorrentIndexerSettings but hidden from UI