DirectoryWatchers.cs 21 KB

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