LibraryMonitor.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Threading.Tasks;
  9. using Emby.Server.Implementations.Library;
  10. using MediaBrowser.Controller.Configuration;
  11. using MediaBrowser.Controller.Entities;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Model.IO;
  14. using Microsoft.Extensions.Logging;
  15. namespace Emby.Server.Implementations.IO
  16. {
  17. public class LibraryMonitor : ILibraryMonitor
  18. {
  19. private readonly ILogger<LibraryMonitor> _logger;
  20. private readonly ILibraryManager _libraryManager;
  21. private readonly IServerConfigurationManager _configurationManager;
  22. private readonly IFileSystem _fileSystem;
  23. /// <summary>
  24. /// The file system watchers.
  25. /// </summary>
  26. private readonly ConcurrentDictionary<string, FileSystemWatcher> _fileSystemWatchers = new ConcurrentDictionary<string, FileSystemWatcher>(StringComparer.OrdinalIgnoreCase);
  27. /// <summary>
  28. /// The affected paths.
  29. /// </summary>
  30. private readonly List<FileRefresher> _activeRefreshers = new List<FileRefresher>();
  31. /// <summary>
  32. /// A dynamic list of paths that should be ignored. Added to during our own file system modifications.
  33. /// </summary>
  34. private readonly ConcurrentDictionary<string, string> _tempIgnoredPaths = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  35. private bool _disposed = false;
  36. /// <summary>
  37. /// Initializes a new instance of the <see cref="LibraryMonitor" /> class.
  38. /// </summary>
  39. /// <param name="logger">The logger.</param>
  40. /// <param name="libraryManager">The library manager.</param>
  41. /// <param name="configurationManager">The configuration manager.</param>
  42. /// <param name="fileSystem">The filesystem.</param>
  43. public LibraryMonitor(
  44. ILogger<LibraryMonitor> logger,
  45. ILibraryManager libraryManager,
  46. IServerConfigurationManager configurationManager,
  47. IFileSystem fileSystem)
  48. {
  49. _libraryManager = libraryManager;
  50. _logger = logger;
  51. _configurationManager = configurationManager;
  52. _fileSystem = fileSystem;
  53. }
  54. /// <summary>
  55. /// Add the path to our temporary ignore list. Use when writing to a path within our listening scope.
  56. /// </summary>
  57. /// <param name="path">The path.</param>
  58. private void TemporarilyIgnore(string path)
  59. {
  60. _tempIgnoredPaths[path] = path;
  61. }
  62. public void ReportFileSystemChangeBeginning(string path)
  63. {
  64. if (string.IsNullOrEmpty(path))
  65. {
  66. throw new ArgumentNullException(nameof(path));
  67. }
  68. TemporarilyIgnore(path);
  69. }
  70. public async void ReportFileSystemChangeComplete(string path, bool refreshPath)
  71. {
  72. if (string.IsNullOrEmpty(path))
  73. {
  74. throw new ArgumentNullException(nameof(path));
  75. }
  76. // This is an arbitrary amount of time, but delay it because file system writes often trigger events long after the file was actually written to.
  77. // Seeing long delays in some situations, especially over the network, sometimes up to 45 seconds
  78. // But if we make this delay too high, we risk missing legitimate changes, such as user adding a new file, or hand-editing metadata
  79. await Task.Delay(45000).ConfigureAwait(false);
  80. _tempIgnoredPaths.TryRemove(path, out _);
  81. if (refreshPath)
  82. {
  83. try
  84. {
  85. ReportFileSystemChanged(path);
  86. }
  87. catch (Exception ex)
  88. {
  89. _logger.LogError(ex, "Error in ReportFileSystemChanged for {Path}", path);
  90. }
  91. }
  92. }
  93. private bool IsLibraryMonitorEnabled(BaseItem item)
  94. {
  95. if (item is BasePluginFolder)
  96. {
  97. return false;
  98. }
  99. var options = _libraryManager.GetLibraryOptions(item);
  100. if (options is not null)
  101. {
  102. return options.EnableRealtimeMonitor;
  103. }
  104. return false;
  105. }
  106. public void Start()
  107. {
  108. _libraryManager.ItemAdded += OnLibraryManagerItemAdded;
  109. _libraryManager.ItemRemoved += OnLibraryManagerItemRemoved;
  110. var pathsToWatch = new List<string>();
  111. var paths = _libraryManager
  112. .RootFolder
  113. .Children
  114. .Where(IsLibraryMonitorEnabled)
  115. .OfType<Folder>()
  116. .SelectMany(f => f.PhysicalLocations)
  117. .Distinct(StringComparer.OrdinalIgnoreCase)
  118. .OrderBy(i => i);
  119. foreach (var path in paths)
  120. {
  121. if (!ContainsParentFolder(pathsToWatch, path))
  122. {
  123. pathsToWatch.Add(path);
  124. }
  125. }
  126. foreach (var path in pathsToWatch)
  127. {
  128. StartWatchingPath(path);
  129. }
  130. }
  131. private void StartWatching(BaseItem item)
  132. {
  133. if (IsLibraryMonitorEnabled(item))
  134. {
  135. StartWatchingPath(item.Path);
  136. }
  137. }
  138. /// <summary>
  139. /// Handles the ItemRemoved event of the LibraryManager control.
  140. /// </summary>
  141. /// <param name="sender">The source of the event.</param>
  142. /// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
  143. private void OnLibraryManagerItemRemoved(object sender, ItemChangeEventArgs e)
  144. {
  145. if (e.Parent is AggregateFolder)
  146. {
  147. StopWatchingPath(e.Item.Path);
  148. }
  149. }
  150. /// <summary>
  151. /// Handles the ItemAdded event of the LibraryManager control.
  152. /// </summary>
  153. /// <param name="sender">The source of the event.</param>
  154. /// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
  155. private void OnLibraryManagerItemAdded(object sender, ItemChangeEventArgs e)
  156. {
  157. if (e.Parent is AggregateFolder)
  158. {
  159. StartWatching(e.Item);
  160. }
  161. }
  162. /// <summary>
  163. /// Examine a list of strings assumed to be file paths to see if it contains a parent of
  164. /// the provided path.
  165. /// </summary>
  166. /// <param name="lst">The LST.</param>
  167. /// <param name="path">The path.</param>
  168. /// <returns><c>true</c> if [contains parent folder] [the specified LST]; otherwise, <c>false</c>.</returns>
  169. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <c>null</c>.</exception>
  170. private static bool ContainsParentFolder(IEnumerable<string> lst, string path)
  171. {
  172. if (string.IsNullOrEmpty(path))
  173. {
  174. throw new ArgumentNullException(nameof(path));
  175. }
  176. path = path.TrimEnd(Path.DirectorySeparatorChar);
  177. return lst.Any(str =>
  178. {
  179. // this should be a little quicker than examining each actual parent folder...
  180. var compare = str.TrimEnd(Path.DirectorySeparatorChar);
  181. return path.Equals(compare, StringComparison.OrdinalIgnoreCase) || (path.StartsWith(compare, StringComparison.OrdinalIgnoreCase) && path[compare.Length] == Path.DirectorySeparatorChar);
  182. });
  183. }
  184. /// <summary>
  185. /// Starts the watching path.
  186. /// </summary>
  187. /// <param name="path">The path.</param>
  188. private void StartWatchingPath(string path)
  189. {
  190. if (!Directory.Exists(path))
  191. {
  192. // Seeing a crash in the mono runtime due to an exception being thrown on a different thread
  193. _logger.LogInformation("Skipping realtime monitor for {Path} because the path does not exist", path);
  194. return;
  195. }
  196. // Already being watched
  197. if (_fileSystemWatchers.ContainsKey(path))
  198. {
  199. return;
  200. }
  201. // Creating a FileSystemWatcher over the LAN can take hundreds of milliseconds, so wrap it in a Task to do them all in parallel
  202. Task.Run(() =>
  203. {
  204. try
  205. {
  206. var newWatcher = new FileSystemWatcher(path, "*")
  207. {
  208. IncludeSubdirectories = true,
  209. InternalBufferSize = 65536,
  210. NotifyFilter = NotifyFilters.CreationTime |
  211. NotifyFilters.DirectoryName |
  212. NotifyFilters.FileName |
  213. NotifyFilters.LastWrite |
  214. NotifyFilters.Size |
  215. NotifyFilters.Attributes
  216. };
  217. newWatcher.Created += OnWatcherChanged;
  218. newWatcher.Deleted += OnWatcherChanged;
  219. newWatcher.Renamed += OnWatcherChanged;
  220. newWatcher.Changed += OnWatcherChanged;
  221. newWatcher.Error += OnWatcherError;
  222. if (_fileSystemWatchers.TryAdd(path, newWatcher))
  223. {
  224. newWatcher.EnableRaisingEvents = true;
  225. _logger.LogInformation("Watching directory {Path}", path);
  226. }
  227. else
  228. {
  229. DisposeWatcher(newWatcher, false);
  230. }
  231. }
  232. catch (Exception ex)
  233. {
  234. _logger.LogError(ex, "Error watching path: {Path}", path);
  235. }
  236. });
  237. }
  238. /// <summary>
  239. /// Stops the watching path.
  240. /// </summary>
  241. /// <param name="path">The path.</param>
  242. private void StopWatchingPath(string path)
  243. {
  244. if (_fileSystemWatchers.TryGetValue(path, out var watcher))
  245. {
  246. DisposeWatcher(watcher, true);
  247. }
  248. }
  249. /// <summary>
  250. /// Disposes the watcher.
  251. /// </summary>
  252. private void DisposeWatcher(FileSystemWatcher watcher, bool removeFromList)
  253. {
  254. try
  255. {
  256. using (watcher)
  257. {
  258. _logger.LogInformation("Stopping directory watching for path {Path}", watcher.Path);
  259. watcher.Created -= OnWatcherChanged;
  260. watcher.Deleted -= OnWatcherChanged;
  261. watcher.Renamed -= OnWatcherChanged;
  262. watcher.Changed -= OnWatcherChanged;
  263. watcher.Error -= OnWatcherError;
  264. watcher.EnableRaisingEvents = false;
  265. }
  266. }
  267. finally
  268. {
  269. if (removeFromList)
  270. {
  271. RemoveWatcherFromList(watcher);
  272. }
  273. }
  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. _fileSystemWatchers.TryRemove(watcher.Path, out _);
  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. private void OnWatcherError(object sender, ErrorEventArgs e)
  289. {
  290. var ex = e.GetException();
  291. var dw = (FileSystemWatcher)sender;
  292. _logger.LogError(ex, "Error in Directory watcher for: {Path}", dw.Path);
  293. DisposeWatcher(dw, true);
  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. private void OnWatcherChanged(object sender, FileSystemEventArgs e)
  301. {
  302. try
  303. {
  304. ReportFileSystemChanged(e.FullPath);
  305. }
  306. catch (Exception ex)
  307. {
  308. _logger.LogError(ex, "Exception in ReportFileSystemChanged. Path: {FullPath}", e.FullPath);
  309. }
  310. }
  311. public void ReportFileSystemChanged(string path)
  312. {
  313. if (string.IsNullOrEmpty(path))
  314. {
  315. throw new ArgumentNullException(nameof(path));
  316. }
  317. var monitorPath = !IgnorePatterns.ShouldIgnore(path);
  318. // Ignore certain files, If the parent of an ignored path has a change event, ignore that too
  319. if (_tempIgnoredPaths.Keys.Any(i =>
  320. {
  321. if (_fileSystem.AreEqual(i, path))
  322. {
  323. _logger.LogDebug("Ignoring change to {Path}", path);
  324. return true;
  325. }
  326. if (_fileSystem.ContainsSubPath(i, path))
  327. {
  328. _logger.LogDebug("Ignoring change to {Path}", path);
  329. return true;
  330. }
  331. // Go up a level
  332. var parent = Path.GetDirectoryName(i);
  333. if (!string.IsNullOrEmpty(parent) && _fileSystem.AreEqual(parent, path))
  334. {
  335. _logger.LogDebug("Ignoring change to {Path}", path);
  336. return true;
  337. }
  338. return false;
  339. }))
  340. {
  341. monitorPath = false;
  342. }
  343. if (monitorPath)
  344. {
  345. // Avoid implicitly captured closure
  346. CreateRefresher(path);
  347. }
  348. }
  349. private void CreateRefresher(string path)
  350. {
  351. var parentPath = Path.GetDirectoryName(path);
  352. lock (_activeRefreshers)
  353. {
  354. foreach (var refresher in _activeRefreshers)
  355. {
  356. // Path is already being refreshed
  357. if (_fileSystem.AreEqual(path, refresher.Path))
  358. {
  359. refresher.RestartTimer();
  360. return;
  361. }
  362. // Parent folder is already being refreshed
  363. if (_fileSystem.ContainsSubPath(refresher.Path, path))
  364. {
  365. refresher.AddPath(path);
  366. return;
  367. }
  368. // New path is a parent
  369. if (_fileSystem.ContainsSubPath(path, refresher.Path))
  370. {
  371. refresher.ResetPath(path, null);
  372. return;
  373. }
  374. // They are siblings. Rebase the refresher to the parent folder.
  375. if (string.Equals(parentPath, Path.GetDirectoryName(refresher.Path), StringComparison.Ordinal))
  376. {
  377. refresher.ResetPath(parentPath, path);
  378. return;
  379. }
  380. }
  381. var newRefresher = new FileRefresher(path, _configurationManager, _libraryManager, _logger);
  382. newRefresher.Completed += OnNewRefresherCompleted;
  383. _activeRefreshers.Add(newRefresher);
  384. }
  385. }
  386. private void OnNewRefresherCompleted(object sender, EventArgs e)
  387. {
  388. var refresher = (FileRefresher)sender;
  389. DisposeRefresher(refresher);
  390. }
  391. /// <summary>
  392. /// Stops this instance.
  393. /// </summary>
  394. public void Stop()
  395. {
  396. _libraryManager.ItemAdded -= OnLibraryManagerItemAdded;
  397. _libraryManager.ItemRemoved -= OnLibraryManagerItemRemoved;
  398. foreach (var watcher in _fileSystemWatchers.Values.ToList())
  399. {
  400. DisposeWatcher(watcher, false);
  401. }
  402. _fileSystemWatchers.Clear();
  403. DisposeRefreshers();
  404. }
  405. private void DisposeRefresher(FileRefresher refresher)
  406. {
  407. lock (_activeRefreshers)
  408. {
  409. refresher.Completed -= OnNewRefresherCompleted;
  410. refresher.Dispose();
  411. _activeRefreshers.Remove(refresher);
  412. }
  413. }
  414. private void DisposeRefreshers()
  415. {
  416. lock (_activeRefreshers)
  417. {
  418. foreach (var refresher in _activeRefreshers)
  419. {
  420. refresher.Completed -= OnNewRefresherCompleted;
  421. refresher.Dispose();
  422. }
  423. _activeRefreshers.Clear();
  424. }
  425. }
  426. /// <summary>
  427. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  428. /// </summary>
  429. public void Dispose()
  430. {
  431. Dispose(true);
  432. GC.SuppressFinalize(this);
  433. }
  434. /// <summary>
  435. /// Releases unmanaged and - optionally - managed resources.
  436. /// </summary>
  437. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  438. protected virtual void Dispose(bool disposing)
  439. {
  440. if (_disposed)
  441. {
  442. return;
  443. }
  444. if (disposing)
  445. {
  446. Stop();
  447. }
  448. _disposed = true;
  449. }
  450. }
  451. }