FileRefresher.cs 9.5 KB

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