FileRefresher.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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 Microsoft.Extensions.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.LogDebug("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.IsNullOrEmpty(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.IsNullOrEmpty(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.LogDebug("Resetting file refresher from {0} to {1}", Path, path);
  100. Path = path;
  101. AddAffectedPath(path);
  102. if (!string.IsNullOrEmpty(affectedFile))
  103. {
  104. AddAffectedPath(affectedFile);
  105. }
  106. }
  107. RestartTimer();
  108. }
  109. private void OnTimerCallback(object state)
  110. {
  111. List<string> paths;
  112. lock (_timerLock)
  113. {
  114. paths = _affectedPaths.ToList();
  115. }
  116. Logger.LogDebug("Timer stopped.");
  117. DisposeTimer();
  118. EventHelper.FireEventIfNotNull(Completed, this, EventArgs.Empty, Logger);
  119. try
  120. {
  121. ProcessPathChanges(paths.ToList());
  122. }
  123. catch (Exception ex)
  124. {
  125. Logger.LogError("Error processing directory changes", ex);
  126. }
  127. }
  128. private void 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 item in itemsToRefresh)
  137. {
  138. if (item is AggregateFolder)
  139. {
  140. continue;
  141. }
  142. Logger.LogInformation(item.Name + " (" + item.Path + ") will be refreshed.");
  143. try
  144. {
  145. item.ChangedExternally();
  146. }
  147. catch (IOException ex)
  148. {
  149. // For now swallow and log.
  150. // Research item: If an IOException occurs, the item may be in a disconnected state (media unavailable)
  151. // Should we remove it from it's parent?
  152. Logger.LogError("Error refreshing {0}", ex, item.Name);
  153. }
  154. catch (Exception ex)
  155. {
  156. Logger.LogError("Error refreshing {0}", ex, item.Name);
  157. }
  158. }
  159. }
  160. /// <summary>
  161. /// Gets the affected base item.
  162. /// </summary>
  163. /// <param name="path">The path.</param>
  164. /// <returns>BaseItem.</returns>
  165. private BaseItem GetAffectedBaseItem(string path)
  166. {
  167. BaseItem item = null;
  168. while (item == null && !string.IsNullOrEmpty(path))
  169. {
  170. item = LibraryManager.FindByPath(path, null);
  171. path = _fileSystem.GetDirectoryName(path);
  172. }
  173. if (item != null)
  174. {
  175. // If the item has been deleted find the first valid parent that still exists
  176. while (!_fileSystem.DirectoryExists(item.Path) && !_fileSystem.FileExists(item.Path))
  177. {
  178. item = item.GetOwner() ?? item.GetParent();
  179. if (item == null)
  180. {
  181. break;
  182. }
  183. }
  184. }
  185. return item;
  186. }
  187. private void DisposeTimer()
  188. {
  189. lock (_timerLock)
  190. {
  191. if (_timer != null)
  192. {
  193. _timer.Dispose();
  194. _timer = null;
  195. }
  196. }
  197. }
  198. private bool _disposed;
  199. public void Dispose()
  200. {
  201. _disposed = true;
  202. DisposeTimer();
  203. }
  204. }
  205. }