2
0

LibraryMonitor.cs 20 KB

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