LibraryMonitor.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  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 MediaBrowser.Model.Tasks;
  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 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 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 readonly string[] _alwaysIgnoreSubstrings = new string[]
  43. {
  44. // Synology
  45. "eaDir",
  46. "#recycle",
  47. ".wd_tv",
  48. ".actors"
  49. };
  50. private 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. /// <summary>
  109. /// Gets or sets the task manager.
  110. /// </summary>
  111. /// <value>The task manager.</value>
  112. private ITaskManager TaskManager { get; set; }
  113. private ILibraryManager LibraryManager { get; set; }
  114. private IServerConfigurationManager ConfigurationManager { get; set; }
  115. private readonly IFileSystem _fileSystem;
  116. private readonly IEnvironmentInfo _environmentInfo;
  117. /// <summary>
  118. /// Initializes a new instance of the <see cref="LibraryMonitor" /> class.
  119. /// </summary>
  120. public LibraryMonitor(
  121. ILoggerFactory loggerFactory,
  122. ITaskManager taskManager,
  123. ILibraryManager libraryManager,
  124. IServerConfigurationManager configurationManager,
  125. IFileSystem fileSystem,
  126. IEnvironmentInfo environmentInfo)
  127. {
  128. if (taskManager == null)
  129. {
  130. throw new ArgumentNullException(nameof(taskManager));
  131. }
  132. LibraryManager = libraryManager;
  133. TaskManager = taskManager;
  134. Logger = loggerFactory.CreateLogger(GetType().Name);
  135. ConfigurationManager = configurationManager;
  136. _fileSystem = fileSystem;
  137. _environmentInfo = environmentInfo;
  138. }
  139. private bool IsLibraryMonitorEnabled(BaseItem item)
  140. {
  141. if (item is BasePluginFolder)
  142. {
  143. return false;
  144. }
  145. var options = LibraryManager.GetLibraryOptions(item);
  146. if (options != null)
  147. {
  148. return options.EnableRealtimeMonitor;
  149. }
  150. return false;
  151. }
  152. public void Start()
  153. {
  154. LibraryManager.ItemAdded += LibraryManager_ItemAdded;
  155. LibraryManager.ItemRemoved += LibraryManager_ItemRemoved;
  156. var pathsToWatch = new List<string> { };
  157. var paths = LibraryManager
  158. .RootFolder
  159. .Children
  160. .Where(IsLibraryMonitorEnabled)
  161. .OfType<Folder>()
  162. .SelectMany(f => f.PhysicalLocations)
  163. .Distinct(StringComparer.OrdinalIgnoreCase)
  164. .OrderBy(i => i)
  165. .ToList();
  166. foreach (var path in paths)
  167. {
  168. if (!ContainsParentFolder(pathsToWatch, path))
  169. {
  170. pathsToWatch.Add(path);
  171. }
  172. }
  173. foreach (var path in pathsToWatch)
  174. {
  175. StartWatchingPath(path);
  176. }
  177. }
  178. private void StartWatching(BaseItem item)
  179. {
  180. if (IsLibraryMonitorEnabled(item))
  181. {
  182. StartWatchingPath(item.Path);
  183. }
  184. }
  185. /// <summary>
  186. /// Handles the ItemRemoved event of the LibraryManager control.
  187. /// </summary>
  188. /// <param name="sender">The source of the event.</param>
  189. /// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
  190. void LibraryManager_ItemRemoved(object sender, ItemChangeEventArgs e)
  191. {
  192. if (e.Parent is AggregateFolder)
  193. {
  194. StopWatchingPath(e.Item.Path);
  195. }
  196. }
  197. /// <summary>
  198. /// Handles the ItemAdded event of the LibraryManager control.
  199. /// </summary>
  200. /// <param name="sender">The source of the event.</param>
  201. /// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
  202. void LibraryManager_ItemAdded(object sender, ItemChangeEventArgs e)
  203. {
  204. if (e.Parent is AggregateFolder)
  205. {
  206. StartWatching(e.Item);
  207. }
  208. }
  209. /// <summary>
  210. /// Examine a list of strings assumed to be file paths to see if it contains a parent of
  211. /// the provided path.
  212. /// </summary>
  213. /// <param name="lst">The LST.</param>
  214. /// <param name="path">The path.</param>
  215. /// <returns><c>true</c> if [contains parent folder] [the specified LST]; otherwise, <c>false</c>.</returns>
  216. /// <exception cref="ArgumentNullException">path</exception>
  217. private static bool ContainsParentFolder(IEnumerable<string> lst, string path)
  218. {
  219. if (string.IsNullOrEmpty(path))
  220. {
  221. throw new ArgumentNullException(nameof(path));
  222. }
  223. path = path.TrimEnd(Path.DirectorySeparatorChar);
  224. return lst.Any(str =>
  225. {
  226. //this should be a little quicker than examining each actual parent folder...
  227. var compare = str.TrimEnd(Path.DirectorySeparatorChar);
  228. return path.Equals(compare, StringComparison.OrdinalIgnoreCase) || (path.StartsWith(compare, StringComparison.OrdinalIgnoreCase) && path[compare.Length] == Path.DirectorySeparatorChar);
  229. });
  230. }
  231. /// <summary>
  232. /// Starts the watching path.
  233. /// </summary>
  234. /// <param name="path">The path.</param>
  235. private void StartWatchingPath(string path)
  236. {
  237. if (!Directory.Exists(path))
  238. {
  239. // Seeing a crash in the mono runtime due to an exception being thrown on a different thread
  240. Logger.LogInformation("Skipping realtime monitor for {0} because the path does not exist", path);
  241. return;
  242. }
  243. if (_environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows)
  244. {
  245. if (path.StartsWith("\\\\", StringComparison.OrdinalIgnoreCase) || path.StartsWith("smb://", StringComparison.OrdinalIgnoreCase))
  246. {
  247. // not supported
  248. return;
  249. }
  250. }
  251. if (_environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Android)
  252. {
  253. // causing crashing
  254. return;
  255. }
  256. // Already being watched
  257. if (_fileSystemWatchers.ContainsKey(path))
  258. {
  259. return;
  260. }
  261. // Creating a FileSystemWatcher over the LAN can take hundreds of milliseconds, so wrap it in a Task to do them all in parallel
  262. Task.Run(() =>
  263. {
  264. try
  265. {
  266. var newWatcher = new FileSystemWatcher(path, "*")
  267. {
  268. IncludeSubdirectories = true
  269. };
  270. newWatcher.InternalBufferSize = 65536;
  271. newWatcher.NotifyFilter = NotifyFilters.CreationTime |
  272. NotifyFilters.DirectoryName |
  273. NotifyFilters.FileName |
  274. NotifyFilters.LastWrite |
  275. NotifyFilters.Size |
  276. NotifyFilters.Attributes;
  277. newWatcher.Created += watcher_Changed;
  278. newWatcher.Deleted += watcher_Changed;
  279. newWatcher.Renamed += watcher_Changed;
  280. newWatcher.Changed += watcher_Changed;
  281. newWatcher.Error += watcher_Error;
  282. if (_fileSystemWatchers.TryAdd(path, newWatcher))
  283. {
  284. newWatcher.EnableRaisingEvents = true;
  285. Logger.LogInformation("Watching directory " + path);
  286. }
  287. else
  288. {
  289. DisposeWatcher(newWatcher, false);
  290. }
  291. }
  292. catch (Exception ex)
  293. {
  294. Logger.LogError(ex, "Error watching path: {path}", path);
  295. }
  296. });
  297. }
  298. /// <summary>
  299. /// Stops the watching path.
  300. /// </summary>
  301. /// <param name="path">The path.</param>
  302. private void StopWatchingPath(string path)
  303. {
  304. if (_fileSystemWatchers.TryGetValue(path, out var watcher))
  305. {
  306. DisposeWatcher(watcher, true);
  307. }
  308. }
  309. /// <summary>
  310. /// Disposes the watcher.
  311. /// </summary>
  312. private void DisposeWatcher(FileSystemWatcher watcher, bool removeFromList)
  313. {
  314. try
  315. {
  316. using (watcher)
  317. {
  318. Logger.LogInformation("Stopping directory watching for path {path}", watcher.Path);
  319. watcher.Created -= watcher_Changed;
  320. watcher.Deleted -= watcher_Changed;
  321. watcher.Renamed -= watcher_Changed;
  322. watcher.Changed -= watcher_Changed;
  323. watcher.Error -= watcher_Error;
  324. try
  325. {
  326. watcher.EnableRaisingEvents = false;
  327. }
  328. catch (InvalidOperationException)
  329. {
  330. // Seeing this under mono on linux sometimes
  331. // Collection was modified; enumeration operation may not execute.
  332. }
  333. }
  334. }
  335. catch (NotImplementedException)
  336. {
  337. // the dispose method on FileSystemWatcher is sometimes throwing NotImplementedException on Xamarin Android
  338. }
  339. catch
  340. {
  341. }
  342. finally
  343. {
  344. if (removeFromList)
  345. {
  346. RemoveWatcherFromList(watcher);
  347. }
  348. }
  349. }
  350. /// <summary>
  351. /// Removes the watcher from list.
  352. /// </summary>
  353. /// <param name="watcher">The watcher.</param>
  354. private void RemoveWatcherFromList(FileSystemWatcher watcher)
  355. {
  356. _fileSystemWatchers.TryRemove(watcher.Path, out var removed);
  357. }
  358. /// <summary>
  359. /// Handles the Error event of the watcher control.
  360. /// </summary>
  361. /// <param name="sender">The source of the event.</param>
  362. /// <param name="e">The <see cref="ErrorEventArgs" /> instance containing the event data.</param>
  363. void watcher_Error(object sender, ErrorEventArgs e)
  364. {
  365. var ex = e.GetException();
  366. var dw = (FileSystemWatcher)sender;
  367. Logger.LogError(ex, "Error in Directory watcher for: {path}", dw.Path);
  368. DisposeWatcher(dw, true);
  369. }
  370. /// <summary>
  371. /// Handles the Changed event of the watcher control.
  372. /// </summary>
  373. /// <param name="sender">The source of the event.</param>
  374. /// <param name="e">The <see cref="FileSystemEventArgs" /> instance containing the event data.</param>
  375. void watcher_Changed(object sender, FileSystemEventArgs e)
  376. {
  377. try
  378. {
  379. //logger.LogDebug("Changed detected of type " + e.ChangeType + " to " + e.FullPath);
  380. var path = e.FullPath;
  381. ReportFileSystemChanged(path);
  382. }
  383. catch (Exception ex)
  384. {
  385. Logger.LogError(ex, "Exception in ReportFileSystemChanged. Path: {FullPath}", e.FullPath);
  386. }
  387. }
  388. public void ReportFileSystemChanged(string path)
  389. {
  390. if (string.IsNullOrEmpty(path))
  391. {
  392. throw new ArgumentNullException(nameof(path));
  393. }
  394. var filename = Path.GetFileName(path);
  395. var monitorPath = !string.IsNullOrEmpty(filename) &&
  396. !_alwaysIgnoreFiles.Contains(filename) &&
  397. !_alwaysIgnoreExtensions.Contains(Path.GetExtension(path)) &&
  398. _alwaysIgnoreSubstrings.All(i => path.IndexOf(i, StringComparison.OrdinalIgnoreCase) == -1);
  399. // Ignore certain files
  400. var tempIgnorePaths = _tempIgnoredPaths.Keys.ToList();
  401. // If the parent of an ignored path has a change event, ignore that too
  402. if (tempIgnorePaths.Any(i =>
  403. {
  404. if (_fileSystem.AreEqual(i, path))
  405. {
  406. Logger.LogDebug("Ignoring change to {path}", path);
  407. return true;
  408. }
  409. if (_fileSystem.ContainsSubPath(i, path))
  410. {
  411. Logger.LogDebug("Ignoring change to {path}", path);
  412. return true;
  413. }
  414. // Go up a level
  415. var parent = Path.GetDirectoryName(i);
  416. if (!string.IsNullOrEmpty(parent))
  417. {
  418. if (_fileSystem.AreEqual(parent, path))
  419. {
  420. Logger.LogDebug("Ignoring change to {path}", path);
  421. return true;
  422. }
  423. }
  424. return false;
  425. }))
  426. {
  427. monitorPath = false;
  428. }
  429. if (monitorPath)
  430. {
  431. // Avoid implicitly captured closure
  432. CreateRefresher(path);
  433. }
  434. }
  435. private void CreateRefresher(string path)
  436. {
  437. var parentPath = Path.GetDirectoryName(path);
  438. lock (_activeRefreshers)
  439. {
  440. var refreshers = _activeRefreshers.ToList();
  441. foreach (var refresher in refreshers)
  442. {
  443. // Path is already being refreshed
  444. if (_fileSystem.AreEqual(path, refresher.Path))
  445. {
  446. refresher.RestartTimer();
  447. return;
  448. }
  449. // Parent folder is already being refreshed
  450. if (_fileSystem.ContainsSubPath(refresher.Path, path))
  451. {
  452. refresher.AddPath(path);
  453. return;
  454. }
  455. // New path is a parent
  456. if (_fileSystem.ContainsSubPath(path, refresher.Path))
  457. {
  458. refresher.ResetPath(path, null);
  459. return;
  460. }
  461. // They are siblings. Rebase the refresher to the parent folder.
  462. if (string.Equals(parentPath, Path.GetDirectoryName(refresher.Path), StringComparison.Ordinal))
  463. {
  464. refresher.ResetPath(parentPath, path);
  465. return;
  466. }
  467. }
  468. var newRefresher = new FileRefresher(path, _fileSystem, ConfigurationManager, LibraryManager, TaskManager, Logger, _environmentInfo, LibraryManager);
  469. newRefresher.Completed += NewRefresher_Completed;
  470. _activeRefreshers.Add(newRefresher);
  471. }
  472. }
  473. private void NewRefresher_Completed(object sender, EventArgs e)
  474. {
  475. var refresher = (FileRefresher)sender;
  476. DisposeRefresher(refresher);
  477. }
  478. /// <summary>
  479. /// Stops this instance.
  480. /// </summary>
  481. public void Stop()
  482. {
  483. LibraryManager.ItemAdded -= LibraryManager_ItemAdded;
  484. LibraryManager.ItemRemoved -= LibraryManager_ItemRemoved;
  485. foreach (var watcher in _fileSystemWatchers.Values.ToList())
  486. {
  487. DisposeWatcher(watcher, false);
  488. }
  489. _fileSystemWatchers.Clear();
  490. DisposeRefreshers();
  491. }
  492. private void DisposeRefresher(FileRefresher refresher)
  493. {
  494. lock (_activeRefreshers)
  495. {
  496. refresher.Dispose();
  497. _activeRefreshers.Remove(refresher);
  498. }
  499. }
  500. private void DisposeRefreshers()
  501. {
  502. lock (_activeRefreshers)
  503. {
  504. foreach (var refresher in _activeRefreshers.ToList())
  505. {
  506. refresher.Dispose();
  507. }
  508. _activeRefreshers.Clear();
  509. }
  510. }
  511. private bool _disposed;
  512. /// <summary>
  513. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  514. /// </summary>
  515. public void Dispose()
  516. {
  517. Dispose(true);
  518. }
  519. /// <summary>
  520. /// Releases unmanaged and - optionally - managed resources.
  521. /// </summary>
  522. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  523. protected virtual void Dispose(bool disposing)
  524. {
  525. if (_disposed)
  526. {
  527. return;
  528. }
  529. if (disposing)
  530. {
  531. Stop();
  532. }
  533. _disposed = true;
  534. }
  535. }
  536. public class LibraryMonitorStartup : IServerEntryPoint
  537. {
  538. private readonly ILibraryMonitor _monitor;
  539. public LibraryMonitorStartup(ILibraryMonitor monitor)
  540. {
  541. _monitor = monitor;
  542. }
  543. public Task RunAsync()
  544. {
  545. _monitor.Start();
  546. return Task.CompletedTask;
  547. }
  548. public void Dispose()
  549. {
  550. }
  551. }
  552. }