| | 1 | | using System; |
| | 2 | | using System.Collections.Concurrent; |
| | 3 | | using System.Collections.Generic; |
| | 4 | | using System.Globalization; |
| | 5 | | using System.Linq; |
| | 6 | | using System.Threading; |
| | 7 | | using System.Threading.Tasks; |
| | 8 | | using Jellyfin.Data.Events; |
| | 9 | | using Jellyfin.Database.Implementations.Entities; |
| | 10 | | using Jellyfin.Extensions; |
| | 11 | | using MediaBrowser.Controller.Channels; |
| | 12 | | using MediaBrowser.Controller.Configuration; |
| | 13 | | using MediaBrowser.Controller.Entities; |
| | 14 | | using MediaBrowser.Controller.Entities.Audio; |
| | 15 | | using MediaBrowser.Controller.Library; |
| | 16 | | using MediaBrowser.Controller.Providers; |
| | 17 | | using MediaBrowser.Controller.Session; |
| | 18 | | using MediaBrowser.Model.Entities; |
| | 19 | | using MediaBrowser.Model.Session; |
| | 20 | | using Microsoft.Extensions.Hosting; |
| | 21 | | using Microsoft.Extensions.Logging; |
| | 22 | |
|
| | 23 | | namespace Emby.Server.Implementations.EntryPoints; |
| | 24 | |
|
| | 25 | | /// <summary> |
| | 26 | | /// A <see cref="IHostedService"/> responsible for notifying users when libraries are updated. |
| | 27 | | /// </summary> |
| | 28 | | public sealed class LibraryChangedNotifier : IHostedService, IDisposable |
| | 29 | | { |
| | 30 | | private readonly ILibraryManager _libraryManager; |
| | 31 | | private readonly IServerConfigurationManager _configurationManager; |
| | 32 | | private readonly IProviderManager _providerManager; |
| | 33 | | private readonly ISessionManager _sessionManager; |
| | 34 | | private readonly IUserManager _userManager; |
| | 35 | | private readonly ILogger<LibraryChangedNotifier> _logger; |
| | 36 | |
|
| 21 | 37 | | private readonly Lock _libraryChangedSyncLock = new(); |
| 21 | 38 | | private readonly List<Folder> _foldersAddedTo = new(); |
| 21 | 39 | | private readonly List<Folder> _foldersRemovedFrom = new(); |
| 21 | 40 | | private readonly List<BaseItem> _itemsAdded = new(); |
| 21 | 41 | | private readonly List<BaseItem> _itemsRemoved = new(); |
| 21 | 42 | | private readonly List<BaseItem> _itemsUpdated = new(); |
| 21 | 43 | | private readonly ConcurrentDictionary<Guid, DateTime> _lastProgressMessageTimes = new(); |
| | 44 | |
|
| | 45 | | private Timer? _libraryUpdateTimer; |
| | 46 | |
|
| | 47 | | /// <summary> |
| | 48 | | /// Initializes a new instance of the <see cref="LibraryChangedNotifier"/> class. |
| | 49 | | /// </summary> |
| | 50 | | /// <param name="libraryManager">The <see cref="ILibraryManager"/>.</param> |
| | 51 | | /// <param name="configurationManager">The <see cref="IServerConfigurationManager"/>.</param> |
| | 52 | | /// <param name="sessionManager">The <see cref="ISessionManager"/>.</param> |
| | 53 | | /// <param name="userManager">The <see cref="IUserManager"/>.</param> |
| | 54 | | /// <param name="logger">The <see cref="ILogger"/>.</param> |
| | 55 | | /// <param name="providerManager">The <see cref="IProviderManager"/>.</param> |
| | 56 | | public LibraryChangedNotifier( |
| | 57 | | ILibraryManager libraryManager, |
| | 58 | | IServerConfigurationManager configurationManager, |
| | 59 | | ISessionManager sessionManager, |
| | 60 | | IUserManager userManager, |
| | 61 | | ILogger<LibraryChangedNotifier> logger, |
| | 62 | | IProviderManager providerManager) |
| | 63 | | { |
| 21 | 64 | | _libraryManager = libraryManager; |
| 21 | 65 | | _configurationManager = configurationManager; |
| 21 | 66 | | _sessionManager = sessionManager; |
| 21 | 67 | | _userManager = userManager; |
| 21 | 68 | | _logger = logger; |
| 21 | 69 | | _providerManager = providerManager; |
| 21 | 70 | | } |
| | 71 | |
|
| | 72 | | /// <inheritdoc /> |
| | 73 | | public Task StartAsync(CancellationToken cancellationToken) |
| | 74 | | { |
| 21 | 75 | | _libraryManager.ItemAdded += OnLibraryItemAdded; |
| 21 | 76 | | _libraryManager.ItemUpdated += OnLibraryItemUpdated; |
| 21 | 77 | | _libraryManager.ItemRemoved += OnLibraryItemRemoved; |
| | 78 | |
|
| 21 | 79 | | _providerManager.RefreshCompleted += OnProviderRefreshCompleted; |
| 21 | 80 | | _providerManager.RefreshStarted += OnProviderRefreshStarted; |
| 21 | 81 | | _providerManager.RefreshProgress += OnProviderRefreshProgress; |
| | 82 | |
|
| 21 | 83 | | return Task.CompletedTask; |
| | 84 | | } |
| | 85 | |
|
| | 86 | | /// <inheritdoc /> |
| | 87 | | public Task StopAsync(CancellationToken cancellationToken) |
| | 88 | | { |
| 21 | 89 | | _libraryManager.ItemAdded -= OnLibraryItemAdded; |
| 21 | 90 | | _libraryManager.ItemUpdated -= OnLibraryItemUpdated; |
| 21 | 91 | | _libraryManager.ItemRemoved -= OnLibraryItemRemoved; |
| | 92 | |
|
| 21 | 93 | | _providerManager.RefreshCompleted -= OnProviderRefreshCompleted; |
| 21 | 94 | | _providerManager.RefreshStarted -= OnProviderRefreshStarted; |
| 21 | 95 | | _providerManager.RefreshProgress -= OnProviderRefreshProgress; |
| | 96 | |
|
| 21 | 97 | | return Task.CompletedTask; |
| | 98 | | } |
| | 99 | |
|
| | 100 | | private void OnProviderRefreshProgress(object? sender, GenericEventArgs<Tuple<BaseItem, double>> e) |
| | 101 | | { |
| 50 | 102 | | var item = e.Argument.Item1; |
| | 103 | |
|
| 50 | 104 | | if (!EnableRefreshMessage(item)) |
| | 105 | | { |
| 50 | 106 | | return; |
| | 107 | | } |
| | 108 | |
|
| 0 | 109 | | var progress = e.Argument.Item2; |
| | 110 | |
|
| 0 | 111 | | if (_lastProgressMessageTimes.TryGetValue(item.Id, out var lastMessageSendTime)) |
| | 112 | | { |
| 0 | 113 | | if (progress > 0 && progress < 100 && (DateTime.UtcNow - lastMessageSendTime).TotalMilliseconds < 1000) |
| | 114 | | { |
| 0 | 115 | | return; |
| | 116 | | } |
| | 117 | | } |
| | 118 | |
|
| 0 | 119 | | _lastProgressMessageTimes.AddOrUpdate(item.Id, _ => DateTime.UtcNow, (_, _) => DateTime.UtcNow); |
| | 120 | |
|
| 0 | 121 | | var dict = new Dictionary<string, string>(); |
| 0 | 122 | | dict["ItemId"] = item.Id.ToString("N", CultureInfo.InvariantCulture); |
| 0 | 123 | | dict["Progress"] = progress.ToString(CultureInfo.InvariantCulture); |
| | 124 | |
|
| | 125 | | try |
| | 126 | | { |
| 0 | 127 | | _sessionManager.SendMessageToAdminSessions(SessionMessageType.RefreshProgress, dict, CancellationToken.None) |
| 0 | 128 | | } |
| 0 | 129 | | catch |
| | 130 | | { |
| 0 | 131 | | } |
| | 132 | |
|
| 0 | 133 | | var collectionFolders = _libraryManager.GetCollectionFolders(item); |
| | 134 | |
|
| 0 | 135 | | foreach (var collectionFolder in collectionFolders) |
| | 136 | | { |
| 0 | 137 | | var collectionFolderDict = new Dictionary<string, string> |
| 0 | 138 | | { |
| 0 | 139 | | ["ItemId"] = collectionFolder.Id.ToString("N", CultureInfo.InvariantCulture), |
| 0 | 140 | | ["Progress"] = (collectionFolder.GetRefreshProgress() ?? 0).ToString(CultureInfo.InvariantCulture) |
| 0 | 141 | | }; |
| | 142 | |
|
| | 143 | | try |
| | 144 | | { |
| 0 | 145 | | _sessionManager.SendMessageToAdminSessions(SessionMessageType.RefreshProgress, collectionFolderDict, Can |
| 0 | 146 | | } |
| 0 | 147 | | catch |
| | 148 | | { |
| 0 | 149 | | } |
| | 150 | | } |
| 0 | 151 | | } |
| | 152 | |
|
| | 153 | | private void OnProviderRefreshStarted(object? sender, GenericEventArgs<BaseItem> e) |
| 10 | 154 | | => OnProviderRefreshProgress(sender, new GenericEventArgs<Tuple<BaseItem, double>>(new Tuple<BaseItem, double>(e |
| | 155 | |
|
| | 156 | | private void OnProviderRefreshCompleted(object? sender, GenericEventArgs<BaseItem> e) |
| | 157 | | { |
| 10 | 158 | | OnProviderRefreshProgress(sender, new GenericEventArgs<Tuple<BaseItem, double>>(new Tuple<BaseItem, double>(e.Ar |
| | 159 | |
|
| 10 | 160 | | _lastProgressMessageTimes.TryRemove(e.Argument.Id, out _); |
| 10 | 161 | | } |
| | 162 | |
|
| | 163 | | private static bool EnableRefreshMessage(BaseItem item) |
| 50 | 164 | | => item is Folder { IsRoot: false, IsTopParent: true } |
| 50 | 165 | | and not (AggregateFolder or UserRootFolder or UserView or Channel); |
| | 166 | |
|
| | 167 | | private void OnLibraryItemAdded(object? sender, ItemChangeEventArgs e) |
| 2 | 168 | | => OnLibraryChange(e.Item, e.Parent, _itemsAdded, _foldersAddedTo); |
| | 169 | |
|
| | 170 | | private void OnLibraryItemUpdated(object? sender, ItemChangeEventArgs e) |
| 71 | 171 | | => OnLibraryChange(e.Item, e.Parent, _itemsUpdated, null); |
| | 172 | |
|
| | 173 | | private void OnLibraryItemRemoved(object? sender, ItemChangeEventArgs e) |
| 2 | 174 | | => OnLibraryChange(e.Item, e.Parent, _itemsRemoved, _foldersRemovedFrom); |
| | 175 | |
|
| | 176 | | private void OnLibraryChange(BaseItem item, BaseItem parent, List<BaseItem> itemsList, List<Folder>? foldersList) |
| | 177 | | { |
| 75 | 178 | | if (!FilterItem(item)) |
| | 179 | | { |
| 0 | 180 | | return; |
| | 181 | | } |
| | 182 | |
|
| | 183 | | lock (_libraryChangedSyncLock) |
| | 184 | | { |
| 75 | 185 | | var updateDuration = TimeSpan.FromSeconds(_configurationManager.Configuration.LibraryUpdateDuration); |
| | 186 | |
|
| 75 | 187 | | if (_libraryUpdateTimer is null) |
| | 188 | | { |
| 21 | 189 | | _libraryUpdateTimer = new Timer(LibraryUpdateTimerCallback, null, updateDuration, Timeout.InfiniteTimeSp |
| | 190 | | } |
| | 191 | | else |
| | 192 | | { |
| 54 | 193 | | _libraryUpdateTimer.Change(updateDuration, Timeout.InfiniteTimeSpan); |
| | 194 | | } |
| | 195 | |
|
| 75 | 196 | | if (foldersList is not null && parent is Folder folder) |
| | 197 | | { |
| 4 | 198 | | foldersList.Add(folder); |
| | 199 | | } |
| | 200 | |
|
| 75 | 201 | | itemsList.Add(item); |
| 75 | 202 | | } |
| 75 | 203 | | } |
| | 204 | |
|
| | 205 | | private async void LibraryUpdateTimerCallback(object? state) |
| | 206 | | { |
| | 207 | | List<Folder> foldersAddedTo; |
| | 208 | | List<Folder> foldersRemovedFrom; |
| | 209 | | List<BaseItem> itemsUpdated; |
| | 210 | | List<BaseItem> itemsAdded; |
| | 211 | | List<BaseItem> itemsRemoved; |
| | 212 | | lock (_libraryChangedSyncLock) |
| | 213 | | { |
| | 214 | | // Remove dupes in case some were saved multiple times |
| | 215 | | foldersAddedTo = _foldersAddedTo |
| | 216 | | .DistinctBy(x => x.Id) |
| | 217 | | .ToList(); |
| | 218 | |
|
| | 219 | | foldersRemovedFrom = _foldersRemovedFrom |
| | 220 | | .DistinctBy(x => x.Id) |
| | 221 | | .ToList(); |
| | 222 | |
|
| | 223 | | itemsUpdated = _itemsUpdated |
| | 224 | | .Where(i => !_itemsAdded.Contains(i)) |
| | 225 | | .DistinctBy(x => x.Id) |
| | 226 | | .ToList(); |
| | 227 | |
|
| | 228 | | itemsAdded = _itemsAdded.ToList(); |
| | 229 | | itemsRemoved = _itemsRemoved.ToList(); |
| | 230 | |
|
| | 231 | | if (_libraryUpdateTimer is not null) |
| | 232 | | { |
| | 233 | | _libraryUpdateTimer.Dispose(); |
| | 234 | | _libraryUpdateTimer = null; |
| | 235 | | } |
| | 236 | |
|
| | 237 | | _itemsAdded.Clear(); |
| | 238 | | _itemsRemoved.Clear(); |
| | 239 | | _itemsUpdated.Clear(); |
| | 240 | | _foldersAddedTo.Clear(); |
| | 241 | | _foldersRemovedFrom.Clear(); |
| | 242 | | } |
| | 243 | |
|
| | 244 | | await SendChangeNotifications(itemsAdded, itemsUpdated, itemsRemoved, foldersAddedTo, foldersRemovedFrom, Cancel |
| | 245 | | } |
| | 246 | |
|
| | 247 | | private async Task SendChangeNotifications( |
| | 248 | | List<BaseItem> itemsAdded, |
| | 249 | | List<BaseItem> itemsUpdated, |
| | 250 | | List<BaseItem> itemsRemoved, |
| | 251 | | List<Folder> foldersAddedTo, |
| | 252 | | List<Folder> foldersRemovedFrom, |
| | 253 | | CancellationToken cancellationToken) |
| | 254 | | { |
| | 255 | | var userIds = _sessionManager.Sessions |
| | 256 | | .Select(i => i.UserId) |
| | 257 | | .Where(i => !i.IsEmpty()) |
| | 258 | | .Distinct() |
| | 259 | | .ToArray(); |
| | 260 | |
|
| | 261 | | foreach (var userId in userIds) |
| | 262 | | { |
| | 263 | | LibraryUpdateInfo info; |
| | 264 | |
|
| | 265 | | try |
| | 266 | | { |
| | 267 | | info = GetLibraryUpdateInfo(itemsAdded, itemsUpdated, itemsRemoved, foldersAddedTo, foldersRemovedFrom, |
| | 268 | | } |
| | 269 | | catch (Exception ex) |
| | 270 | | { |
| | 271 | | _logger.LogError(ex, "Error in GetLibraryUpdateInfo"); |
| | 272 | | return; |
| | 273 | | } |
| | 274 | |
|
| | 275 | | if (info.IsEmpty) |
| | 276 | | { |
| | 277 | | continue; |
| | 278 | | } |
| | 279 | |
|
| | 280 | | try |
| | 281 | | { |
| | 282 | | await _sessionManager.SendMessageToUserSessions( |
| | 283 | | new List<Guid> { userId }, |
| | 284 | | SessionMessageType.LibraryChanged, |
| | 285 | | info, |
| | 286 | | cancellationToken) |
| | 287 | | .ConfigureAwait(false); |
| | 288 | | } |
| | 289 | | catch (Exception ex) |
| | 290 | | { |
| | 291 | | _logger.LogError(ex, "Error sending LibraryChanged message"); |
| | 292 | | } |
| | 293 | | } |
| | 294 | | } |
| | 295 | |
|
| | 296 | | private LibraryUpdateInfo GetLibraryUpdateInfo( |
| | 297 | | List<BaseItem> itemsAdded, |
| | 298 | | List<BaseItem> itemsUpdated, |
| | 299 | | List<BaseItem> itemsRemoved, |
| | 300 | | List<Folder> foldersAddedTo, |
| | 301 | | List<Folder> foldersRemovedFrom, |
| | 302 | | Guid userId) |
| | 303 | | { |
| 0 | 304 | | var user = _userManager.GetUserById(userId); |
| 0 | 305 | | ArgumentNullException.ThrowIfNull(user); |
| | 306 | |
|
| 0 | 307 | | var newAndRemoved = new List<BaseItem>(); |
| 0 | 308 | | newAndRemoved.AddRange(foldersAddedTo); |
| 0 | 309 | | newAndRemoved.AddRange(foldersRemovedFrom); |
| | 310 | |
|
| 0 | 311 | | var allUserRootChildren = _libraryManager.GetUserRootFolder() |
| 0 | 312 | | .GetChildren(user, true) |
| 0 | 313 | | .OfType<Folder>() |
| 0 | 314 | | .ToList(); |
| | 315 | |
|
| 0 | 316 | | return new LibraryUpdateInfo |
| 0 | 317 | | { |
| 0 | 318 | | ItemsAdded = itemsAdded.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user)) |
| 0 | 319 | | .Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture)) |
| 0 | 320 | | .Distinct() |
| 0 | 321 | | .ToArray(), |
| 0 | 322 | | ItemsUpdated = itemsUpdated.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user)) |
| 0 | 323 | | .Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture)) |
| 0 | 324 | | .Distinct() |
| 0 | 325 | | .ToArray(), |
| 0 | 326 | | ItemsRemoved = itemsRemoved.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user, true)) |
| 0 | 327 | | .Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture)) |
| 0 | 328 | | .Distinct() |
| 0 | 329 | | .ToArray(), |
| 0 | 330 | | FoldersAddedTo = foldersAddedTo.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user)) |
| 0 | 331 | | .Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture)) |
| 0 | 332 | | .Distinct() |
| 0 | 333 | | .ToArray(), |
| 0 | 334 | | FoldersRemovedFrom = foldersRemovedFrom.SelectMany(i => TranslatePhysicalItemToUserLibrary(i, user)) |
| 0 | 335 | | .Select(i => i.Id.ToString("N", CultureInfo.InvariantCulture)) |
| 0 | 336 | | .Distinct() |
| 0 | 337 | | .ToArray(), |
| 0 | 338 | | CollectionFolders = GetTopParentIds(newAndRemoved, allUserRootChildren).ToArray() |
| 0 | 339 | | }; |
| | 340 | | } |
| | 341 | |
|
| | 342 | | private static bool FilterItem(BaseItem item) |
| | 343 | | { |
| 75 | 344 | | if (!item.IsFolder && !item.HasPathProtocol) |
| | 345 | | { |
| 0 | 346 | | return false; |
| | 347 | | } |
| | 348 | |
|
| 75 | 349 | | if (item is IItemByName && item is not MusicArtist) |
| | 350 | | { |
| 0 | 351 | | return false; |
| | 352 | | } |
| | 353 | |
|
| 75 | 354 | | return item.SourceType == SourceType.Library; |
| | 355 | | } |
| | 356 | |
|
| | 357 | | private static IEnumerable<string> GetTopParentIds(List<BaseItem> items, List<Folder> allUserRootChildren) |
| | 358 | | { |
| 0 | 359 | | var list = new List<string>(); |
| | 360 | |
|
| 0 | 361 | | foreach (var item in items) |
| | 362 | | { |
| | 363 | | // If the physical root changed, return the user root |
| 0 | 364 | | if (item is AggregateFolder) |
| | 365 | | { |
| | 366 | | continue; |
| | 367 | | } |
| | 368 | |
|
| 0 | 369 | | foreach (var folder in allUserRootChildren) |
| | 370 | | { |
| 0 | 371 | | list.Add(folder.Id.ToString("N", CultureInfo.InvariantCulture)); |
| | 372 | | } |
| | 373 | | } |
| | 374 | |
|
| 0 | 375 | | return list.Distinct(StringComparer.Ordinal); |
| | 376 | | } |
| | 377 | |
|
| | 378 | | private T[] TranslatePhysicalItemToUserLibrary<T>(T item, User user, bool includeIfNotFound = false) |
| | 379 | | where T : BaseItem |
| | 380 | | { |
| | 381 | | // If the physical root changed, return the user root |
| 0 | 382 | | if (item is AggregateFolder) |
| | 383 | | { |
| 0 | 384 | | return _libraryManager.GetUserRootFolder() is T t ? new[] { t } : Array.Empty<T>(); |
| | 385 | | } |
| | 386 | |
|
| | 387 | | // Return it only if it's in the user's library |
| 0 | 388 | | if (includeIfNotFound || item.IsVisibleStandalone(user)) |
| | 389 | | { |
| 0 | 390 | | return new[] { item }; |
| | 391 | | } |
| | 392 | |
|
| 0 | 393 | | return Array.Empty<T>(); |
| | 394 | | } |
| | 395 | |
|
| | 396 | | /// <inheritdoc /> |
| | 397 | | public void Dispose() |
| | 398 | | { |
| 21 | 399 | | _libraryUpdateTimer?.Dispose(); |
| 21 | 400 | | _libraryUpdateTimer = null; |
| 21 | 401 | | } |
| | 402 | | } |