FileRefresher.cs 7.0 KB

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