FileRefresher.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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 CommonIO;
  8. using MediaBrowser.Common.Events;
  9. using MediaBrowser.Common.ScheduledTasks;
  10. using MediaBrowser.Controller.Configuration;
  11. using MediaBrowser.Controller.Entities;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Model.Logging;
  14. using MediaBrowser.Server.Implementations.ScheduledTasks;
  15. namespace MediaBrowser.Server.Implementations.IO
  16. {
  17. public class FileRefresher : IDisposable
  18. {
  19. private ILogger Logger { get; set; }
  20. private ITaskManager TaskManager { get; set; }
  21. private ILibraryManager LibraryManager { get; set; }
  22. private IServerConfigurationManager ConfigurationManager { get; set; }
  23. private readonly IFileSystem _fileSystem;
  24. private readonly List<string> _affectedPaths = new List<string>();
  25. private Timer _timer;
  26. private readonly object _timerLock = new object();
  27. public string Path { get; private set; }
  28. public event EventHandler<EventArgs> Completed;
  29. public FileRefresher(string path, IFileSystem fileSystem, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, ITaskManager taskManager, ILogger logger)
  30. {
  31. logger.Debug("New file refresher created for {0}", path);
  32. Path = path;
  33. _affectedPaths.Add(path);
  34. _fileSystem = fileSystem;
  35. ConfigurationManager = configurationManager;
  36. LibraryManager = libraryManager;
  37. TaskManager = taskManager;
  38. Logger = logger;
  39. }
  40. private void AddAffectedPath(string path)
  41. {
  42. if (!_affectedPaths.Contains(path, StringComparer.Ordinal))
  43. {
  44. _affectedPaths.Add(path);
  45. }
  46. }
  47. public void AddPath(string path)
  48. {
  49. lock (_timerLock)
  50. {
  51. AddAffectedPath(path);
  52. }
  53. RestartTimer();
  54. }
  55. public void RestartTimer()
  56. {
  57. lock (_timerLock)
  58. {
  59. if (_timer == null)
  60. {
  61. _timer = new Timer(OnTimerCallback, null, TimeSpan.FromSeconds(ConfigurationManager.Configuration.LibraryMonitorDelay), TimeSpan.FromMilliseconds(-1));
  62. }
  63. else
  64. {
  65. _timer.Change(TimeSpan.FromSeconds(ConfigurationManager.Configuration.LibraryMonitorDelay), TimeSpan.FromMilliseconds(-1));
  66. }
  67. }
  68. }
  69. public void ResetPath(string path, string affectedFile)
  70. {
  71. lock (_timerLock)
  72. {
  73. Logger.Debug("Resetting file refresher from {0} to {1}", Path, path);
  74. Path = path;
  75. AddAffectedPath(path);
  76. if (!string.IsNullOrWhiteSpace(affectedFile))
  77. {
  78. AddAffectedPath(affectedFile);
  79. }
  80. }
  81. RestartTimer();
  82. }
  83. private async void OnTimerCallback(object state)
  84. {
  85. List<string> paths;
  86. lock (_timerLock)
  87. {
  88. paths = _affectedPaths.ToList();
  89. }
  90. // Extend the timer as long as any of the paths are still being written to.
  91. if (paths.Any(IsFileLocked))
  92. {
  93. Logger.Info("Timer extended.");
  94. RestartTimer();
  95. return;
  96. }
  97. Logger.Debug("Timer stopped.");
  98. DisposeTimer();
  99. EventHelper.FireEventIfNotNull(Completed, this, EventArgs.Empty, Logger);
  100. try
  101. {
  102. await ProcessPathChanges(paths.ToList()).ConfigureAwait(false);
  103. }
  104. catch (Exception ex)
  105. {
  106. Logger.ErrorException("Error processing directory changes", ex);
  107. }
  108. }
  109. private async Task ProcessPathChanges(List<string> paths)
  110. {
  111. var itemsToRefresh = paths
  112. .Select(GetAffectedBaseItem)
  113. .Where(item => item != null)
  114. .Distinct()
  115. .ToList();
  116. foreach (var p in paths)
  117. {
  118. Logger.Info(p + " reports change.");
  119. }
  120. // If the root folder changed, run the library task so the user can see it
  121. if (itemsToRefresh.Any(i => i is AggregateFolder))
  122. {
  123. TaskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  124. return;
  125. }
  126. foreach (var item in itemsToRefresh)
  127. {
  128. Logger.Info(item.Name + " (" + item.Path + ") will be refreshed.");
  129. try
  130. {
  131. await item.ChangedExternally().ConfigureAwait(false);
  132. }
  133. catch (IOException ex)
  134. {
  135. // For now swallow and log.
  136. // Research item: If an IOException occurs, the item may be in a disconnected state (media unavailable)
  137. // Should we remove it from it's parent?
  138. Logger.ErrorException("Error refreshing {0}", ex, item.Name);
  139. }
  140. catch (Exception ex)
  141. {
  142. Logger.ErrorException("Error refreshing {0}", ex, item.Name);
  143. }
  144. }
  145. }
  146. /// <summary>
  147. /// Gets the affected base item.
  148. /// </summary>
  149. /// <param name="path">The path.</param>
  150. /// <returns>BaseItem.</returns>
  151. private BaseItem GetAffectedBaseItem(string path)
  152. {
  153. BaseItem item = null;
  154. while (item == null && !string.IsNullOrEmpty(path))
  155. {
  156. item = LibraryManager.FindByPath(path, null);
  157. path = System.IO.Path.GetDirectoryName(path);
  158. }
  159. if (item != null)
  160. {
  161. // If the item has been deleted find the first valid parent that still exists
  162. while (!_fileSystem.DirectoryExists(item.Path) && !_fileSystem.FileExists(item.Path))
  163. {
  164. item = item.GetParent();
  165. if (item == null)
  166. {
  167. break;
  168. }
  169. }
  170. }
  171. return item;
  172. }
  173. private bool IsFileLocked(string path)
  174. {
  175. if (Environment.OSVersion.Platform != PlatformID.Win32NT)
  176. {
  177. // Causing lockups on linux
  178. return false;
  179. }
  180. try
  181. {
  182. var data = _fileSystem.GetFileSystemInfo(path);
  183. if (!data.Exists
  184. || data.IsDirectory
  185. // Opening a writable stream will fail with readonly files
  186. || data.Attributes.HasFlag(FileAttributes.ReadOnly))
  187. {
  188. return false;
  189. }
  190. }
  191. catch (IOException)
  192. {
  193. return false;
  194. }
  195. catch (Exception ex)
  196. {
  197. Logger.ErrorException("Error getting file system info for: {0}", ex, path);
  198. return false;
  199. }
  200. // In order to determine if the file is being written to, we have to request write access
  201. // But if the server only has readonly access, this is going to cause this entire algorithm to fail
  202. // So we'll take a best guess about our access level
  203. var requestedFileAccess = ConfigurationManager.Configuration.SaveLocalMeta
  204. ? FileAccess.ReadWrite
  205. : FileAccess.Read;
  206. try
  207. {
  208. using (_fileSystem.GetFileStream(path, FileMode.Open, requestedFileAccess, FileShare.ReadWrite))
  209. {
  210. //file is not locked
  211. return false;
  212. }
  213. }
  214. catch (DirectoryNotFoundException)
  215. {
  216. // File may have been deleted
  217. return false;
  218. }
  219. catch (FileNotFoundException)
  220. {
  221. // File may have been deleted
  222. return false;
  223. }
  224. catch (IOException)
  225. {
  226. //the file is unavailable because it is:
  227. //still being written to
  228. //or being processed by another thread
  229. //or does not exist (has already been processed)
  230. Logger.Debug("{0} is locked.", path);
  231. return true;
  232. }
  233. catch (Exception ex)
  234. {
  235. Logger.ErrorException("Error determining if file is locked: {0}", ex, path);
  236. return false;
  237. }
  238. }
  239. private void DisposeTimer()
  240. {
  241. lock (_timerLock)
  242. {
  243. if (_timer != null)
  244. {
  245. _timer.Dispose();
  246. }
  247. }
  248. }
  249. public void Dispose()
  250. {
  251. DisposeTimer();
  252. }
  253. }
  254. }