LibraryMonitor.cs 20 KB

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