FileRefresher.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. if (string.IsNullOrEmpty(path))
  36. {
  37. throw new ArgumentNullException(nameof(path));
  38. }
  39. if (!_affectedPaths.Contains(path, StringComparer.Ordinal))
  40. {
  41. _affectedPaths.Add(path);
  42. }
  43. }
  44. public void AddPath(string path)
  45. {
  46. if (string.IsNullOrEmpty(path))
  47. {
  48. throw new ArgumentNullException(nameof(path));
  49. }
  50. lock (_timerLock)
  51. {
  52. AddAffectedPath(path);
  53. }
  54. RestartTimer();
  55. }
  56. public void RestartTimer()
  57. {
  58. if (_disposed)
  59. {
  60. return;
  61. }
  62. lock (_timerLock)
  63. {
  64. if (_disposed)
  65. {
  66. return;
  67. }
  68. if (_timer is null)
  69. {
  70. _timer = new Timer(OnTimerCallback, null, TimeSpan.FromSeconds(_configurationManager.Configuration.LibraryMonitorDelay), TimeSpan.FromMilliseconds(-1));
  71. }
  72. else
  73. {
  74. _timer.Change(TimeSpan.FromSeconds(_configurationManager.Configuration.LibraryMonitorDelay), TimeSpan.FromMilliseconds(-1));
  75. }
  76. }
  77. }
  78. public void ResetPath(string path, string affectedFile)
  79. {
  80. lock (_timerLock)
  81. {
  82. _logger.LogDebug("Resetting file refresher from {0} to {1}", Path, path);
  83. Path = path;
  84. AddAffectedPath(path);
  85. if (!string.IsNullOrEmpty(affectedFile))
  86. {
  87. AddAffectedPath(affectedFile);
  88. }
  89. }
  90. RestartTimer();
  91. }
  92. private void OnTimerCallback(object? state)
  93. {
  94. List<string> paths;
  95. lock (_timerLock)
  96. {
  97. paths = _affectedPaths.ToList();
  98. }
  99. _logger.LogDebug("Timer stopped.");
  100. DisposeTimer();
  101. Completed?.Invoke(this, EventArgs.Empty);
  102. try
  103. {
  104. ProcessPathChanges(paths);
  105. }
  106. catch (Exception ex)
  107. {
  108. _logger.LogError(ex, "Error processing directory changes");
  109. }
  110. }
  111. private void ProcessPathChanges(List<string> paths)
  112. {
  113. IEnumerable<BaseItem> itemsToRefresh = paths
  114. .Distinct(StringComparer.OrdinalIgnoreCase)
  115. .Select(GetAffectedBaseItem)
  116. .Where(item => item is not null)
  117. .GroupBy(x => x!.Id) // Removed null values in the previous .Where()
  118. .Select(x => x.First())!;
  119. foreach (var item in itemsToRefresh)
  120. {
  121. if (item is AggregateFolder)
  122. {
  123. continue;
  124. }
  125. _logger.LogInformation("{Name} ({Path}) will be refreshed.", item.Name, item.Path);
  126. try
  127. {
  128. item.ChangedExternally();
  129. }
  130. catch (IOException ex)
  131. {
  132. // For now swallow and log.
  133. // Research item: If an IOException occurs, the item may be in a disconnected state (media unavailable)
  134. // Should we remove it from it's parent?
  135. _logger.LogError(ex, "Error refreshing {Name}", item.Name);
  136. }
  137. catch (Exception ex)
  138. {
  139. _logger.LogError(ex, "Error refreshing {Name}", item.Name);
  140. }
  141. }
  142. }
  143. /// <summary>
  144. /// Gets the affected base item.
  145. /// </summary>
  146. /// <param name="path">The path.</param>
  147. /// <returns>BaseItem.</returns>
  148. private BaseItem? GetAffectedBaseItem(string path)
  149. {
  150. BaseItem? item = null;
  151. while (item is null && !string.IsNullOrEmpty(path))
  152. {
  153. item = _libraryManager.FindByPath(path, null);
  154. path = System.IO.Path.GetDirectoryName(path) ?? string.Empty;
  155. }
  156. if (item is not null)
  157. {
  158. // If the item has been deleted find the first valid parent that still exists
  159. while (!Directory.Exists(item.Path) && !File.Exists(item.Path))
  160. {
  161. item = item.GetOwner() ?? item.GetParent();
  162. if (item is null)
  163. {
  164. break;
  165. }
  166. }
  167. }
  168. return item;
  169. }
  170. private void DisposeTimer()
  171. {
  172. lock (_timerLock)
  173. {
  174. if (_timer is not null)
  175. {
  176. _timer.Dispose();
  177. _timer = null;
  178. }
  179. }
  180. }
  181. /// <inheritdoc />
  182. public void Dispose()
  183. {
  184. if (_disposed)
  185. {
  186. return;
  187. }
  188. DisposeTimer();
  189. _disposed = true;
  190. GC.SuppressFinalize(this);
  191. }
  192. }
  193. }