LibraryMonitor.cs 19 KB

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