LibraryMonitor.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  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 MediaBrowser.Model.System;
  13. using Microsoft.Extensions.Logging;
  14. using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
  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 sytem 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 arbitraty 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 += LibraryManager_ItemAdded;
  141. LibraryManager.ItemRemoved += LibraryManager_ItemRemoved;
  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. void LibraryManager_ItemRemoved(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. void LibraryManager_ItemAdded(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 {0} because the path does not exist", path);
  227. return;
  228. }
  229. if (OperatingSystem.Id != OperatingSystemId.Windows)
  230. {
  231. if (path.StartsWith("\\\\", StringComparison.OrdinalIgnoreCase) || path.StartsWith("smb://", StringComparison.OrdinalIgnoreCase))
  232. {
  233. // not supported
  234. return;
  235. }
  236. }
  237. // Already being watched
  238. if (_fileSystemWatchers.ContainsKey(path))
  239. {
  240. return;
  241. }
  242. // Creating a FileSystemWatcher over the LAN can take hundreds of milliseconds, so wrap it in a Task to do them all in parallel
  243. Task.Run(() =>
  244. {
  245. try
  246. {
  247. var newWatcher = new FileSystemWatcher(path, "*")
  248. {
  249. IncludeSubdirectories = true
  250. };
  251. newWatcher.InternalBufferSize = 65536;
  252. newWatcher.NotifyFilter = NotifyFilters.CreationTime |
  253. NotifyFilters.DirectoryName |
  254. NotifyFilters.FileName |
  255. NotifyFilters.LastWrite |
  256. NotifyFilters.Size |
  257. NotifyFilters.Attributes;
  258. newWatcher.Created += watcher_Changed;
  259. newWatcher.Deleted += watcher_Changed;
  260. newWatcher.Renamed += watcher_Changed;
  261. newWatcher.Changed += watcher_Changed;
  262. newWatcher.Error += watcher_Error;
  263. if (_fileSystemWatchers.TryAdd(path, newWatcher))
  264. {
  265. newWatcher.EnableRaisingEvents = true;
  266. Logger.LogInformation("Watching directory " + path);
  267. }
  268. else
  269. {
  270. DisposeWatcher(newWatcher, false);
  271. }
  272. }
  273. catch (Exception ex)
  274. {
  275. Logger.LogError(ex, "Error watching path: {path}", path);
  276. }
  277. });
  278. }
  279. /// <summary>
  280. /// Stops the watching path.
  281. /// </summary>
  282. /// <param name="path">The path.</param>
  283. private void StopWatchingPath(string path)
  284. {
  285. if (_fileSystemWatchers.TryGetValue(path, out var watcher))
  286. {
  287. DisposeWatcher(watcher, true);
  288. }
  289. }
  290. /// <summary>
  291. /// Disposes the watcher.
  292. /// </summary>
  293. private void DisposeWatcher(FileSystemWatcher watcher, bool removeFromList)
  294. {
  295. try
  296. {
  297. using (watcher)
  298. {
  299. Logger.LogInformation("Stopping directory watching for path {path}", watcher.Path);
  300. watcher.Created -= watcher_Changed;
  301. watcher.Deleted -= watcher_Changed;
  302. watcher.Renamed -= watcher_Changed;
  303. watcher.Changed -= watcher_Changed;
  304. watcher.Error -= watcher_Error;
  305. try
  306. {
  307. watcher.EnableRaisingEvents = false;
  308. }
  309. catch (InvalidOperationException)
  310. {
  311. // Seeing this under mono on linux sometimes
  312. // Collection was modified; enumeration operation may not execute.
  313. }
  314. }
  315. }
  316. catch (NotImplementedException)
  317. {
  318. // the dispose method on FileSystemWatcher is sometimes throwing NotImplementedException on Xamarin Android
  319. }
  320. catch
  321. {
  322. }
  323. finally
  324. {
  325. if (removeFromList)
  326. {
  327. RemoveWatcherFromList(watcher);
  328. }
  329. }
  330. }
  331. /// <summary>
  332. /// Removes the watcher from list.
  333. /// </summary>
  334. /// <param name="watcher">The watcher.</param>
  335. private void RemoveWatcherFromList(FileSystemWatcher watcher)
  336. {
  337. _fileSystemWatchers.TryRemove(watcher.Path, out var removed);
  338. }
  339. /// <summary>
  340. /// Handles the Error event of the watcher control.
  341. /// </summary>
  342. /// <param name="sender">The source of the event.</param>
  343. /// <param name="e">The <see cref="ErrorEventArgs" /> instance containing the event data.</param>
  344. void watcher_Error(object sender, ErrorEventArgs e)
  345. {
  346. var ex = e.GetException();
  347. var dw = (FileSystemWatcher)sender;
  348. Logger.LogError(ex, "Error in Directory watcher for: {path}", dw.Path);
  349. DisposeWatcher(dw, true);
  350. }
  351. /// <summary>
  352. /// Handles the Changed event of the watcher control.
  353. /// </summary>
  354. /// <param name="sender">The source of the event.</param>
  355. /// <param name="e">The <see cref="FileSystemEventArgs" /> instance containing the event data.</param>
  356. void watcher_Changed(object sender, FileSystemEventArgs e)
  357. {
  358. try
  359. {
  360. //logger.LogDebug("Changed detected of type " + e.ChangeType + " to " + e.FullPath);
  361. var path = e.FullPath;
  362. ReportFileSystemChanged(path);
  363. }
  364. catch (Exception ex)
  365. {
  366. Logger.LogError(ex, "Exception in ReportFileSystemChanged. Path: {FullPath}", e.FullPath);
  367. }
  368. }
  369. public void ReportFileSystemChanged(string path)
  370. {
  371. if (string.IsNullOrEmpty(path))
  372. {
  373. throw new ArgumentNullException(nameof(path));
  374. }
  375. var filename = Path.GetFileName(path);
  376. var monitorPath = !string.IsNullOrEmpty(filename) &&
  377. !_alwaysIgnoreFiles.Contains(filename) &&
  378. !_alwaysIgnoreExtensions.Contains(Path.GetExtension(path)) &&
  379. _alwaysIgnoreSubstrings.All(i => path.IndexOf(i, StringComparison.OrdinalIgnoreCase) == -1);
  380. // Ignore certain files
  381. var tempIgnorePaths = _tempIgnoredPaths.Keys.ToList();
  382. // If the parent of an ignored path has a change event, ignore that too
  383. if (tempIgnorePaths.Any(i =>
  384. {
  385. if (_fileSystem.AreEqual(i, path))
  386. {
  387. Logger.LogDebug("Ignoring change to {path}", path);
  388. return true;
  389. }
  390. if (_fileSystem.ContainsSubPath(i, path))
  391. {
  392. Logger.LogDebug("Ignoring change to {path}", path);
  393. return true;
  394. }
  395. // Go up a level
  396. var parent = Path.GetDirectoryName(i);
  397. if (!string.IsNullOrEmpty(parent))
  398. {
  399. if (_fileSystem.AreEqual(parent, path))
  400. {
  401. Logger.LogDebug("Ignoring change to {path}", path);
  402. return true;
  403. }
  404. }
  405. return false;
  406. }))
  407. {
  408. monitorPath = false;
  409. }
  410. if (monitorPath)
  411. {
  412. // Avoid implicitly captured closure
  413. CreateRefresher(path);
  414. }
  415. }
  416. private void CreateRefresher(string path)
  417. {
  418. var parentPath = Path.GetDirectoryName(path);
  419. lock (_activeRefreshers)
  420. {
  421. var refreshers = _activeRefreshers.ToList();
  422. foreach (var refresher in refreshers)
  423. {
  424. // Path is already being refreshed
  425. if (_fileSystem.AreEqual(path, refresher.Path))
  426. {
  427. refresher.RestartTimer();
  428. return;
  429. }
  430. // Parent folder is already being refreshed
  431. if (_fileSystem.ContainsSubPath(refresher.Path, path))
  432. {
  433. refresher.AddPath(path);
  434. return;
  435. }
  436. // New path is a parent
  437. if (_fileSystem.ContainsSubPath(path, refresher.Path))
  438. {
  439. refresher.ResetPath(path, null);
  440. return;
  441. }
  442. // They are siblings. Rebase the refresher to the parent folder.
  443. if (string.Equals(parentPath, Path.GetDirectoryName(refresher.Path), StringComparison.Ordinal))
  444. {
  445. refresher.ResetPath(parentPath, path);
  446. return;
  447. }
  448. }
  449. var newRefresher = new FileRefresher(path, ConfigurationManager, LibraryManager, Logger);
  450. newRefresher.Completed += NewRefresher_Completed;
  451. _activeRefreshers.Add(newRefresher);
  452. }
  453. }
  454. private void NewRefresher_Completed(object sender, EventArgs e)
  455. {
  456. var refresher = (FileRefresher)sender;
  457. DisposeRefresher(refresher);
  458. }
  459. /// <summary>
  460. /// Stops this instance.
  461. /// </summary>
  462. public void Stop()
  463. {
  464. LibraryManager.ItemAdded -= LibraryManager_ItemAdded;
  465. LibraryManager.ItemRemoved -= LibraryManager_ItemRemoved;
  466. foreach (var watcher in _fileSystemWatchers.Values.ToList())
  467. {
  468. DisposeWatcher(watcher, false);
  469. }
  470. _fileSystemWatchers.Clear();
  471. DisposeRefreshers();
  472. }
  473. private void DisposeRefresher(FileRefresher refresher)
  474. {
  475. lock (_activeRefreshers)
  476. {
  477. refresher.Dispose();
  478. _activeRefreshers.Remove(refresher);
  479. }
  480. }
  481. private void DisposeRefreshers()
  482. {
  483. lock (_activeRefreshers)
  484. {
  485. foreach (var refresher in _activeRefreshers.ToList())
  486. {
  487. refresher.Dispose();
  488. }
  489. _activeRefreshers.Clear();
  490. }
  491. }
  492. private bool _disposed;
  493. /// <summary>
  494. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  495. /// </summary>
  496. public void Dispose()
  497. {
  498. Dispose(true);
  499. }
  500. /// <summary>
  501. /// Releases unmanaged and - optionally - managed resources.
  502. /// </summary>
  503. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  504. protected virtual void Dispose(bool disposing)
  505. {
  506. if (_disposed)
  507. {
  508. return;
  509. }
  510. if (disposing)
  511. {
  512. Stop();
  513. }
  514. _disposed = true;
  515. }
  516. }
  517. public class LibraryMonitorStartup : IServerEntryPoint
  518. {
  519. private readonly ILibraryMonitor _monitor;
  520. public LibraryMonitorStartup(ILibraryMonitor monitor)
  521. {
  522. _monitor = monitor;
  523. }
  524. public Task RunAsync()
  525. {
  526. _monitor.Start();
  527. return Task.CompletedTask;
  528. }
  529. public void Dispose()
  530. {
  531. }
  532. }
  533. }