LibraryMonitor.cs 17 KB

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