FileRefresher.cs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Threading;
  7. using MediaBrowser.Controller.Configuration;
  8. using MediaBrowser.Controller.Entities;
  9. using MediaBrowser.Controller.Library;
  10. using Microsoft.Extensions.Logging;
  11. namespace Emby.Server.Implementations.IO
  12. {
  13. public sealed class FileRefresher : IDisposable
  14. {
  15. private readonly ILogger _logger;
  16. private readonly ILibraryManager _libraryManager;
  17. private readonly IServerConfigurationManager _configurationManager;
  18. private readonly List<string> _affectedPaths = new();
  19. private readonly Lock _timerLock = new();
  20. private Timer? _timer;
  21. private bool _disposed;
  22. public FileRefresher(string path, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, ILogger logger)
  23. {
  24. logger.LogDebug("New file refresher created for {0}", path);
  25. Path = path;
  26. _configurationManager = configurationManager;
  27. _libraryManager = libraryManager;
  28. _logger = logger;
  29. AddPath(path);
  30. }
  31. public event EventHandler<EventArgs>? Completed;
  32. public string Path { get; private set; }
  33. private void AddAffectedPath(string path)
  34. {
  35. ArgumentException.ThrowIfNullOrEmpty(path);
  36. if (!_affectedPaths.Contains(path, StringComparer.Ordinal))
  37. {
  38. _affectedPaths.Add(path);
  39. }
  40. }
  41. public void AddPath(string path)
  42. {
  43. ArgumentException.ThrowIfNullOrEmpty(path);
  44. lock (_timerLock)
  45. {
  46. AddAffectedPath(path);
  47. }
  48. RestartTimer();
  49. }
  50. public void RestartTimer()
  51. {
  52. if (_disposed)
  53. {
  54. return;
  55. }
  56. lock (_timerLock)
  57. {
  58. if (_disposed)
  59. {
  60. return;
  61. }
  62. if (_timer is null)
  63. {
  64. _timer = new Timer(OnTimerCallback, null, TimeSpan.FromSeconds(_configurationManager.Configuration.LibraryMonitorDelay), TimeSpan.FromMilliseconds(-1));
  65. }
  66. else
  67. {
  68. _timer.Change(TimeSpan.FromSeconds(_configurationManager.Configuration.LibraryMonitorDelay), TimeSpan.FromMilliseconds(-1));
  69. }
  70. }
  71. }
  72. public void ResetPath(string path, string? affectedFile)
  73. {
  74. lock (_timerLock)
  75. {
  76. _logger.LogDebug("Resetting file refresher from {0} to {1}", Path, path);
  77. Path = path;
  78. AddAffectedPath(path);
  79. if (!string.IsNullOrEmpty(affectedFile))
  80. {
  81. AddAffectedPath(affectedFile);
  82. }
  83. }
  84. RestartTimer();
  85. }
  86. private void OnTimerCallback(object? state)
  87. {
  88. List<string> paths;
  89. lock (_timerLock)
  90. {
  91. paths = _affectedPaths.ToList();
  92. }
  93. _logger.LogDebug("Timer stopped.");
  94. DisposeTimer();
  95. Completed?.Invoke(this, EventArgs.Empty);
  96. try
  97. {
  98. ProcessPathChanges(paths);
  99. }
  100. catch (Exception ex)
  101. {
  102. _logger.LogError(ex, "Error processing directory changes");
  103. }
  104. }
  105. private void ProcessPathChanges(List<string> paths)
  106. {
  107. IEnumerable<BaseItem> itemsToRefresh = paths
  108. .Distinct()
  109. .Select(GetAffectedBaseItem)
  110. .Where(item => item is not null)
  111. .DistinctBy(x => x!.Id)!; // Removed null values in the previous .Where()
  112. foreach (var item in itemsToRefresh)
  113. {
  114. if (item is AggregateFolder)
  115. {
  116. continue;
  117. }
  118. _logger.LogInformation("{Name} ({Path}) will be refreshed.", item.Name, item.Path);
  119. try
  120. {
  121. item.ChangedExternally();
  122. }
  123. catch (Exception ex)
  124. {
  125. _logger.LogError(ex, "Error refreshing {Name}", item.Name);
  126. }
  127. }
  128. }
  129. /// <summary>
  130. /// Gets the affected base item.
  131. /// </summary>
  132. /// <param name="path">The path.</param>
  133. /// <returns>BaseItem.</returns>
  134. private BaseItem? GetAffectedBaseItem(string path)
  135. {
  136. BaseItem? item = null;
  137. while (item is null && !string.IsNullOrEmpty(path))
  138. {
  139. item = _libraryManager.FindByPath(path, null);
  140. path = System.IO.Path.GetDirectoryName(path) ?? string.Empty;
  141. }
  142. if (item is not null)
  143. {
  144. // If the item has been deleted find the first valid parent that still exists
  145. while (!Directory.Exists(item.Path) && !File.Exists(item.Path))
  146. {
  147. item = item.GetOwner() ?? item.GetParent();
  148. if (item is null)
  149. {
  150. break;
  151. }
  152. }
  153. }
  154. return item;
  155. }
  156. private void DisposeTimer()
  157. {
  158. lock (_timerLock)
  159. {
  160. if (_timer is not null)
  161. {
  162. _timer.Dispose();
  163. _timer = null;
  164. }
  165. }
  166. }
  167. /// <inheritdoc />
  168. public void Dispose()
  169. {
  170. if (_disposed)
  171. {
  172. return;
  173. }
  174. DisposeTimer();
  175. _disposed = true;
  176. }
  177. }
  178. }