Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixing issues around marking seasons/episodes as watched #84

Merged
merged 5 commits into from
Oct 20, 2023
Merged
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
94 changes: 94 additions & 0 deletions Tasks/TaskProcessMarkedMedia.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.IO;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;

namespace jellyfin_ani_sync;

public class TaskProcessMarkedMedia {
private List<(Guid userId, Guid? seasonId, Video baseItem)> itemsToUpdate { get; set; } = new ();
private readonly ILoggerFactory _loggerFactory;
private readonly ILogger<TaskProcessMarkedMedia> _logger;
private readonly ILibraryManager _libraryManager;
private readonly IFileSystem _fileSystem;
private readonly IMemoryCache _memoryCache;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IServerApplicationHost _serverApplicationHost;
private readonly IHttpClientFactory _httpClientFactory;
private readonly IApplicationPaths _applicationPaths;

public TaskProcessMarkedMedia(ILoggerFactory loggerFactory, ILibraryManager libraryManager, IFileSystem fileSystem, IMemoryCache memoryCache, IHttpContextAccessor httpContextAccessor, IServerApplicationHost serverApplicationHost, IHttpClientFactory httpClientFactory, IApplicationPaths applicationPaths) {
_loggerFactory = loggerFactory;
_libraryManager = libraryManager;
_fileSystem = fileSystem;
_memoryCache = memoryCache;
_httpContextAccessor = httpContextAccessor;
_serverApplicationHost = serverApplicationHost;
_httpClientFactory = httpClientFactory;
_applicationPaths = applicationPaths;
_logger = loggerFactory.CreateLogger<TaskProcessMarkedMedia>();
}

public void AddToUpdateList((Guid userId, Guid? seasonId, Video baseItem) itemToAdd) {
lock (itemsToUpdate) {
itemsToUpdate.Add(itemToAdd);
}
}

private void RemoveFromUpdateList((Guid userId, Guid? seasonId, Video baseItem) itemToRemove) {
lock (itemsToUpdate) {
itemsToUpdate.Remove(itemToRemove);
}
}

public async Task RunUpdate() {
// wait a second to let the list populate itself if a mass update is occuring
await Task.Delay(1000);

while (itemsToUpdate.Any()) {
var item = itemsToUpdate.FirstOrDefault();
if (item.Equals(default)) {
RemoveFromUpdateList(item);
continue;
};

var aniSyncConfigUser = Plugin.Instance?.PluginConfiguration.UserConfig.FirstOrDefault(uc => uc.UserId == item.userId);
List<(Guid userId, Guid? seasonId, Video baseItem)> pairedItems = new List<(Guid userId, Guid? seasonId, Video baseItem)>();
if (aniSyncConfigUser != null && UpdateProviderStatus.LibraryCheck(aniSyncConfigUser, _libraryManager, _fileSystem, _logger, item.baseItem)) {
if (_memoryCache.TryGetValue("lastQuery", out DateTime lastQuery)) {
if ((DateTime.UtcNow - lastQuery).TotalSeconds <= 5) {
await Task.Delay(5000);
_logger.LogInformation("Too many requests! Waiting 5 seconds...");
}
}

_memoryCache.Set("lastQuery", DateTime.UtcNow, new MemoryCacheEntryOptions {
AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(5)
});

UpdateProviderStatus updateProviderStatus = new UpdateProviderStatus(_fileSystem, _libraryManager, _loggerFactory, _httpContextAccessor, _serverApplicationHost, _httpClientFactory, _applicationPaths);
pairedItems = itemsToUpdate.Where(items => items.seasonId == item.seasonId && items.userId == item.userId).ToList();
item = pairedItems.MaxBy(item => item.baseItem.IndexNumber);
await updateProviderStatus.Update(item.baseItem, item.userId, true);
}

if (pairedItems.Count() > 1) {
foreach ((Guid userId, Guid? seasonId, Video baseItem) pairedItem in pairedItems) {
RemoveFromUpdateList(pairedItem);
}
} else {
RemoveFromUpdateList(item);
}
}
}
}
23 changes: 16 additions & 7 deletions UpdateProviderStatus.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public async Task Update(BaseItem e, Guid userId, bool playedToCompletion) {
return;
}

if (LibraryCheck(e) && video is Episode or Movie && playedToCompletion) {
if (LibraryCheck(_userConfig, _libraryManager, _fileSystem, _logger, e) && video is Episode or Movie && playedToCompletion) {
if ((video is Episode && (episode.IndexNumber == null ||
episode.Season.IndexNumber == null)) ||
(video is Movie && movie.IndexNumber == null)) {
Expand Down Expand Up @@ -339,14 +339,23 @@ private bool ContainsExtended(string first, string second) {
return StringFormatter.RemoveSpecialCharacters(first).Contains(StringFormatter.RemoveSpecialCharacters(second), StringComparison.OrdinalIgnoreCase);
}

private bool LibraryCheck(BaseItem item) {
/// <summary>
/// Checks if the supplied item is in a folder the user wants to track for anime updates.
/// </summary>
/// <param name="userConfig">User config.</param>
/// <param name="libraryManager">Library manager instance.</param>
/// <param name="fileSystem">File system instance.</param>
/// <param name="logger">Logger instance.</param>
/// <param name="item">Item to check location of.</param>
/// <returns></returns>
public static bool LibraryCheck(UserConfig userConfig, ILibraryManager libraryManager, IFileSystem fileSystem, ILogger logger, BaseItem item) {
try {
if (_userConfig.LibraryToCheck is { Length: > 0 }) {
var folders = _libraryManager.GetVirtualFolders().Where(item => _userConfig.LibraryToCheck.Contains(item.ItemId));
if (userConfig.LibraryToCheck is { Length: > 0 }) {
var folders = libraryManager.GetVirtualFolders().Where(item => userConfig.LibraryToCheck.Contains(item.ItemId));

foreach (var folder in folders) {
foreach (var location in folder.Locations) {
if (item.Path != null && _fileSystem.ContainsSubPath(location, item.Path)) {
if (item.Path != null && fileSystem.ContainsSubPath(location, item.Path)) {
// item is in a path of a folder the user wants to be monitored
return true;
}
Expand All @@ -357,10 +366,10 @@ private bool LibraryCheck(BaseItem item) {
return true;
}

_logger.LogInformation("Item is in a folder the user does not want to be monitored; ignoring");
logger.LogInformation("Item is in a folder the user does not want to be monitored; ignoring");
return false;
} catch (Exception e) {
_logger.LogInformation($"Library check ran into an issue: {e.Message}");
logger.LogInformation($"Library check ran into an issue: {e.Message}");
return false;
}
}
Expand Down
32 changes: 11 additions & 21 deletions UserDataServerEntry.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#nullable enable
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller;
Expand All @@ -19,13 +19,13 @@ public class UserDataServerEntry : IServerEntryPoint {
private readonly IUserDataManager _userDataManager;
private readonly IFileSystem _fileSystem;
private readonly ILibraryManager _libraryManager;
private readonly ILoggerFactory _loggerFactory;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IServerApplicationHost _serverApplicationHost;
private readonly IHttpClientFactory _httpClientFactory;
private readonly IMemoryCache _memoryCache;
private readonly IApplicationPaths _applicationPaths;
private readonly ILogger<UpdateProviderStatus> _logger;
private readonly TaskProcessMarkedMedia _taskProcessMarkedMedia;
private Task? _updateTask;

public UserDataServerEntry(IUserDataManager userDataManager,
IFileSystem fileSystem,
Expand All @@ -39,13 +39,13 @@ public UserDataServerEntry(IUserDataManager userDataManager,
_userDataManager = userDataManager;
_fileSystem = fileSystem;
_libraryManager = libraryManager;
_loggerFactory = loggerFactory;
_logger = loggerFactory.CreateLogger<UpdateProviderStatus>();
loggerFactory.CreateLogger<UpdateProviderStatus>();
_httpContextAccessor = httpContextAccessor;
_serverApplicationHost = serverApplicationHost;
_httpClientFactory = httpClientFactory;
_memoryCache = memoryCache;
_applicationPaths = applicationPaths;
_taskProcessMarkedMedia = new TaskProcessMarkedMedia(loggerFactory, _libraryManager, _fileSystem, _memoryCache, _httpContextAccessor, _serverApplicationHost, _httpClientFactory, _applicationPaths);
}

public Task RunAsync() {
Expand All @@ -54,25 +54,15 @@ public Task RunAsync() {
}

private void UserDataManagerOnUserDataSaved(object sender, UserDataSaveEventArgs e) {
if (e.SaveReason == UserDataSaveReason.TogglePlayed && Plugin.Instance.PluginConfiguration.watchedTickboxUpdatesProvider) {
if (e.SaveReason == UserDataSaveReason.TogglePlayed && Plugin.Instance?.PluginConfiguration.watchedTickboxUpdatesProvider == true) {
if (!e.UserData.Played || e.Item is not Video) return;
var _ = UpdateJob(e);
}
}

private async Task UpdateJob(UserDataSaveEventArgs e) {
if (_memoryCache.TryGetValue("lastQuery", out DateTime lastQuery)) {
if ((DateTime.UtcNow - lastQuery).TotalSeconds <= 5) {
Thread.Sleep(5000);
_logger.LogInformation("Too many requests! Waiting 5 seconds...");
// asynchronous call so it doesn't prevent the UI marking the media as watched
Episode? episode = e.Item as Episode;
_taskProcessMarkedMedia.AddToUpdateList((e.UserId, episode?.Season.Id, e.Item as Video));
if (_updateTask == null || _updateTask.IsCompleted) {
_updateTask = _taskProcessMarkedMedia.RunUpdate();
}
}

_memoryCache.Set("lastQuery", DateTime.UtcNow, new MemoryCacheEntryOptions {
AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(5)
});
UpdateProviderStatus updateProviderStatus = new UpdateProviderStatus(_fileSystem, _libraryManager, _loggerFactory, _httpContextAccessor, _serverApplicationHost, _httpClientFactory, _applicationPaths);
await updateProviderStatus.Update(e.Item, e.UserId, true);
}

public void Dispose() {
Expand Down