LibraryMonitor.cs 18 KB

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