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.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. try
  219. {
  220. var newWatcher = new FileSystemWatcher(path, "*")
  221. {
  222. IncludeSubdirectories = true,
  223. InternalBufferSize = 32767
  224. };
  225. newWatcher.NotifyFilter = NotifyFilters.CreationTime |
  226. NotifyFilters.DirectoryName |
  227. NotifyFilters.FileName |
  228. NotifyFilters.LastWrite |
  229. NotifyFilters.Size |
  230. NotifyFilters.Attributes;
  231. newWatcher.Created += watcher_Changed;
  232. newWatcher.Deleted += watcher_Changed;
  233. newWatcher.Renamed += watcher_Changed;
  234. newWatcher.Changed += watcher_Changed;
  235. newWatcher.Error += watcher_Error;
  236. if (_fileSystemWatchers.TryAdd(path, newWatcher))
  237. {
  238. newWatcher.EnableRaisingEvents = true;
  239. Logger.Info("Watching directory " + path);
  240. }
  241. else
  242. {
  243. Logger.Info("Unable to add directory watcher for {0}. It already exists in the dictionary.", path);
  244. newWatcher.Dispose();
  245. }
  246. }
  247. catch (Exception ex)
  248. {
  249. Logger.ErrorException("Error watching path: {0}", ex, path);
  250. }
  251. });
  252. }
  253. /// <summary>
  254. /// Stops the watching path.
  255. /// </summary>
  256. /// <param name="path">The path.</param>
  257. private void StopWatchingPath(string path)
  258. {
  259. FileSystemWatcher watcher;
  260. if (_fileSystemWatchers.TryGetValue(path, out watcher))
  261. {
  262. DisposeWatcher(watcher);
  263. }
  264. }
  265. /// <summary>
  266. /// Disposes the watcher.
  267. /// </summary>
  268. /// <param name="watcher">The watcher.</param>
  269. private void DisposeWatcher(FileSystemWatcher watcher)
  270. {
  271. Logger.Info("Stopping directory watching for path {0}", watcher.Path);
  272. watcher.EnableRaisingEvents = false;
  273. watcher.Dispose();
  274. RemoveWatcherFromList(watcher);
  275. }
  276. /// <summary>
  277. /// Removes the watcher from list.
  278. /// </summary>
  279. /// <param name="watcher">The watcher.</param>
  280. private void RemoveWatcherFromList(FileSystemWatcher watcher)
  281. {
  282. FileSystemWatcher removed;
  283. _fileSystemWatchers.TryRemove(watcher.Path, out removed);
  284. }
  285. /// <summary>
  286. /// Handles the Error event of the watcher control.
  287. /// </summary>
  288. /// <param name="sender">The source of the event.</param>
  289. /// <param name="e">The <see cref="ErrorEventArgs" /> instance containing the event data.</param>
  290. void watcher_Error(object sender, ErrorEventArgs e)
  291. {
  292. var ex = e.GetException();
  293. var dw = (FileSystemWatcher)sender;
  294. Logger.ErrorException("Error in Directory watcher for: " + dw.Path, ex);
  295. DisposeWatcher(dw);
  296. }
  297. /// <summary>
  298. /// Handles the Changed event of the watcher control.
  299. /// </summary>
  300. /// <param name="sender">The source of the event.</param>
  301. /// <param name="e">The <see cref="FileSystemEventArgs" /> instance containing the event data.</param>
  302. void watcher_Changed(object sender, FileSystemEventArgs e)
  303. {
  304. try
  305. {
  306. Logger.Debug("Changed detected of type " + e.ChangeType + " to " + e.FullPath);
  307. ReportFileSystemChanged(e.FullPath);
  308. }
  309. catch (Exception ex)
  310. {
  311. Logger.ErrorException("Exception in ReportFileSystemChanged. Path: {0}", ex, e.FullPath);
  312. }
  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. var monitorPath = !(!string.IsNullOrEmpty(filename) && _alwaysIgnoreFiles.Contains(filename, StringComparer.OrdinalIgnoreCase));
  322. // Ignore certain files
  323. var tempIgnorePaths = _tempIgnoredPaths.Keys.ToList();
  324. // If the parent of an ignored path has a change event, ignore that too
  325. if (tempIgnorePaths.Any(i =>
  326. {
  327. if (string.Equals(i, path, StringComparison.OrdinalIgnoreCase))
  328. {
  329. Logger.Debug("Ignoring change to {0}", path);
  330. return true;
  331. }
  332. if (_fileSystem.ContainsSubPath(i, path))
  333. {
  334. Logger.Debug("Ignoring change to {0}", path);
  335. return true;
  336. }
  337. // Go up a level
  338. var parent = Path.GetDirectoryName(i);
  339. if (!string.IsNullOrEmpty(parent))
  340. {
  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. monitorPath = false;
  351. }
  352. if (monitorPath)
  353. {
  354. // Avoid implicitly captured closure
  355. var affectedPath = path;
  356. _affectedPaths.AddOrUpdate(path, path, (key, oldValue) => affectedPath);
  357. }
  358. lock (_timerLock)
  359. {
  360. if (_updateTimer == null)
  361. {
  362. _updateTimer = new Timer(TimerStopped, null, TimeSpan.FromSeconds(ConfigurationManager.Configuration.RealtimeMonitorDelay), TimeSpan.FromMilliseconds(-1));
  363. }
  364. else
  365. {
  366. _updateTimer.Change(TimeSpan.FromSeconds(ConfigurationManager.Configuration.RealtimeMonitorDelay), TimeSpan.FromMilliseconds(-1));
  367. }
  368. }
  369. }
  370. /// <summary>
  371. /// Timers the stopped.
  372. /// </summary>
  373. /// <param name="stateInfo">The state info.</param>
  374. private async void TimerStopped(object stateInfo)
  375. {
  376. Logger.Debug("Timer stopped.");
  377. DisposeTimer();
  378. var paths = _affectedPaths.Keys.ToList();
  379. _affectedPaths.Clear();
  380. try
  381. {
  382. await ProcessPathChanges(paths).ConfigureAwait(false);
  383. }
  384. catch (Exception ex)
  385. {
  386. Logger.ErrorException("Error processing directory changes", ex);
  387. }
  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. }