Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 82 additions & 8 deletions Trakt/Helpers/LibraryManagerEventsHelper.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
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;
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;
Expand All @@ -17,20 +21,24 @@ namespace Trakt.Helpers;
internal sealed class LibraryManagerEventsHelper : IDisposable
{
private readonly List<LibraryEvent> _queuedEvents;
private readonly SemaphoreSlim _processLock = new SemaphoreSlim(1, 1);
private readonly ILogger<LibraryManagerEventsHelper> _logger;
private readonly TraktApi _traktApi;
private readonly ILibraryManager _libraryManager;
private Timer _queueTimer;

/// <summary>
/// Initializes a new instance of the <see cref="LibraryManagerEventsHelper"/> class.
/// </summary>
/// <param name="logger">The logger.</param>
/// <param name="traktApi">The <see cref="TraktApi"/>.</param>
public LibraryManagerEventsHelper(ILogger<LibraryManagerEventsHelper> logger, TraktApi traktApi)
/// <param name="libraryManager">The <see cref="ILibraryManager"/>.</param>
public LibraryManagerEventsHelper(ILogger<LibraryManagerEventsHelper> logger, TraktApi traktApi, ILibraryManager libraryManager)
{
_queuedEvents = new List<LibraryEvent>();
_logger = logger;
_traktApi = traktApi;
_libraryManager = libraryManager;
}

/// <summary>
Expand Down Expand Up @@ -64,8 +72,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.
Expand All @@ -84,7 +96,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)
{
Expand Down Expand Up @@ -178,10 +199,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);
}
Expand All @@ -206,18 +229,68 @@ private async Task ProcessQueuedShowEvents(IReadOnlyCollection<LibraryEvent> 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)
{
// Should probably not be awaiting this, but it's unlikely a user will be deleting more than one or two shows at a time
foreach (var show in shows)
try
{
if (eventType == EventType.Remove && IsShowStillInLibrary(show))
{
continue;
}

await _traktApi.SendLibraryUpdateAsync(show, traktUser, eventType, CancellationToken.None).ConfigureAwait(false);
}
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);
}
}
}

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)
{
_logger.LogError(ex, "Exception handled processing queued series events");
// 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;
}

/// <summary>
Expand Down Expand Up @@ -321,5 +394,6 @@ private async Task ProcessQueuedEpisodeEvents(IReadOnlyCollection<LibraryEvent>
public void Dispose()
{
_queueTimer?.Dispose();
_processLock.Dispose();
}
}
2 changes: 1 addition & 1 deletion Trakt/ServerMediator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public ServerMediator(
_playbackState = new Dictionary<Guid, PlaybackState>();

_traktApi = new TraktApi(loggerFactory.CreateLogger<TraktApi>(), httpClientFactory, appHost, userDataManager, userManager);
_libraryManagerEventsHelper = new LibraryManagerEventsHelper(loggerFactory.CreateLogger<LibraryManagerEventsHelper>(), _traktApi);
_libraryManagerEventsHelper = new LibraryManagerEventsHelper(loggerFactory.CreateLogger<LibraryManagerEventsHelper>(), _traktApi, libraryManager);
_userDataManagerEventsHelper = new UserDataManagerEventsHelper(loggerFactory.CreateLogger<UserDataManagerEventsHelper>(), _traktApi);
}

Expand Down