LibraryMonitor.cs 20 KB

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