DirectoryWatchers.cs 18 KB

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