DirectoryWatchers.cs 21 KB

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