LibraryMonitor.cs 19 KB

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