DirectoryWatchers.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  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. Logger.Debug("Watcher ignoring change to {0}", e.FullPath);
  318. return true;
  319. }
  320. // Go up a level
  321. var parent = Path.GetDirectoryName(i);
  322. if (string.Equals(parent, e.FullPath, StringComparison.OrdinalIgnoreCase))
  323. {
  324. Logger.Debug("Watcher ignoring change to {0}", e.FullPath);
  325. return true;
  326. }
  327. // Go up another level
  328. if (!string.IsNullOrEmpty(parent))
  329. {
  330. parent = Path.GetDirectoryName(i);
  331. if (string.Equals(parent, e.FullPath, StringComparison.OrdinalIgnoreCase))
  332. {
  333. Logger.Debug("Watcher ignoring change to {0}", e.FullPath);
  334. return true;
  335. }
  336. }
  337. if (i.StartsWith(e.FullPath, StringComparison.OrdinalIgnoreCase) ||
  338. e.FullPath.StartsWith(i, StringComparison.OrdinalIgnoreCase))
  339. {
  340. Logger.Debug("Watcher ignoring change to {0}", e.FullPath);
  341. return true;
  342. }
  343. return false;
  344. }))
  345. {
  346. return;
  347. }
  348. Logger.Info("Watcher sees change of type " + e.ChangeType + " to " + e.FullPath);
  349. //Since we're watching created, deleted and renamed we always want the parent of the item to be the affected path
  350. var affectedPath = e.FullPath;
  351. _affectedPaths.AddOrUpdate(affectedPath, affectedPath, (key, oldValue) => affectedPath);
  352. lock (_timerLock)
  353. {
  354. if (_updateTimer == null)
  355. {
  356. _updateTimer = new Timer(TimerStopped, null, TimeSpan.FromSeconds(ConfigurationManager.Configuration.FileWatcherDelay), TimeSpan.FromMilliseconds(-1));
  357. }
  358. else
  359. {
  360. _updateTimer.Change(TimeSpan.FromSeconds(ConfigurationManager.Configuration.FileWatcherDelay), TimeSpan.FromMilliseconds(-1));
  361. }
  362. }
  363. }
  364. /// <summary>
  365. /// Timers the stopped.
  366. /// </summary>
  367. /// <param name="stateInfo">The state info.</param>
  368. private async void TimerStopped(object stateInfo)
  369. {
  370. lock (_timerLock)
  371. {
  372. // Extend the timer as long as any of the paths are still being written to.
  373. if (_affectedPaths.Any(p => IsFileLocked(p.Key)))
  374. {
  375. Logger.Info("Timer extended.");
  376. _updateTimer.Change(TimeSpan.FromSeconds(ConfigurationManager.Configuration.FileWatcherDelay), TimeSpan.FromMilliseconds(-1));
  377. return;
  378. }
  379. Logger.Info("Timer stopped.");
  380. if (_updateTimer != null)
  381. {
  382. _updateTimer.Dispose();
  383. _updateTimer = null;
  384. }
  385. }
  386. var paths = _affectedPaths.Keys.ToList();
  387. _affectedPaths.Clear();
  388. await ProcessPathChanges(paths).ConfigureAwait(false);
  389. }
  390. /// <summary>
  391. /// Try and determine if a file is locked
  392. /// This is not perfect, and is subject to race conditions, so I'd rather not make this a re-usable library method.
  393. /// </summary>
  394. /// <param name="path">The path.</param>
  395. /// <returns><c>true</c> if [is file locked] [the specified path]; otherwise, <c>false</c>.</returns>
  396. private bool IsFileLocked(string path)
  397. {
  398. try
  399. {
  400. var data = _fileSystem.GetFileSystemInfo(path);
  401. if (!data.Exists
  402. || data.Attributes.HasFlag(FileAttributes.Directory)
  403. || data.Attributes.HasFlag(FileAttributes.ReadOnly))
  404. {
  405. return false;
  406. }
  407. }
  408. catch (IOException)
  409. {
  410. return false;
  411. }
  412. try
  413. {
  414. using (_fileSystem.GetFileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
  415. {
  416. //file is not locked
  417. return false;
  418. }
  419. }
  420. catch (DirectoryNotFoundException)
  421. {
  422. return false;
  423. }
  424. catch (FileNotFoundException)
  425. {
  426. return false;
  427. }
  428. catch (IOException)
  429. {
  430. //the file is unavailable because it is:
  431. //still being written to
  432. //or being processed by another thread
  433. //or does not exist (has already been processed)
  434. Logger.Debug("{0} is locked.", path);
  435. return true;
  436. }
  437. catch
  438. {
  439. return false;
  440. }
  441. }
  442. /// <summary>
  443. /// Processes the path changes.
  444. /// </summary>
  445. /// <param name="paths">The paths.</param>
  446. /// <returns>Task.</returns>
  447. private async Task ProcessPathChanges(List<string> paths)
  448. {
  449. var itemsToRefresh = paths.Select(Path.GetDirectoryName)
  450. .Select(GetAffectedBaseItem)
  451. .Where(item => item != null)
  452. .Distinct()
  453. .ToList();
  454. foreach (var p in paths) Logger.Info(p + " reports change.");
  455. // If the root folder changed, run the library task so the user can see it
  456. if (itemsToRefresh.Any(i => i is AggregateFolder))
  457. {
  458. TaskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  459. return;
  460. }
  461. await Task.WhenAll(itemsToRefresh.Select(i => Task.Run(async () =>
  462. {
  463. Logger.Info(i.Name + " (" + i.Path + ") will be refreshed.");
  464. try
  465. {
  466. await i.ChangedExternally().ConfigureAwait(false);
  467. }
  468. catch (IOException ex)
  469. {
  470. // For now swallow and log.
  471. // Research item: If an IOException occurs, the item may be in a disconnected state (media unavailable)
  472. // Should we remove it from it's parent?
  473. Logger.ErrorException("Error refreshing {0}", ex, i.Name);
  474. }
  475. catch (Exception ex)
  476. {
  477. Logger.ErrorException("Error refreshing {0}", ex, i.Name);
  478. }
  479. }))).ConfigureAwait(false);
  480. }
  481. /// <summary>
  482. /// Gets the affected base item.
  483. /// </summary>
  484. /// <param name="path">The path.</param>
  485. /// <returns>BaseItem.</returns>
  486. private BaseItem GetAffectedBaseItem(string path)
  487. {
  488. BaseItem item = null;
  489. while (item == null && !string.IsNullOrEmpty(path))
  490. {
  491. item = LibraryManager.RootFolder.FindByPath(path);
  492. path = Path.GetDirectoryName(path);
  493. }
  494. if (item != null)
  495. {
  496. // If the item has been deleted find the first valid parent that still exists
  497. while (!Directory.Exists(item.Path) && !File.Exists(item.Path))
  498. {
  499. item = item.Parent;
  500. if (item == null)
  501. {
  502. break;
  503. }
  504. }
  505. }
  506. return item;
  507. }
  508. /// <summary>
  509. /// Stops this instance.
  510. /// </summary>
  511. public void Stop()
  512. {
  513. LibraryManager.ItemAdded -= LibraryManager_ItemAdded;
  514. LibraryManager.ItemRemoved -= LibraryManager_ItemRemoved;
  515. foreach (var watcher in _fileSystemWatchers.Values.ToList())
  516. {
  517. watcher.Changed -= watcher_Changed;
  518. watcher.EnableRaisingEvents = false;
  519. watcher.Dispose();
  520. }
  521. lock (_timerLock)
  522. {
  523. if (_updateTimer != null)
  524. {
  525. _updateTimer.Dispose();
  526. _updateTimer = null;
  527. }
  528. }
  529. _fileSystemWatchers.Clear();
  530. _affectedPaths.Clear();
  531. }
  532. /// <summary>
  533. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  534. /// </summary>
  535. public void Dispose()
  536. {
  537. Dispose(true);
  538. GC.SuppressFinalize(this);
  539. }
  540. /// <summary>
  541. /// Releases unmanaged and - optionally - managed resources.
  542. /// </summary>
  543. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  544. protected virtual void Dispose(bool dispose)
  545. {
  546. if (dispose)
  547. {
  548. Stop();
  549. }
  550. }
  551. }
  552. }