LibraryMonitor.cs 20 KB

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