DirectoryWatchers.cs 18 KB

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