FileRefresher.cs 7.5 KB

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