LibraryMonitor.cs 22 KB

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