LibraryMonitor.cs 22 KB

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