FileRefresher.cs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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 List<string>();
  19. private readonly object _timerLock = new object();
  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(StringComparer.OrdinalIgnoreCase)
  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 (IOException ex)
  124. {
  125. // For now swallow and log.
  126. // Research item: If an IOException occurs, the item may be in a disconnected state (media unavailable)
  127. // Should we remove it from it's parent?
  128. _logger.LogError(ex, "Error refreshing {Name}", item.Name);
  129. }
  130. catch (Exception ex)
  131. {
  132. _logger.LogError(ex, "Error refreshing {Name}", item.Name);
  133. }
  134. }
  135. }
  136. /// <summary>
  137. /// Gets the affected base item.
  138. /// </summary>
  139. /// <param name="path">The path.</param>
  140. /// <returns>BaseItem.</returns>
  141. private BaseItem? GetAffectedBaseItem(string path)
  142. {
  143. BaseItem? item = null;
  144. while (item is null && !string.IsNullOrEmpty(path))
  145. {
  146. item = _libraryManager.FindByPath(path, null);
  147. path = System.IO.Path.GetDirectoryName(path) ?? string.Empty;
  148. }
  149. if (item is not null)
  150. {
  151. // If the item has been deleted find the first valid parent that still exists
  152. while (!Directory.Exists(item.Path) && !File.Exists(item.Path))
  153. {
  154. item = item.GetOwner() ?? item.GetParent();
  155. if (item is null)
  156. {
  157. break;
  158. }
  159. }
  160. }
  161. return item;
  162. }
  163. private void DisposeTimer()
  164. {
  165. lock (_timerLock)
  166. {
  167. if (_timer is not null)
  168. {
  169. _timer.Dispose();
  170. _timer = null;
  171. }
  172. }
  173. }
  174. /// <inheritdoc />
  175. public void Dispose()
  176. {
  177. if (_disposed)
  178. {
  179. return;
  180. }
  181. DisposeTimer();
  182. _disposed = true;
  183. GC.SuppressFinalize(this);
  184. }
  185. }
  186. }