FileRefresher.cs 9.4 KB

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