DirectoryWatchers.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  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(1500).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. .Distinct(StringComparer.OrdinalIgnoreCase)
  135. .OrderBy(i => i)
  136. .ToList();
  137. foreach (var path in paths)
  138. {
  139. if (!ContainsParentFolder(pathsToWatch, path))
  140. {
  141. pathsToWatch.Add(path);
  142. }
  143. }
  144. foreach (var path in pathsToWatch)
  145. {
  146. StartWatchingPath(path);
  147. }
  148. }
  149. /// <summary>
  150. /// Handles the ItemRemoved event of the LibraryManager control.
  151. /// </summary>
  152. /// <param name="sender">The source of the event.</param>
  153. /// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
  154. void LibraryManager_ItemRemoved(object sender, ItemChangeEventArgs e)
  155. {
  156. if (e.Item.Parent is AggregateFolder)
  157. {
  158. StopWatchingPath(e.Item.Path);
  159. }
  160. }
  161. /// <summary>
  162. /// Handles the ItemAdded event of the LibraryManager control.
  163. /// </summary>
  164. /// <param name="sender">The source of the event.</param>
  165. /// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
  166. void LibraryManager_ItemAdded(object sender, ItemChangeEventArgs e)
  167. {
  168. if (e.Item.Parent is AggregateFolder)
  169. {
  170. StartWatchingPath(e.Item.Path);
  171. }
  172. }
  173. /// <summary>
  174. /// Examine a list of strings assumed to be file paths to see if it contains a parent of
  175. /// the provided path.
  176. /// </summary>
  177. /// <param name="lst">The LST.</param>
  178. /// <param name="path">The path.</param>
  179. /// <returns><c>true</c> if [contains parent folder] [the specified LST]; otherwise, <c>false</c>.</returns>
  180. /// <exception cref="System.ArgumentNullException">path</exception>
  181. private static bool ContainsParentFolder(IEnumerable<string> lst, string path)
  182. {
  183. if (string.IsNullOrEmpty(path))
  184. {
  185. throw new ArgumentNullException("path");
  186. }
  187. path = path.TrimEnd(Path.DirectorySeparatorChar);
  188. return lst.Any(str =>
  189. {
  190. //this should be a little quicker than examining each actual parent folder...
  191. var compare = str.TrimEnd(Path.DirectorySeparatorChar);
  192. return (path.Equals(compare, StringComparison.OrdinalIgnoreCase) || (path.StartsWith(compare, StringComparison.OrdinalIgnoreCase) && path[compare.Length] == Path.DirectorySeparatorChar));
  193. });
  194. }
  195. /// <summary>
  196. /// Starts the watching path.
  197. /// </summary>
  198. /// <param name="path">The path.</param>
  199. private void StartWatchingPath(string path)
  200. {
  201. // Creating a FileSystemWatcher over the LAN can take hundreds of milliseconds, so wrap it in a Task to do them all in parallel
  202. Task.Run(() =>
  203. {
  204. var newWatcher = new FileSystemWatcher(path, "*") { IncludeSubdirectories = true, InternalBufferSize = 32767 };
  205. newWatcher.Created += watcher_Changed;
  206. newWatcher.Deleted += watcher_Changed;
  207. newWatcher.Renamed += watcher_Changed;
  208. newWatcher.Changed += watcher_Changed;
  209. newWatcher.Error += watcher_Error;
  210. try
  211. {
  212. if (_fileSystemWatchers.TryAdd(path, newWatcher))
  213. {
  214. newWatcher.EnableRaisingEvents = true;
  215. Logger.Info("Watching directory " + path);
  216. }
  217. else
  218. {
  219. Logger.Info("Unable to add directory watcher for {0}. It already exists in the dictionary." + path);
  220. newWatcher.Dispose();
  221. }
  222. }
  223. catch (IOException ex)
  224. {
  225. Logger.ErrorException("Error watching path: {0}", ex, path);
  226. }
  227. catch (PlatformNotSupportedException ex)
  228. {
  229. Logger.ErrorException("Error watching path: {0}", ex, path);
  230. }
  231. });
  232. }
  233. /// <summary>
  234. /// Stops the watching path.
  235. /// </summary>
  236. /// <param name="path">The path.</param>
  237. private void StopWatchingPath(string path)
  238. {
  239. FileSystemWatcher watcher;
  240. if (_fileSystemWatchers.TryGetValue(path, out watcher))
  241. {
  242. DisposeWatcher(watcher);
  243. }
  244. }
  245. /// <summary>
  246. /// Disposes the watcher.
  247. /// </summary>
  248. /// <param name="watcher">The watcher.</param>
  249. private void DisposeWatcher(FileSystemWatcher watcher)
  250. {
  251. Logger.Info("Stopping directory watching for path {0}", watcher.Path);
  252. watcher.EnableRaisingEvents = false;
  253. watcher.Dispose();
  254. RemoveWatcherFromList(watcher);
  255. }
  256. /// <summary>
  257. /// Removes the watcher from list.
  258. /// </summary>
  259. /// <param name="watcher">The watcher.</param>
  260. private void RemoveWatcherFromList(FileSystemWatcher watcher)
  261. {
  262. FileSystemWatcher removed;
  263. _fileSystemWatchers.TryRemove(watcher.Path, out removed);
  264. }
  265. /// <summary>
  266. /// Handles the Error event of the watcher control.
  267. /// </summary>
  268. /// <param name="sender">The source of the event.</param>
  269. /// <param name="e">The <see cref="ErrorEventArgs" /> instance containing the event data.</param>
  270. void watcher_Error(object sender, ErrorEventArgs e)
  271. {
  272. var ex = e.GetException();
  273. var dw = (FileSystemWatcher)sender;
  274. Logger.ErrorException("Error in Directory watcher for: " + dw.Path, ex);
  275. DisposeWatcher(dw);
  276. }
  277. /// <summary>
  278. /// Handles the Changed event of the watcher control.
  279. /// </summary>
  280. /// <param name="sender">The source of the event.</param>
  281. /// <param name="e">The <see cref="FileSystemEventArgs" /> instance containing the event data.</param>
  282. void watcher_Changed(object sender, FileSystemEventArgs e)
  283. {
  284. try
  285. {
  286. OnWatcherChanged(e);
  287. }
  288. catch (IOException ex)
  289. {
  290. Logger.ErrorException("IOException in watcher changed. Path: {0}", ex, e.FullPath);
  291. }
  292. }
  293. private void OnWatcherChanged(FileSystemEventArgs e)
  294. {
  295. var name = e.Name;
  296. // Ignore certain files
  297. if (_alwaysIgnoreFiles.Contains(name, StringComparer.OrdinalIgnoreCase))
  298. {
  299. return;
  300. }
  301. var nameFromFullPath = Path.GetFileName(e.FullPath);
  302. // Ignore certain files
  303. if (!string.IsNullOrEmpty(nameFromFullPath) && _alwaysIgnoreFiles.Contains(nameFromFullPath, StringComparer.OrdinalIgnoreCase))
  304. {
  305. return;
  306. }
  307. // Ignore when someone manually creates a new folder
  308. if (e.ChangeType == WatcherChangeTypes.Created && name == "New folder")
  309. {
  310. return;
  311. }
  312. var tempIgnorePaths = _tempIgnoredPaths.Keys.ToList();
  313. // If the parent of an ignored path has a change event, ignore that too
  314. if (tempIgnorePaths.Any(i =>
  315. {
  316. if (string.Equals(i, e.FullPath, StringComparison.OrdinalIgnoreCase))
  317. {
  318. Logger.Debug("Watcher ignoring change to {0}", e.FullPath);
  319. return true;
  320. }
  321. // Go up a level
  322. var parent = Path.GetDirectoryName(i);
  323. if (string.Equals(parent, e.FullPath, StringComparison.OrdinalIgnoreCase))
  324. {
  325. Logger.Debug("Watcher ignoring change to {0}", e.FullPath);
  326. return true;
  327. }
  328. // Go up another level
  329. if (!string.IsNullOrEmpty(parent))
  330. {
  331. parent = Path.GetDirectoryName(i);
  332. if (string.Equals(parent, e.FullPath, StringComparison.OrdinalIgnoreCase))
  333. {
  334. Logger.Debug("Watcher ignoring change to {0}", e.FullPath);
  335. return true;
  336. }
  337. }
  338. if (i.StartsWith(e.FullPath, StringComparison.OrdinalIgnoreCase) ||
  339. e.FullPath.StartsWith(i, StringComparison.OrdinalIgnoreCase))
  340. {
  341. Logger.Debug("Watcher ignoring change to {0}", e.FullPath);
  342. return true;
  343. }
  344. return false;
  345. }))
  346. {
  347. return;
  348. }
  349. Logger.Info("Watcher sees change of type " + e.ChangeType + " to " + e.FullPath);
  350. //Since we're watching created, deleted and renamed we always want the parent of the item to be the affected path
  351. var affectedPath = e.FullPath;
  352. _affectedPaths.AddOrUpdate(affectedPath, affectedPath, (key, oldValue) => affectedPath);
  353. lock (_timerLock)
  354. {
  355. if (_updateTimer == null)
  356. {
  357. _updateTimer = new Timer(TimerStopped, null, TimeSpan.FromSeconds(ConfigurationManager.Configuration.FileWatcherDelay), TimeSpan.FromMilliseconds(-1));
  358. }
  359. else
  360. {
  361. _updateTimer.Change(TimeSpan.FromSeconds(ConfigurationManager.Configuration.FileWatcherDelay), TimeSpan.FromMilliseconds(-1));
  362. }
  363. }
  364. }
  365. /// <summary>
  366. /// Timers the stopped.
  367. /// </summary>
  368. /// <param name="stateInfo">The state info.</param>
  369. private async void TimerStopped(object stateInfo)
  370. {
  371. lock (_timerLock)
  372. {
  373. // Extend the timer as long as any of the paths are still being written to.
  374. if (_affectedPaths.Any(p => IsFileLocked(p.Key)))
  375. {
  376. Logger.Info("Timer extended.");
  377. _updateTimer.Change(TimeSpan.FromSeconds(ConfigurationManager.Configuration.FileWatcherDelay), TimeSpan.FromMilliseconds(-1));
  378. return;
  379. }
  380. Logger.Info("Timer stopped.");
  381. if (_updateTimer != null)
  382. {
  383. _updateTimer.Dispose();
  384. _updateTimer = null;
  385. }
  386. }
  387. var paths = _affectedPaths.Keys.ToList();
  388. _affectedPaths.Clear();
  389. await ProcessPathChanges(paths).ConfigureAwait(false);
  390. }
  391. /// <summary>
  392. /// Try and determine if a file is locked
  393. /// This is not perfect, and is subject to race conditions, so I'd rather not make this a re-usable library method.
  394. /// </summary>
  395. /// <param name="path">The path.</param>
  396. /// <returns><c>true</c> if [is file locked] [the specified path]; otherwise, <c>false</c>.</returns>
  397. private bool IsFileLocked(string path)
  398. {
  399. try
  400. {
  401. var data = _fileSystem.GetFileSystemInfo(path);
  402. if (!data.Exists
  403. || data.Attributes.HasFlag(FileAttributes.Directory)
  404. || data.Attributes.HasFlag(FileAttributes.ReadOnly))
  405. {
  406. return false;
  407. }
  408. }
  409. catch (IOException)
  410. {
  411. return false;
  412. }
  413. try
  414. {
  415. using (_fileSystem.GetFileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
  416. {
  417. //file is not locked
  418. return false;
  419. }
  420. }
  421. catch (DirectoryNotFoundException)
  422. {
  423. return false;
  424. }
  425. catch (FileNotFoundException)
  426. {
  427. return false;
  428. }
  429. catch (IOException)
  430. {
  431. //the file is unavailable because it is:
  432. //still being written to
  433. //or being processed by another thread
  434. //or does not exist (has already been processed)
  435. Logger.Debug("{0} is locked.", path);
  436. return true;
  437. }
  438. catch
  439. {
  440. return false;
  441. }
  442. }
  443. /// <summary>
  444. /// Processes the path changes.
  445. /// </summary>
  446. /// <param name="paths">The paths.</param>
  447. /// <returns>Task.</returns>
  448. private async Task ProcessPathChanges(List<string> paths)
  449. {
  450. var itemsToRefresh = paths.Select(Path.GetDirectoryName)
  451. .Select(GetAffectedBaseItem)
  452. .Where(item => item != null)
  453. .Distinct()
  454. .ToList();
  455. foreach (var p in paths) Logger.Info(p + " reports change.");
  456. // If the root folder changed, run the library task so the user can see it
  457. if (itemsToRefresh.Any(i => i is AggregateFolder))
  458. {
  459. TaskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  460. return;
  461. }
  462. await Task.WhenAll(itemsToRefresh.Select(i => Task.Run(async () =>
  463. {
  464. Logger.Info(i.Name + " (" + i.Path + ") will be refreshed.");
  465. try
  466. {
  467. await i.ChangedExternally().ConfigureAwait(false);
  468. }
  469. catch (IOException ex)
  470. {
  471. // For now swallow and log.
  472. // Research item: If an IOException occurs, the item may be in a disconnected state (media unavailable)
  473. // Should we remove it from it's parent?
  474. Logger.ErrorException("Error refreshing {0}", ex, i.Name);
  475. }
  476. catch (Exception ex)
  477. {
  478. Logger.ErrorException("Error refreshing {0}", ex, i.Name);
  479. }
  480. }))).ConfigureAwait(false);
  481. }
  482. /// <summary>
  483. /// Gets the affected base item.
  484. /// </summary>
  485. /// <param name="path">The path.</param>
  486. /// <returns>BaseItem.</returns>
  487. private BaseItem GetAffectedBaseItem(string path)
  488. {
  489. BaseItem item = null;
  490. while (item == null && !string.IsNullOrEmpty(path))
  491. {
  492. item = LibraryManager.RootFolder.FindByPath(path);
  493. path = Path.GetDirectoryName(path);
  494. }
  495. if (item != null)
  496. {
  497. // If the item has been deleted find the first valid parent that still exists
  498. while (!Directory.Exists(item.Path) && !File.Exists(item.Path))
  499. {
  500. item = item.Parent;
  501. if (item == null)
  502. {
  503. break;
  504. }
  505. }
  506. }
  507. return item;
  508. }
  509. /// <summary>
  510. /// Stops this instance.
  511. /// </summary>
  512. public void Stop()
  513. {
  514. LibraryManager.ItemAdded -= LibraryManager_ItemAdded;
  515. LibraryManager.ItemRemoved -= LibraryManager_ItemRemoved;
  516. foreach (var watcher in _fileSystemWatchers.Values.ToList())
  517. {
  518. watcher.Changed -= watcher_Changed;
  519. watcher.EnableRaisingEvents = false;
  520. watcher.Dispose();
  521. }
  522. lock (_timerLock)
  523. {
  524. if (_updateTimer != null)
  525. {
  526. _updateTimer.Dispose();
  527. _updateTimer = null;
  528. }
  529. }
  530. _fileSystemWatchers.Clear();
  531. _affectedPaths.Clear();
  532. }
  533. /// <summary>
  534. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  535. /// </summary>
  536. public void Dispose()
  537. {
  538. Dispose(true);
  539. GC.SuppressFinalize(this);
  540. }
  541. /// <summary>
  542. /// Releases unmanaged and - optionally - managed resources.
  543. /// </summary>
  544. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  545. protected virtual void Dispose(bool dispose)
  546. {
  547. if (dispose)
  548. {
  549. Stop();
  550. }
  551. }
  552. }
  553. }