DirectoryWatchers.cs 22 KB

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