LibraryMonitor.cs 20 KB

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