LibraryMonitor.cs 21 KB

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