From bf883afe52f4d15e61ad01f40374899969402edd Mon Sep 17 00:00:00 2001 From: zotabee <89345101+zotabee@users.noreply.github.com> Date: Sat, 17 Oct 2026 22:33:20 +0200 Subject: [PATCH 1/2] Remove a deleted series from the trakt.tv collection Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019NK5BSFsEuuqMcNPPpysee --- Trakt/Helpers/LibraryManagerEventsHelper.cs | 75 +++++++++++++++++++-- Trakt/ServerMediator.cs | 2 +- 2 files changed, 71 insertions(+), 6 deletions(-) diff --git a/Trakt/Helpers/LibraryManagerEventsHelper.cs b/Trakt/Helpers/LibraryManagerEventsHelper.cs index b34f1ff6..81fb43cf 100644 --- a/Trakt/Helpers/LibraryManagerEventsHelper.cs +++ b/Trakt/Helpers/LibraryManagerEventsHelper.cs @@ -3,9 +3,11 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Jellyfin.Data.Enums; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Entities.TV; +using MediaBrowser.Controller.Library; using MediaBrowser.Model.Entities; using Microsoft.Extensions.Logging; using Trakt.Api; @@ -17,8 +19,10 @@ namespace Trakt.Helpers; internal sealed class LibraryManagerEventsHelper : IDisposable { private readonly List _queuedEvents; + private readonly SemaphoreSlim _processLock = new SemaphoreSlim(1, 1); private readonly ILogger _logger; private readonly TraktApi _traktApi; + private readonly ILibraryManager _libraryManager; private Timer _queueTimer; /// @@ -26,11 +30,13 @@ internal sealed class LibraryManagerEventsHelper : IDisposable /// /// The logger. /// The . - public LibraryManagerEventsHelper(ILogger logger, TraktApi traktApi) + /// The . + public LibraryManagerEventsHelper(ILogger logger, TraktApi traktApi, ILibraryManager libraryManager) { _queuedEvents = new List(); _logger = logger; _traktApi = traktApi; + _libraryManager = libraryManager; } /// @@ -64,8 +70,12 @@ public void QueueItem(BaseItem item, EventType eventType) } // Check if item can be synced for all users. + // Jellyfin removes a deleted series' episodes from the library before reporting them, so they can't be traced + // back to it and CanSync skips them. Queue the series itself; ProcessQueuedShowEvents checks its ids, excluded locations + // and whether another copy is still in the library. + var isSeriesRemoval = item is Series && item.Path != null && eventType == EventType.Remove; - foreach (var user in users.Where(user => _traktApi.CanSync(item, user))) + foreach (var user in users.Where(user => isSeriesRemoval || _traktApi.CanSync(item, user))) { // Add to queue. // Sync will be processed when the next timer elapsed event fires. @@ -84,7 +94,16 @@ private async void OnQueueTimerCallback(object state) { try { - await OnQueueTimerCallbackInternal().ConfigureAwait(false); + // One batch at a time, so a later batch can't add a show back before an earlier one removes it + await _processLock.WaitAsync().ConfigureAwait(false); + try + { + await OnQueueTimerCallbackInternal().ConfigureAwait(false); + } + finally + { + _processLock.Release(); + } } catch (Exception ex) { @@ -178,10 +197,12 @@ private async Task OnQueueTimerCallbackInternal() await ProcessQueuedMovieEvents(queuedMovieUpdates, traktUser, EventType.Update).ConfigureAwait(false); await ProcessQueuedEpisodeEvents(queuedEpisodeDeletes, traktUser, EventType.Remove).ConfigureAwait(false); + + // Remove deleted shows before adding episodes, so a series moved to another folder isn't removed after its episodes were added back + await ProcessQueuedShowEvents(queuedShowDeletes, traktUser, EventType.Remove).ConfigureAwait(false); await ProcessQueuedEpisodeEvents(queuedEpisodeAdds, traktUser, EventType.Add).ConfigureAwait(false); await ProcessQueuedEpisodeEvents(queuedEpisodeUpdates, traktUser, EventType.Update).ConfigureAwait(false); - await ProcessQueuedShowEvents(queuedShowDeletes, traktUser, EventType.Remove).ConfigureAwait(false); await ProcessQueuedShowEvents(queuedShowAdds, traktUser, EventType.Add).ConfigureAwait(false); await ProcessQueuedShowEvents(queuedShowUpdates, traktUser, EventType.Update).ConfigureAwait(false); } @@ -208,9 +229,14 @@ private async Task ProcessQueuedShowEvents(IReadOnlyCollection eve try { - // Should probably not be awaiting this, but it's unlikely a user will be deleting more than one or two shows at a time + // One request per show, so removing a whole library sends many; each is checked right before it is sent foreach (var show in shows) { + if (eventType == EventType.Remove && IsShowStillInLibrary(show)) + { + continue; + } + await _traktApi.SendLibraryUpdateAsync(show, traktUser, eventType, CancellationToken.None).ConfigureAwait(false); } } @@ -220,6 +246,44 @@ private async Task ProcessQueuedShowEvents(IReadOnlyCollection eve } } + private bool IsShowStillInLibrary(Series show) + { + // The deleted series is already gone from the library, so a series with one of its ids is another copy + // (e.g. an HD and a 4K library) or the same show moved to another folder. Removing it would remove every copy. + var providerIds = new[] { MetadataProvider.Tmdb, MetadataProvider.Tvdb, MetadataProvider.Imdb, MetadataProvider.TvRage } + .Select(provider => (Key: provider.ToString(), Value: show.GetProviderId(provider))) + .Where(id => !string.IsNullOrEmpty(id.Value)) + .ToDictionary(id => id.Key, id => id.Value); + if (providerIds.Count == 0) + { + // An empty filter would match every series + return false; + } + + bool stillInLibrary; + try + { + stillInLibrary = _libraryManager.GetCount(new InternalItemsQuery + { + IncludeItemTypes = new[] { BaseItemKind.Series }, + HasAnyProviderId = providerIds + }) > 0; + } + catch (Exception ex) + { + // Keeping the show collected is the safe choice when the library can't be checked + _logger.LogWarning(ex, "Could not check whether {Show} is still in the library, not removing it from trakt.tv", show.Name); + return true; + } + + if (stillInLibrary) + { + _logger.LogInformation("Not removing {Show} from the trakt.tv collection: it is still in the library", show.Name); + } + + return stillInLibrary; + } + /// /// Processes queued movie events. /// @@ -321,5 +385,6 @@ private async Task ProcessQueuedEpisodeEvents(IReadOnlyCollection public void Dispose() { _queueTimer?.Dispose(); + _processLock.Dispose(); } } diff --git a/Trakt/ServerMediator.cs b/Trakt/ServerMediator.cs index 52591f11..01a68b1d 100644 --- a/Trakt/ServerMediator.cs +++ b/Trakt/ServerMediator.cs @@ -62,7 +62,7 @@ public ServerMediator( _playbackState = new Dictionary(); _traktApi = new TraktApi(loggerFactory.CreateLogger(), httpClientFactory, appHost, userDataManager, userManager); - _libraryManagerEventsHelper = new LibraryManagerEventsHelper(loggerFactory.CreateLogger(), _traktApi); + _libraryManagerEventsHelper = new LibraryManagerEventsHelper(loggerFactory.CreateLogger(), _traktApi, libraryManager); _userDataManagerEventsHelper = new UserDataManagerEventsHelper(loggerFactory.CreateLogger(), _traktApi); } From 38580e3e2f7af34122ce61ad0aa7db35d0d54ae4 Mon Sep 17 00:00:00 2001 From: zotabee <89345101+zotabee@users.noreply.github.com> Date: Mon, 19 Oct 2026 20:51:02 +0200 Subject: [PATCH 2/2] Keep removing the other shows when one removal fails Co-Authored-By: Claude Opus 5.5 --- Trakt/Helpers/LibraryManagerEventsHelper.cs | 23 ++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/Trakt/Helpers/LibraryManagerEventsHelper.cs b/Trakt/Helpers/LibraryManagerEventsHelper.cs index 81fb43cf..c7852130 100644 --- a/Trakt/Helpers/LibraryManagerEventsHelper.cs +++ b/Trakt/Helpers/LibraryManagerEventsHelper.cs @@ -1,6 +1,8 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Net; +using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Jellyfin.Data.Enums; @@ -227,10 +229,11 @@ private async Task ProcessQueuedShowEvents(IReadOnlyCollection eve && (traktUser.LocationsExcluded == null || !traktUser.LocationsExcluded.Any(directory => lev.Path.Contains(directory, StringComparison.OrdinalIgnoreCase)))) .ToHashSet(); - try + // One request per show, so removing a whole library sends many; each is checked right before it is sent, + // and a request that fails for one show doesn't stop the others + foreach (var show in shows) { - // One request per show, so removing a whole library sends many; each is checked right before it is sent - foreach (var show in shows) + try { if (eventType == EventType.Remove && IsShowStillInLibrary(show)) { @@ -239,10 +242,16 @@ private async Task ProcessQueuedShowEvents(IReadOnlyCollection eve await _traktApi.SendLibraryUpdateAsync(show, traktUser, eventType, CancellationToken.None).ConfigureAwait(false); } - } - catch (Exception ex) - { - _logger.LogError(ex, "Exception handled processing queued series events"); + catch (Exception ex) when (ex is OperationCanceledException or HttpRequestException { StatusCode: null or HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden or HttpStatusCode.Locked or (HttpStatusCode)420 or HttpStatusCode.TooManyRequests or >= HttpStatusCode.BadGateway }) + { + // trakt.tv is unreachable, times out, rejects the account or limits it, so the other shows would fail the same way + _logger.LogError(ex, "Not sending the remaining shows: the request for {Show} failed", show.Name); + return; + } + catch (Exception ex) + { + _logger.LogError(ex, "Exception handled processing queued series event for {Show}", show.Name); + } } }