DirectoryWatchers.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.ScheduledTasks;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Controller.ScheduledTasks;
  6. using MediaBrowser.Model.Logging;
  7. using System;
  8. using System.Collections.Concurrent;
  9. using System.Collections.Generic;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. namespace MediaBrowser.Controller.IO
  15. {
  16. /// <summary>
  17. /// Class DirectoryWatchers
  18. /// </summary>
  19. public class DirectoryWatchers : IDisposable
  20. {
  21. /// <summary>
  22. /// The file system watchers
  23. /// </summary>
  24. private ConcurrentBag<FileSystemWatcher> FileSystemWatchers = new ConcurrentBag<FileSystemWatcher>();
  25. /// <summary>
  26. /// The update timer
  27. /// </summary>
  28. private Timer updateTimer;
  29. /// <summary>
  30. /// The affected paths
  31. /// </summary>
  32. private readonly ConcurrentDictionary<string, string> affectedPaths = new ConcurrentDictionary<string, string>();
  33. /// <summary>
  34. /// A dynamic list of paths that should be ignored. Added to during our own file sytem modifications.
  35. /// </summary>
  36. private readonly ConcurrentDictionary<string,string> TempIgnoredPaths = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  37. /// <summary>
  38. /// The timer lock
  39. /// </summary>
  40. private readonly object timerLock = new object();
  41. /// <summary>
  42. /// Add the path to our temporary ignore list. Use when writing to a path within our listening scope.
  43. /// </summary>
  44. /// <param name="path">The path.</param>
  45. public void TemporarilyIgnore(string path)
  46. {
  47. TempIgnoredPaths[path] = path;
  48. }
  49. /// <summary>
  50. /// Removes the temp ignore.
  51. /// </summary>
  52. /// <param name="path">The path.</param>
  53. public void RemoveTempIgnore(string path)
  54. {
  55. string val;
  56. TempIgnoredPaths.TryRemove(path, out val);
  57. }
  58. /// <summary>
  59. /// Gets or sets the logger.
  60. /// </summary>
  61. /// <value>The logger.</value>
  62. private ILogger Logger { get; set; }
  63. /// <summary>
  64. /// Gets or sets the task manager.
  65. /// </summary>
  66. /// <value>The task manager.</value>
  67. private ITaskManager TaskManager { get; set; }
  68. private ILibraryManager LibraryManager { get; set; }
  69. /// <summary>
  70. /// Initializes a new instance of the <see cref="DirectoryWatchers" /> class.
  71. /// </summary>
  72. public DirectoryWatchers(ILogger logger, ITaskManager taskManager, ILibraryManager libraryManager)
  73. {
  74. if (logger == null)
  75. {
  76. throw new ArgumentNullException("logger");
  77. }
  78. if (taskManager == null)
  79. {
  80. throw new ArgumentNullException("taskManager");
  81. }
  82. LibraryManager = libraryManager;
  83. TaskManager = taskManager;
  84. Logger = logger;
  85. }
  86. /// <summary>
  87. /// Starts this instance.
  88. /// </summary>
  89. internal void Start()
  90. {
  91. LibraryManager.LibraryChanged += Instance_LibraryChanged;
  92. var pathsToWatch = new List<string> { LibraryManager.RootFolder.Path };
  93. var paths = LibraryManager.RootFolder.Children.OfType<Folder>()
  94. .SelectMany(f =>
  95. {
  96. try
  97. {
  98. // Accessing ResolveArgs could involve file system access
  99. return f.ResolveArgs.PhysicalLocations;
  100. }
  101. catch (IOException)
  102. {
  103. return new string[] {};
  104. }
  105. })
  106. .Where(Path.IsPathRooted);
  107. foreach (var path in paths)
  108. {
  109. if (!ContainsParentFolder(pathsToWatch, path))
  110. {
  111. pathsToWatch.Add(path);
  112. }
  113. }
  114. foreach (var path in pathsToWatch)
  115. {
  116. StartWatchingPath(path);
  117. }
  118. }
  119. /// <summary>
  120. /// Examine a list of strings assumed to be file paths to see if it contains a parent of
  121. /// the provided path.
  122. /// </summary>
  123. /// <param name="lst">The LST.</param>
  124. /// <param name="path">The path.</param>
  125. /// <returns><c>true</c> if [contains parent folder] [the specified LST]; otherwise, <c>false</c>.</returns>
  126. /// <exception cref="System.ArgumentNullException">path</exception>
  127. private static bool ContainsParentFolder(IEnumerable<string> lst, string path)
  128. {
  129. if (string.IsNullOrEmpty(path))
  130. {
  131. throw new ArgumentNullException("path");
  132. }
  133. path = path.TrimEnd(Path.DirectorySeparatorChar);
  134. return lst.Any(str =>
  135. {
  136. //this should be a little quicker than examining each actual parent folder...
  137. var compare = str.TrimEnd(Path.DirectorySeparatorChar);
  138. return (path.Equals(compare, StringComparison.OrdinalIgnoreCase) || (path.StartsWith(compare, StringComparison.OrdinalIgnoreCase) && path[compare.Length] == Path.DirectorySeparatorChar));
  139. });
  140. }
  141. /// <summary>
  142. /// Starts the watching path.
  143. /// </summary>
  144. /// <param name="path">The path.</param>
  145. private void StartWatchingPath(string path)
  146. {
  147. // Creating a FileSystemWatcher over the LAN can take hundreds of milliseconds, so wrap it in a Task to do them all in parallel
  148. Task.Run(() =>
  149. {
  150. var newWatcher = new FileSystemWatcher(path, "*") { IncludeSubdirectories = true, InternalBufferSize = 32767 };
  151. newWatcher.Created += watcher_Changed;
  152. newWatcher.Deleted += watcher_Changed;
  153. newWatcher.Renamed += watcher_Changed;
  154. newWatcher.Changed += watcher_Changed;
  155. newWatcher.Error += watcher_Error;
  156. try
  157. {
  158. newWatcher.EnableRaisingEvents = true;
  159. FileSystemWatchers.Add(newWatcher);
  160. Logger.Info("Watching directory " + path);
  161. }
  162. catch (IOException ex)
  163. {
  164. Logger.ErrorException("Error watching path: {0}", ex, path);
  165. }
  166. catch (PlatformNotSupportedException ex)
  167. {
  168. Logger.ErrorException("Error watching path: {0}", ex, path);
  169. }
  170. });
  171. }
  172. /// <summary>
  173. /// Stops the watching path.
  174. /// </summary>
  175. /// <param name="path">The path.</param>
  176. private void StopWatchingPath(string path)
  177. {
  178. var watcher = FileSystemWatchers.FirstOrDefault(f => f.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  179. if (watcher != null)
  180. {
  181. DisposeWatcher(watcher);
  182. }
  183. }
  184. /// <summary>
  185. /// Disposes the watcher.
  186. /// </summary>
  187. /// <param name="watcher">The watcher.</param>
  188. private void DisposeWatcher(FileSystemWatcher watcher)
  189. {
  190. Logger.Info("Stopping directory watching for path {0}", watcher.Path);
  191. watcher.EnableRaisingEvents = false;
  192. watcher.Dispose();
  193. var watchers = FileSystemWatchers.ToList();
  194. watchers.Remove(watcher);
  195. FileSystemWatchers = new ConcurrentBag<FileSystemWatcher>(watchers);
  196. }
  197. /// <summary>
  198. /// Handles the LibraryChanged event of the Kernel
  199. /// </summary>
  200. /// <param name="sender">The source of the event.</param>
  201. /// <param name="e">The <see cref="Library.ChildrenChangedEventArgs" /> instance containing the event data.</param>
  202. void Instance_LibraryChanged(object sender, ChildrenChangedEventArgs e)
  203. {
  204. if (e.Folder is AggregateFolder && e.HasAddOrRemoveChange)
  205. {
  206. if (e.ItemsRemoved != null)
  207. {
  208. foreach (var item in e.ItemsRemoved.OfType<Folder>())
  209. {
  210. StopWatchingPath(item.Path);
  211. }
  212. }
  213. if (e.ItemsAdded != null)
  214. {
  215. foreach (var item in e.ItemsAdded.OfType<Folder>())
  216. {
  217. StartWatchingPath(item.Path);
  218. }
  219. }
  220. }
  221. }
  222. /// <summary>
  223. /// Handles the Error event of the watcher control.
  224. /// </summary>
  225. /// <param name="sender">The source of the event.</param>
  226. /// <param name="e">The <see cref="ErrorEventArgs" /> instance containing the event data.</param>
  227. async void watcher_Error(object sender, ErrorEventArgs e)
  228. {
  229. var ex = e.GetException();
  230. var dw = (FileSystemWatcher) sender;
  231. Logger.ErrorException("Error in Directory watcher for: "+dw.Path, ex);
  232. if (ex.Message.Contains("network name is no longer available"))
  233. {
  234. //Network either dropped or, we are coming out of sleep and it hasn't reconnected yet - wait and retry
  235. Logger.Warn("Network connection lost - will retry...");
  236. var retries = 0;
  237. var success = false;
  238. while (!success && retries < 10)
  239. {
  240. await Task.Delay(500).ConfigureAwait(false);
  241. try
  242. {
  243. dw.EnableRaisingEvents = false;
  244. dw.EnableRaisingEvents = true;
  245. success = true;
  246. }
  247. catch (IOException)
  248. {
  249. Logger.Warn("Network still unavailable...");
  250. retries++;
  251. }
  252. }
  253. if (!success)
  254. {
  255. Logger.Warn("Unable to access network. Giving up.");
  256. DisposeWatcher(dw);
  257. }
  258. }
  259. else
  260. {
  261. if (!ex.Message.Contains("BIOS command limit"))
  262. {
  263. Logger.Info("Attempting to re-start watcher.");
  264. dw.EnableRaisingEvents = false;
  265. dw.EnableRaisingEvents = true;
  266. }
  267. }
  268. }
  269. /// <summary>
  270. /// Handles the Changed event of the watcher control.
  271. /// </summary>
  272. /// <param name="sender">The source of the event.</param>
  273. /// <param name="e">The <see cref="FileSystemEventArgs" /> instance containing the event data.</param>
  274. void watcher_Changed(object sender, FileSystemEventArgs e)
  275. {
  276. if (e.ChangeType == WatcherChangeTypes.Created && e.Name == "New folder")
  277. {
  278. return;
  279. }
  280. if (TempIgnoredPaths.ContainsKey(e.FullPath))
  281. {
  282. Logger.Info("Watcher requested to ignore change to " + e.FullPath);
  283. return;
  284. }
  285. Logger.Info("Watcher sees change of type " + e.ChangeType.ToString() + " to " + e.FullPath);
  286. //Since we're watching created, deleted and renamed we always want the parent of the item to be the affected path
  287. var affectedPath = e.FullPath;
  288. affectedPaths.AddOrUpdate(affectedPath, affectedPath, (key, oldValue) => affectedPath);
  289. lock (timerLock)
  290. {
  291. if (updateTimer == null)
  292. {
  293. updateTimer = new Timer(TimerStopped, null, TimeSpan.FromSeconds(Kernel.Instance.Configuration.FileWatcherDelay), TimeSpan.FromMilliseconds(-1));
  294. }
  295. else
  296. {
  297. updateTimer.Change(TimeSpan.FromSeconds(Kernel.Instance.Configuration.FileWatcherDelay), TimeSpan.FromMilliseconds(-1));
  298. }
  299. }
  300. }
  301. /// <summary>
  302. /// Timers the stopped.
  303. /// </summary>
  304. /// <param name="stateInfo">The state info.</param>
  305. private async void TimerStopped(object stateInfo)
  306. {
  307. lock (timerLock)
  308. {
  309. // Extend the timer as long as any of the paths are still being written to.
  310. if (affectedPaths.Any(p => IsFileLocked(p.Key)))
  311. {
  312. Logger.Info("Timer extended.");
  313. updateTimer.Change(TimeSpan.FromSeconds(Kernel.Instance.Configuration.FileWatcherDelay), TimeSpan.FromMilliseconds(-1));
  314. return;
  315. }
  316. Logger.Info("Timer stopped.");
  317. updateTimer.Dispose();
  318. updateTimer = null;
  319. }
  320. var paths = affectedPaths.Keys.ToList();
  321. affectedPaths.Clear();
  322. await ProcessPathChanges(paths).ConfigureAwait(false);
  323. }
  324. /// <summary>
  325. /// Try and determine if a file is locked
  326. /// This is not perfect, and is subject to race conditions, so I'd rather not make this a re-usable library method.
  327. /// </summary>
  328. /// <param name="path">The path.</param>
  329. /// <returns><c>true</c> if [is file locked] [the specified path]; otherwise, <c>false</c>.</returns>
  330. private bool IsFileLocked(string path)
  331. {
  332. try
  333. {
  334. var data = FileSystem.GetFileData(path);
  335. if (!data.HasValue || data.Value.IsDirectory)
  336. {
  337. return false;
  338. }
  339. }
  340. catch (IOException)
  341. {
  342. return false;
  343. }
  344. FileStream stream = null;
  345. try
  346. {
  347. stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
  348. }
  349. catch
  350. {
  351. //the file is unavailable because it is:
  352. //still being written to
  353. //or being processed by another thread
  354. //or does not exist (has already been processed)
  355. return true;
  356. }
  357. finally
  358. {
  359. if (stream != null)
  360. stream.Close();
  361. }
  362. //file is not locked
  363. return false;
  364. }
  365. /// <summary>
  366. /// Processes the path changes.
  367. /// </summary>
  368. /// <param name="paths">The paths.</param>
  369. /// <returns>Task.</returns>
  370. private async Task ProcessPathChanges(List<string> paths)
  371. {
  372. var itemsToRefresh = paths.Select(Path.GetDirectoryName)
  373. .Select(GetAffectedBaseItem)
  374. .Where(item => item != null)
  375. .Distinct()
  376. .ToList();
  377. foreach (var p in paths) Logger.Info(p + " reports change.");
  378. // If the root folder changed, run the library task so the user can see it
  379. if (itemsToRefresh.Any(i => i is AggregateFolder))
  380. {
  381. TaskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  382. return;
  383. }
  384. await Task.WhenAll(itemsToRefresh.Select(i => Task.Run(async () =>
  385. {
  386. Logger.Info(i.Name + " (" + i.Path + ") will be refreshed.");
  387. try
  388. {
  389. await i.ChangedExternally().ConfigureAwait(false);
  390. }
  391. catch (IOException ex)
  392. {
  393. // For now swallow and log.
  394. // Research item: If an IOException occurs, the item may be in a disconnected state (media unavailable)
  395. // Should we remove it from it's parent?
  396. Logger.ErrorException("Error refreshing {0}", ex, i.Name);
  397. }
  398. }))).ConfigureAwait(false);
  399. }
  400. /// <summary>
  401. /// Gets the affected base item.
  402. /// </summary>
  403. /// <param name="path">The path.</param>
  404. /// <returns>BaseItem.</returns>
  405. private BaseItem GetAffectedBaseItem(string path)
  406. {
  407. BaseItem item = null;
  408. while (item == null && !string.IsNullOrEmpty(path))
  409. {
  410. item = LibraryManager.RootFolder.FindByPath(path);
  411. path = Path.GetDirectoryName(path);
  412. }
  413. if (item != null)
  414. {
  415. // If the item has been deleted find the first valid parent that still exists
  416. while (!Directory.Exists(item.Path) && !File.Exists(item.Path))
  417. {
  418. item = item.Parent;
  419. if (item == null)
  420. {
  421. break;
  422. }
  423. }
  424. }
  425. return item;
  426. }
  427. /// <summary>
  428. /// Stops this instance.
  429. /// </summary>
  430. private void Stop()
  431. {
  432. LibraryManager.LibraryChanged -= Instance_LibraryChanged;
  433. FileSystemWatcher watcher;
  434. while (FileSystemWatchers.TryTake(out watcher))
  435. {
  436. watcher.Changed -= watcher_Changed;
  437. watcher.EnableRaisingEvents = false;
  438. watcher.Dispose();
  439. }
  440. lock (timerLock)
  441. {
  442. if (updateTimer != null)
  443. {
  444. updateTimer.Dispose();
  445. updateTimer = null;
  446. }
  447. }
  448. affectedPaths.Clear();
  449. }
  450. /// <summary>
  451. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  452. /// </summary>
  453. public void Dispose()
  454. {
  455. Dispose(true);
  456. GC.SuppressFinalize(this);
  457. }
  458. /// <summary>
  459. /// Releases unmanaged and - optionally - managed resources.
  460. /// </summary>
  461. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  462. protected virtual void Dispose(bool dispose)
  463. {
  464. if (dispose)
  465. {
  466. Stop();
  467. }
  468. }
  469. }
  470. }