LibraryMonitor.cs 20 KB

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