DirectoryWatchers.cs 22 KB

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