LibraryMonitor.cs 17 KB

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