DirectoryWatchers.cs 21 KB

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