FileRefresher.cs 6.8 KB

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