Merge pull request #10592 from barronpm/librarychangednotifier-cleanup

LibraryChangedNotifier Cleanup
This commit is contained in:
Bond-009 2023-11-22 12:57:41 +01:00 committed by GitHub
commit 547d8c07b3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,7 +1,3 @@
#nullable disable
#pragma warning disable CS1591
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
@ -23,9 +19,12 @@ using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Session;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.EntryPoints
{
public class LibraryChangedNotifier : IServerEntryPoint
namespace Emby.Server.Implementations.EntryPoints;
/// <summary>
/// A <see cref="IServerEntryPoint"/> that notifies users when libraries are updated.
/// </summary>
public sealed class LibraryChangedNotifier : IServerEntryPoint
{
private readonly ILibraryManager _libraryManager;
private readonly IServerConfigurationManager _configurationManager;
@ -34,18 +33,25 @@ namespace Emby.Server.Implementations.EntryPoints
private readonly IUserManager _userManager;
private readonly ILogger<LibraryChangedNotifier> _logger;
private readonly object _libraryChangedSyncLock = new();
private readonly List<Folder> _foldersAddedTo = new();
private readonly List<Folder> _foldersRemovedFrom = new();
private readonly List<BaseItem> _itemsAdded = new();
private readonly List<BaseItem> _itemsRemoved = new();
private readonly List<BaseItem> _itemsUpdated = new();
private readonly ConcurrentDictionary<Guid, DateTime> _lastProgressMessageTimes = new();
private Timer? _libraryUpdateTimer;
/// <summary>
/// The library changed sync lock.
/// Initializes a new instance of the <see cref="LibraryChangedNotifier"/> class.
/// </summary>
private readonly object _libraryChangedSyncLock = new object();
private readonly List<Folder> _foldersAddedTo = new List<Folder>();
private readonly List<Folder> _foldersRemovedFrom = new List<Folder>();
private readonly List<BaseItem> _itemsAdded = new List<BaseItem>();
private readonly List<BaseItem> _itemsRemoved = new List<BaseItem>();
private readonly List<BaseItem> _itemsUpdated = new List<BaseItem>();
private readonly ConcurrentDictionary<Guid, DateTime> _lastProgressMessageTimes = new ConcurrentDictionary<Guid, DateTime>();
/// <param name="libraryManager">The <see cref="ILibraryManager"/>.</param>
/// <param name="configurationManager">The <see cref="IServerConfigurationManager"/>.</param>
/// <param name="sessionManager">The <see cref="ISessionManager"/>.</param>
/// <param name="userManager">The <see cref="IUserManager"/>.</param>
/// <param name="logger">The <see cref="ILogger"/>.</param>
/// <param name="providerManager">The <see cref="IProviderManager"/>.</param>
public LibraryChangedNotifier(
ILibraryManager libraryManager,
IServerConfigurationManager configurationManager,
@ -62,12 +68,7 @@ namespace Emby.Server.Implementations.EntryPoints
_providerManager = providerManager;
}
/// <summary>
/// Gets or sets the library update timer.
/// </summary>
/// <value>The library update timer.</value>
private Timer LibraryUpdateTimer { get; set; }
/// <inheritdoc />
public Task RunAsync()
{
_libraryManager.ItemAdded += OnLibraryItemAdded;
@ -81,7 +82,7 @@ namespace Emby.Server.Implementations.EntryPoints
return Task.CompletedTask;
}
private void OnProviderRefreshProgress(object sender, GenericEventArgs<Tuple<BaseItem, double>> e)
private void OnProviderRefreshProgress(object? sender, GenericEventArgs<Tuple<BaseItem, double>> e)
{
var item = e.Argument.Item1;
@ -134,12 +135,12 @@ namespace Emby.Server.Implementations.EntryPoints
}
}
private void OnProviderRefreshStarted(object sender, GenericEventArgs<BaseItem> e)
private void OnProviderRefreshStarted(object? sender, GenericEventArgs<BaseItem> e)
{
OnProviderRefreshProgress(sender, new GenericEventArgs<Tuple<BaseItem, double>>(new Tuple<BaseItem, double>(e.Argument, 0)));
}
private void OnProviderRefreshCompleted(object sender, GenericEventArgs<BaseItem> e)
private void OnProviderRefreshCompleted(object? sender, GenericEventArgs<BaseItem> e)
{
OnProviderRefreshProgress(sender, new GenericEventArgs<Tuple<BaseItem, double>>(new Tuple<BaseItem, double>(e.Argument, 100)));
@ -147,135 +148,48 @@ namespace Emby.Server.Implementations.EntryPoints
}
private static bool EnableRefreshMessage(BaseItem item)
{
if (item is not Folder folder)
{
return false;
}
=> item is Folder { IsRoot: false, IsTopParent: true }
and not (AggregateFolder or UserRootFolder or UserView or Channel);
if (folder.IsRoot)
{
return false;
}
private void OnLibraryItemAdded(object? sender, ItemChangeEventArgs e)
=> OnLibraryChange(e.Item, e.Parent, _itemsAdded, _foldersAddedTo);
if (folder is AggregateFolder || folder is UserRootFolder)
{
return false;
}
private void OnLibraryItemUpdated(object? sender, ItemChangeEventArgs e)
=> OnLibraryChange(e.Item, e.Parent, _itemsUpdated, null);
if (folder is UserView || folder is Channel)
{
return false;
}
private void OnLibraryItemRemoved(object? sender, ItemChangeEventArgs e)
=> OnLibraryChange(e.Item, e.Parent, _itemsRemoved, _foldersRemovedFrom);
if (!folder.IsTopParent)
private void OnLibraryChange(BaseItem item, BaseItem parent, List<BaseItem> itemsList, List<Folder>? foldersList)
{
return false;
}
return true;
}
/// <summary>
/// Handles the ItemAdded event of the libraryManager control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
private void OnLibraryItemAdded(object sender, ItemChangeEventArgs e)
{
if (!FilterItem(e.Item))
if (!FilterItem(item))
{
return;
}
lock (_libraryChangedSyncLock)
{
if (LibraryUpdateTimer is null)
var updateDuration = TimeSpan.FromSeconds(_configurationManager.Configuration.LibraryUpdateDuration);
if (_libraryUpdateTimer is null)
{
LibraryUpdateTimer = new Timer(
LibraryUpdateTimerCallback,
null,
TimeSpan.FromSeconds(_configurationManager.Configuration.LibraryUpdateDuration),
Timeout.InfiniteTimeSpan);
_libraryUpdateTimer = new Timer(LibraryUpdateTimerCallback, null, updateDuration, Timeout.InfiniteTimeSpan);
}
else
{
LibraryUpdateTimer.Change(TimeSpan.FromSeconds(_configurationManager.Configuration.LibraryUpdateDuration), Timeout.InfiniteTimeSpan);
_libraryUpdateTimer.Change(updateDuration, Timeout.InfiniteTimeSpan);
}
if (e.Item.GetParent() is Folder parent)
if (foldersList is not null && parent is Folder folder)
{
_foldersAddedTo.Add(parent);
foldersList.Add(folder);
}
_itemsAdded.Add(e.Item);
itemsList.Add(item);
}
}
/// <summary>
/// Handles the ItemUpdated event of the libraryManager control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
private void OnLibraryItemUpdated(object sender, ItemChangeEventArgs e)
{
if (!FilterItem(e.Item))
{
return;
}
lock (_libraryChangedSyncLock)
{
if (LibraryUpdateTimer is null)
{
LibraryUpdateTimer = new Timer(LibraryUpdateTimerCallback, null, TimeSpan.FromSeconds(_configurationManager.Configuration.LibraryUpdateDuration), Timeout.InfiniteTimeSpan);
}
else
{
LibraryUpdateTimer.Change(TimeSpan.FromSeconds(_configurationManager.Configuration.LibraryUpdateDuration), Timeout.InfiniteTimeSpan);
}
_itemsUpdated.Add(e.Item);
}
}
/// <summary>
/// Handles the ItemRemoved event of the libraryManager control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
private void OnLibraryItemRemoved(object sender, ItemChangeEventArgs e)
{
if (!FilterItem(e.Item))
{
return;
}
lock (_libraryChangedSyncLock)
{
if (LibraryUpdateTimer is null)
{
LibraryUpdateTimer = new Timer(LibraryUpdateTimerCallback, null, TimeSpan.FromSeconds(_configurationManager.Configuration.LibraryUpdateDuration), Timeout.InfiniteTimeSpan);
}
else
{
LibraryUpdateTimer.Change(TimeSpan.FromSeconds(_configurationManager.Configuration.LibraryUpdateDuration), Timeout.InfiniteTimeSpan);
}
if (e.Parent is Folder parent)
{
_foldersRemovedFrom.Add(parent);
}
_itemsRemoved.Add(e.Item);
}
}
/// <summary>
/// Libraries the update timer callback.
/// </summary>
/// <param name="state">The state.</param>
private async void LibraryUpdateTimerCallback(object state)
private async void LibraryUpdateTimerCallback(object? state)
{
List<Folder> foldersAddedTo;
List<Folder> foldersRemovedFrom;
@ -301,10 +215,10 @@ namespace Emby.Server.Implementations.EntryPoints
itemsAdded = _itemsAdded.ToList();
itemsRemoved = _itemsRemoved.ToList();
if (LibraryUpdateTimer is not null)
if (_libraryUpdateTimer is not null)
{
LibraryUpdateTimer.Dispose();
LibraryUpdateTimer = null;
_libraryUpdateTimer.Dispose();
_libraryUpdateTimer = null;
}
_itemsAdded.Clear();
@ -317,16 +231,13 @@ namespace Emby.Server.Implementations.EntryPoints
await SendChangeNotifications(itemsAdded, itemsUpdated, itemsRemoved, foldersAddedTo, foldersRemovedFrom, CancellationToken.None).ConfigureAwait(false);
}
/// <summary>
/// Sends the change notifications.
/// </summary>
/// <param name="itemsAdded">The items added.</param>
/// <param name="itemsUpdated">The items updated.</param>
/// <param name="itemsRemoved">The items removed.</param>
/// <param name="foldersAddedTo">The folders added to.</param>
/// <param name="foldersRemovedFrom">The folders removed from.</param>
/// <param name="cancellationToken">The cancellation token.</param>
private async Task SendChangeNotifications(List<BaseItem> itemsAdded, List<BaseItem> itemsUpdated, List<BaseItem> itemsRemoved, List<Folder> foldersAddedTo, List<Folder> foldersRemovedFrom, CancellationToken cancellationToken)
private async Task SendChangeNotifications(
List<BaseItem> itemsAdded,
List<BaseItem> itemsUpdated,
List<BaseItem> itemsRemoved,
List<Folder> foldersAddedTo,
List<Folder> foldersRemovedFrom,
CancellationToken cancellationToken)
{
var userIds = _sessionManager.Sessions
.Select(i => i.UserId)
@ -355,7 +266,12 @@ namespace Emby.Server.Implementations.EntryPoints
try
{
await _sessionManager.SendMessageToUserSessions(new List<Guid> { userId }, SessionMessageType.LibraryChanged, info, cancellationToken).ConfigureAwait(false);
await _sessionManager.SendMessageToUserSessions(
new List<Guid> { userId },
SessionMessageType.LibraryChanged,
info,
cancellationToken)
.ConfigureAwait(false);
}
catch (Exception ex)
{
@ -364,38 +280,48 @@ namespace Emby.Server.Implementations.EntryPoints
}
}
/// <summary>
/// Gets the library update info.
/// </summary>
/// <param name="itemsAdded">The items added.</param>
/// <param name="itemsUpdated">The items updated.</param>
/// <param name="itemsRemoved">The items removed.</param>
/// <param name="foldersAddedTo">The folders added to.</param>
/// <param name="foldersRemovedFrom">The folders removed from.</param>
/// <param name="userId">The user id.</param>
/// <returns>LibraryUpdateInfo.</returns>
private LibraryUpdateInfo GetLibraryUpdateInfo(List<BaseItem> itemsAdded, List<BaseItem> itemsUpdated, List<BaseItem> itemsRemoved, List<Folder> foldersAddedTo, List<Folder> foldersRemovedFrom, Guid userId)
private LibraryUpdateInfo GetLibraryUpdateInfo(
List<BaseItem> itemsAdded,
List<BaseItem> itemsUpdated,
List<BaseItem> itemsRemoved,
List<Folder> foldersAddedTo,
List<Folder> foldersRemovedFrom,
Guid userId)
{
var user = _userManager.GetUserById(userId);
ArgumentNullException.ThrowIfNull(user);
var newAndRemoved = new List<BaseItem>();
newAndRemoved.AddRange(foldersAddedTo);
newAndRemoved.AddRange(foldersRemovedFrom);
var allUserRootChildren = _libraryManager.GetUserRootFolder().GetChildren(user, true).OfType<Folder>().ToList();
var allUserRootChildren = _libraryManager.GetUserRootFolder()
.GetChildren(user, true)
.OfType<Folder>()
.ToList();
return new LibraryUpdateInfo
{
ItemsAdded = itemsAdded.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user)).Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture)).Distinct().ToArray(),
ItemsUpdated = itemsUpdated.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user)).Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture)).Distinct().ToArray(),
ItemsRemoved = itemsRemoved.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user, true)).Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture)).Distinct().ToArray(),
FoldersAddedTo = foldersAddedTo.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user)).Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture)).Distinct().ToArray(),
FoldersRemovedFrom = foldersRemovedFrom.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user)).Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture)).Distinct().ToArray(),
ItemsAdded = itemsAdded.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user))
.Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture))
.Distinct()
.ToArray(),
ItemsUpdated = itemsUpdated.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user))
.Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture))
.Distinct()
.ToArray(),
ItemsRemoved = itemsRemoved.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user, true))
.Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture))
.Distinct()
.ToArray(),
FoldersAddedTo = foldersAddedTo.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user))
.Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture))
.Distinct()
.ToArray(),
FoldersRemovedFrom = foldersRemovedFrom.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user))
.Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture))
.Distinct()
.ToArray(),
CollectionFolders = GetTopParentIds(newAndRemoved, allUserRootChildren).ToArray()
};
}
@ -436,21 +362,13 @@ namespace Emby.Server.Implementations.EntryPoints
return list.Distinct(StringComparer.Ordinal);
}
/// <summary>
/// Translates the physical item to user library.
/// </summary>
/// <typeparam name="T">The type of item.</typeparam>
/// <param name="item">The item.</param>
/// <param name="user">The user.</param>
/// <param name="includeIfNotFound">if set to <c>true</c> [include if not found].</param>
/// <returns>IEnumerable{``0}.</returns>
private IEnumerable<T> TranslatePhysicalItemToUserLibrary<T>(T item, User user, bool includeIfNotFound = false)
where T : BaseItem
{
// If the physical root changed, return the user root
if (item is AggregateFolder)
{
return new[] { _libraryManager.GetUserRootFolder() as T };
return _libraryManager.GetUserRootFolder() is T t ? new[] { t } : Array.Empty<T>();
}
// Return it only if it's in the user's library
@ -462,29 +380,9 @@ namespace Emby.Server.Implementations.EntryPoints
return Array.Empty<T>();
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <inheritdoc />
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool dispose)
{
if (dispose)
{
if (LibraryUpdateTimer is not null)
{
LibraryUpdateTimer.Dispose();
LibraryUpdateTimer = null;
}
_libraryManager.ItemAdded -= OnLibraryItemAdded;
_libraryManager.ItemUpdated -= OnLibraryItemUpdated;
_libraryManager.ItemRemoved -= OnLibraryItemRemoved;
@ -492,7 +390,11 @@ namespace Emby.Server.Implementations.EntryPoints
_providerManager.RefreshCompleted -= OnProviderRefreshCompleted;
_providerManager.RefreshStarted -= OnProviderRefreshStarted;
_providerManager.RefreshProgress -= OnProviderRefreshProgress;
}
if (_libraryUpdateTimer is not null)
{
_libraryUpdateTimer.Dispose();
_libraryUpdateTimer = null;
}
}
}