LibraryMonitor.cs 21 KB

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