LibraryMonitor.cs 18 KB

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