DirectoryWatchers.cs 21 KB

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