FileRefresher.cs 6.3 KB

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