LibraryMonitor.cs 20 KB

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