LibraryMonitor.cs 18 KB

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