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. /// Add the path to our temporary ignore list. Use when writing to a path within our listening scope.
  38. /// </summary>
  39. /// <param name="path">The path.</param>
  40. private void TemporarilyIgnore(string path)
  41. {
  42. _tempIgnoredPaths[path] = path;
  43. }
  44. public void ReportFileSystemChangeBeginning(string path)
  45. {
  46. if (string.IsNullOrEmpty(path))
  47. {
  48. throw new ArgumentNullException(nameof(path));
  49. }
  50. TemporarilyIgnore(path);
  51. }
  52. public bool IsPathLocked(string path)
  53. {
  54. // This method is not used by the core but it used by auto-organize
  55. var lockedPaths = _tempIgnoredPaths.Keys.ToList();
  56. return lockedPaths.Any(i => _fileSystem.AreEqual(i, path) || _fileSystem.ContainsSubPath(i, path));
  57. }
  58. public async void ReportFileSystemChangeComplete(string path, bool refreshPath)
  59. {
  60. if (string.IsNullOrEmpty(path))
  61. {
  62. throw new ArgumentNullException(nameof(path));
  63. }
  64. // 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.
  65. // Seeing long delays in some situations, especially over the network, sometimes up to 45 seconds
  66. // But if we make this delay too high, we risk missing legitimate changes, such as user adding a new file, or hand-editing metadata
  67. await Task.Delay(45000).ConfigureAwait(false);
  68. _tempIgnoredPaths.TryRemove(path, out var val);
  69. if (refreshPath)
  70. {
  71. try
  72. {
  73. ReportFileSystemChanged(path);
  74. }
  75. catch (Exception ex)
  76. {
  77. _logger.LogError(ex, "Error in ReportFileSystemChanged for {Path}", path);
  78. }
  79. }
  80. }
  81. /// <summary>
  82. /// Initializes a new instance of the <see cref="LibraryMonitor" /> class.
  83. /// </summary>
  84. public LibraryMonitor(
  85. ILogger<LibraryMonitor> logger,
  86. ILibraryManager libraryManager,
  87. IServerConfigurationManager configurationManager,
  88. IFileSystem fileSystem)
  89. {
  90. _libraryManager = libraryManager;
  91. _logger = logger;
  92. _configurationManager = configurationManager;
  93. _fileSystem = fileSystem;
  94. }
  95. private bool IsLibraryMonitorEnabled(BaseItem item)
  96. {
  97. if (item is BasePluginFolder)
  98. {
  99. return false;
  100. }
  101. var options = _libraryManager.GetLibraryOptions(item);
  102. if (options != null)
  103. {
  104. return options.EnableRealtimeMonitor;
  105. }
  106. return false;
  107. }
  108. public void Start()
  109. {
  110. _libraryManager.ItemAdded += OnLibraryManagerItemAdded;
  111. _libraryManager.ItemRemoved += OnLibraryManagerItemRemoved;
  112. var pathsToWatch = new List<string>();
  113. var paths = _libraryManager
  114. .RootFolder
  115. .Children
  116. .Where(IsLibraryMonitorEnabled)
  117. .OfType<Folder>()
  118. .SelectMany(f => f.PhysicalLocations)
  119. .Distinct(StringComparer.OrdinalIgnoreCase)
  120. .OrderBy(i => i)
  121. .ToList();
  122. foreach (var path in paths)
  123. {
  124. if (!ContainsParentFolder(pathsToWatch, path))
  125. {
  126. pathsToWatch.Add(path);
  127. }
  128. }
  129. foreach (var path in pathsToWatch)
  130. {
  131. StartWatchingPath(path);
  132. }
  133. }
  134. private void StartWatching(BaseItem item)
  135. {
  136. if (IsLibraryMonitorEnabled(item))
  137. {
  138. StartWatchingPath(item.Path);
  139. }
  140. }
  141. /// <summary>
  142. /// Handles the ItemRemoved event of the LibraryManager control.
  143. /// </summary>
  144. /// <param name="sender">The source of the event.</param>
  145. /// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
  146. private void OnLibraryManagerItemRemoved(object sender, ItemChangeEventArgs e)
  147. {
  148. if (e.Parent is AggregateFolder)
  149. {
  150. StopWatchingPath(e.Item.Path);
  151. }
  152. }
  153. /// <summary>
  154. /// Handles the ItemAdded event of the LibraryManager control.
  155. /// </summary>
  156. /// <param name="sender">The source of the event.</param>
  157. /// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
  158. private void OnLibraryManagerItemAdded(object sender, ItemChangeEventArgs e)
  159. {
  160. if (e.Parent is AggregateFolder)
  161. {
  162. StartWatching(e.Item);
  163. }
  164. }
  165. /// <summary>
  166. /// Examine a list of strings assumed to be file paths to see if it contains a parent of
  167. /// the provided path.
  168. /// </summary>
  169. /// <param name="lst">The LST.</param>
  170. /// <param name="path">The path.</param>
  171. /// <returns><c>true</c> if [contains parent folder] [the specified LST]; otherwise, <c>false</c>.</returns>
  172. /// <exception cref="ArgumentNullException">path</exception>
  173. private static bool ContainsParentFolder(IEnumerable<string> lst, string path)
  174. {
  175. if (string.IsNullOrEmpty(path))
  176. {
  177. throw new ArgumentNullException(nameof(path));
  178. }
  179. path = path.TrimEnd(Path.DirectorySeparatorChar);
  180. return lst.Any(str =>
  181. {
  182. // this should be a little quicker than examining each actual parent folder...
  183. var compare = str.TrimEnd(Path.DirectorySeparatorChar);
  184. return path.Equals(compare, StringComparison.OrdinalIgnoreCase) || (path.StartsWith(compare, StringComparison.OrdinalIgnoreCase) && path[compare.Length] == Path.DirectorySeparatorChar);
  185. });
  186. }
  187. /// <summary>
  188. /// Starts the watching path.
  189. /// </summary>
  190. /// <param name="path">The path.</param>
  191. private void StartWatchingPath(string path)
  192. {
  193. if (!Directory.Exists(path))
  194. {
  195. // Seeing a crash in the mono runtime due to an exception being thrown on a different thread
  196. _logger.LogInformation("Skipping realtime monitor for {Path} because the path does not exist", path);
  197. return;
  198. }
  199. // Already being watched
  200. if (_fileSystemWatchers.ContainsKey(path))
  201. {
  202. return;
  203. }
  204. // Creating a FileSystemWatcher over the LAN can take hundreds of milliseconds, so wrap it in a Task to do them all in parallel
  205. Task.Run(() =>
  206. {
  207. try
  208. {
  209. var newWatcher = new FileSystemWatcher(path, "*")
  210. {
  211. IncludeSubdirectories = true,
  212. InternalBufferSize = 65536,
  213. NotifyFilter = NotifyFilters.CreationTime |
  214. NotifyFilters.DirectoryName |
  215. NotifyFilters.FileName |
  216. NotifyFilters.LastWrite |
  217. NotifyFilters.Size |
  218. NotifyFilters.Attributes
  219. };
  220. newWatcher.Created += OnWatcherChanged;
  221. newWatcher.Deleted += OnWatcherChanged;
  222. newWatcher.Renamed += OnWatcherChanged;
  223. newWatcher.Changed += OnWatcherChanged;
  224. newWatcher.Error += OnWatcherError;
  225. if (_fileSystemWatchers.TryAdd(path, newWatcher))
  226. {
  227. newWatcher.EnableRaisingEvents = true;
  228. _logger.LogInformation("Watching directory " + path);
  229. }
  230. else
  231. {
  232. DisposeWatcher(newWatcher, false);
  233. }
  234. }
  235. catch (Exception ex)
  236. {
  237. _logger.LogError(ex, "Error watching path: {path}", path);
  238. }
  239. });
  240. }
  241. /// <summary>
  242. /// Stops the watching path.
  243. /// </summary>
  244. /// <param name="path">The path.</param>
  245. private void StopWatchingPath(string path)
  246. {
  247. if (_fileSystemWatchers.TryGetValue(path, out var watcher))
  248. {
  249. DisposeWatcher(watcher, true);
  250. }
  251. }
  252. /// <summary>
  253. /// Disposes the watcher.
  254. /// </summary>
  255. private void DisposeWatcher(FileSystemWatcher watcher, bool removeFromList)
  256. {
  257. try
  258. {
  259. using (watcher)
  260. {
  261. _logger.LogInformation("Stopping directory watching for path {Path}", watcher.Path);
  262. watcher.Created -= OnWatcherChanged;
  263. watcher.Deleted -= OnWatcherChanged;
  264. watcher.Renamed -= OnWatcherChanged;
  265. watcher.Changed -= OnWatcherChanged;
  266. watcher.Error -= OnWatcherError;
  267. watcher.EnableRaisingEvents = false;
  268. }
  269. }
  270. finally
  271. {
  272. if (removeFromList)
  273. {
  274. RemoveWatcherFromList(watcher);
  275. }
  276. }
  277. }
  278. /// <summary>
  279. /// Removes the watcher from list.
  280. /// </summary>
  281. /// <param name="watcher">The watcher.</param>
  282. private void RemoveWatcherFromList(FileSystemWatcher watcher)
  283. {
  284. _fileSystemWatchers.TryRemove(watcher.Path, out _);
  285. }
  286. /// <summary>
  287. /// Handles the Error event of the watcher control.
  288. /// </summary>
  289. /// <param name="sender">The source of the event.</param>
  290. /// <param name="e">The <see cref="ErrorEventArgs" /> instance containing the event data.</param>
  291. private void OnWatcherError(object sender, ErrorEventArgs e)
  292. {
  293. var ex = e.GetException();
  294. var dw = (FileSystemWatcher)sender;
  295. _logger.LogError(ex, "Error in Directory watcher for: {Path}", dw.Path);
  296. DisposeWatcher(dw, true);
  297. }
  298. /// <summary>
  299. /// Handles the Changed event of the watcher control.
  300. /// </summary>
  301. /// <param name="sender">The source of the event.</param>
  302. /// <param name="e">The <see cref="FileSystemEventArgs" /> instance containing the event data.</param>
  303. private void OnWatcherChanged(object sender, FileSystemEventArgs e)
  304. {
  305. try
  306. {
  307. ReportFileSystemChanged(e.FullPath);
  308. }
  309. catch (Exception ex)
  310. {
  311. _logger.LogError(ex, "Exception in ReportFileSystemChanged. Path: {FullPath}", e.FullPath);
  312. }
  313. }
  314. public void ReportFileSystemChanged(string path)
  315. {
  316. if (string.IsNullOrEmpty(path))
  317. {
  318. throw new ArgumentNullException(nameof(path));
  319. }
  320. var monitorPath = !IgnorePatterns.ShouldIgnore(path);
  321. // Ignore certain files
  322. var tempIgnorePaths = _tempIgnoredPaths.Keys.ToList();
  323. // If the parent of an ignored path has a change event, ignore that too
  324. if (tempIgnorePaths.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 += NewRefresher_Completed;
  388. _activeRefreshers.Add(newRefresher);
  389. }
  390. }
  391. private void NewRefresher_Completed(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.Dispose();
  415. _activeRefreshers.Remove(refresher);
  416. }
  417. }
  418. private void DisposeRefreshers()
  419. {
  420. lock (_activeRefreshers)
  421. {
  422. foreach (var refresher in _activeRefreshers.ToList())
  423. {
  424. refresher.Dispose();
  425. }
  426. _activeRefreshers.Clear();
  427. }
  428. }
  429. /// <summary>
  430. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  431. /// </summary>
  432. public void Dispose()
  433. {
  434. Dispose(true);
  435. GC.SuppressFinalize(this);
  436. }
  437. /// <summary>
  438. /// Releases unmanaged and - optionally - managed resources.
  439. /// </summary>
  440. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  441. protected virtual void Dispose(bool disposing)
  442. {
  443. if (_disposed)
  444. {
  445. return;
  446. }
  447. if (disposing)
  448. {
  449. Stop();
  450. }
  451. _disposed = true;
  452. }
  453. }
  454. }