DirectoryWatchers.cs 18 KB

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