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