LibraryMonitor.cs 20 KB

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