LibraryMonitor.cs 17 KB

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