LibraryMonitor.cs 20 KB

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