LibraryMonitor.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  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.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 IReadOnlyList<string> _alwaysIgnoreFiles = new List<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 IReadOnlyList<string> _alwaysIgnoreSubstrings = new List<string>
  44. {
  45. // Synology
  46. "eaDir",
  47. "#recycle",
  48. ".wd_tv",
  49. ".actors"
  50. };
  51. private readonly IReadOnlyList<string> _alwaysIgnoreExtensions = new List<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("path");
  72. }
  73. TemporarilyIgnore(path);
  74. }
  75. public bool IsPathLocked(string path)
  76. {
  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("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. string val;
  91. _tempIgnoredPaths.TryRemove(path, out val);
  92. if (refreshPath)
  93. {
  94. try
  95. {
  96. ReportFileSystemChanged(path);
  97. }
  98. catch (Exception ex)
  99. {
  100. Logger.ErrorException("Error in ReportFileSystemChanged for {0}", ex, 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(ILogManager logManager, ITaskManager taskManager, ILibraryManager libraryManager, IServerConfigurationManager configurationManager, IFileSystem fileSystem, ITimerFactory timerFactory, ISystemEvents systemEvents, IEnvironmentInfo environmentInfo)
  123. {
  124. if (taskManager == null)
  125. {
  126. throw new ArgumentNullException("taskManager");
  127. }
  128. LibraryManager = libraryManager;
  129. TaskManager = taskManager;
  130. Logger = logManager.GetLogger(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.Item.GetParent() 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.Item.GetParent() 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="System.ArgumentNullException">path</exception>
  227. private static bool ContainsParentFolder(IEnumerable<string> lst, string path)
  228. {
  229. if (string.IsNullOrWhiteSpace(path))
  230. {
  231. throw new ArgumentNullException("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.Info("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. // Already being watched
  262. if (_fileSystemWatchers.ContainsKey(path))
  263. {
  264. return;
  265. }
  266. // Creating a FileSystemWatcher over the LAN can take hundreds of milliseconds, so wrap it in a Task to do them all in parallel
  267. Task.Run(() =>
  268. {
  269. try
  270. {
  271. var newWatcher = new FileSystemWatcher(path, "*")
  272. {
  273. IncludeSubdirectories = true
  274. };
  275. if (_environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows)
  276. {
  277. newWatcher.InternalBufferSize = 32767;
  278. }
  279. newWatcher.NotifyFilter = NotifyFilters.CreationTime |
  280. NotifyFilters.DirectoryName |
  281. NotifyFilters.FileName |
  282. NotifyFilters.LastWrite |
  283. NotifyFilters.Size |
  284. NotifyFilters.Attributes;
  285. newWatcher.Created += watcher_Changed;
  286. // Seeing mono crashes on background threads we can't catch, testing if this might help
  287. if (_environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows)
  288. {
  289. newWatcher.Deleted += watcher_Changed;
  290. }
  291. newWatcher.Renamed += watcher_Changed;
  292. newWatcher.Changed += watcher_Changed;
  293. newWatcher.Error += watcher_Error;
  294. if (_fileSystemWatchers.TryAdd(path, newWatcher))
  295. {
  296. newWatcher.EnableRaisingEvents = true;
  297. Logger.Info("Watching directory " + path);
  298. }
  299. else
  300. {
  301. newWatcher.Dispose();
  302. }
  303. }
  304. catch (Exception ex)
  305. {
  306. Logger.ErrorException("Error watching path: {0}", ex, path);
  307. }
  308. });
  309. }
  310. /// <summary>
  311. /// Stops the watching path.
  312. /// </summary>
  313. /// <param name="path">The path.</param>
  314. private void StopWatchingPath(string path)
  315. {
  316. FileSystemWatcher watcher;
  317. if (_fileSystemWatchers.TryGetValue(path, out watcher))
  318. {
  319. DisposeWatcher(watcher);
  320. }
  321. }
  322. /// <summary>
  323. /// Disposes the watcher.
  324. /// </summary>
  325. /// <param name="watcher">The watcher.</param>
  326. private void DisposeWatcher(FileSystemWatcher watcher)
  327. {
  328. try
  329. {
  330. using (watcher)
  331. {
  332. Logger.Info("Stopping directory watching for path {0}", watcher.Path);
  333. watcher.EnableRaisingEvents = false;
  334. }
  335. }
  336. catch
  337. {
  338. }
  339. finally
  340. {
  341. RemoveWatcherFromList(watcher);
  342. }
  343. }
  344. /// <summary>
  345. /// Removes the watcher from list.
  346. /// </summary>
  347. /// <param name="watcher">The watcher.</param>
  348. private void RemoveWatcherFromList(FileSystemWatcher watcher)
  349. {
  350. FileSystemWatcher removed;
  351. _fileSystemWatchers.TryRemove(watcher.Path, out removed);
  352. }
  353. /// <summary>
  354. /// Handles the Error event of the watcher control.
  355. /// </summary>
  356. /// <param name="sender">The source of the event.</param>
  357. /// <param name="e">The <see cref="ErrorEventArgs" /> instance containing the event data.</param>
  358. void watcher_Error(object sender, ErrorEventArgs e)
  359. {
  360. var ex = e.GetException();
  361. var dw = (FileSystemWatcher)sender;
  362. Logger.ErrorException("Error in Directory watcher for: " + dw.Path, ex);
  363. DisposeWatcher(dw);
  364. }
  365. /// <summary>
  366. /// Handles the Changed event of the watcher control.
  367. /// </summary>
  368. /// <param name="sender">The source of the event.</param>
  369. /// <param name="e">The <see cref="FileSystemEventArgs" /> instance containing the event data.</param>
  370. void watcher_Changed(object sender, FileSystemEventArgs e)
  371. {
  372. try
  373. {
  374. //Logger.Debug("Changed detected of type " + e.ChangeType + " to " + e.FullPath);
  375. var path = e.FullPath;
  376. ReportFileSystemChanged(path);
  377. }
  378. catch (Exception ex)
  379. {
  380. Logger.ErrorException("Exception in ReportFileSystemChanged. Path: {0}", ex, e.FullPath);
  381. }
  382. }
  383. public void ReportFileSystemChanged(string path)
  384. {
  385. if (string.IsNullOrEmpty(path))
  386. {
  387. throw new ArgumentNullException("path");
  388. }
  389. var filename = Path.GetFileName(path);
  390. var monitorPath = !string.IsNullOrEmpty(filename) &&
  391. !_alwaysIgnoreFiles.Contains(filename, StringComparer.OrdinalIgnoreCase) &&
  392. !_alwaysIgnoreExtensions.Contains(Path.GetExtension(path) ?? string.Empty, StringComparer.OrdinalIgnoreCase) &&
  393. _alwaysIgnoreSubstrings.All(i => path.IndexOf(i, StringComparison.OrdinalIgnoreCase) == -1);
  394. // Ignore certain files
  395. var tempIgnorePaths = _tempIgnoredPaths.Keys.ToList();
  396. // If the parent of an ignored path has a change event, ignore that too
  397. if (tempIgnorePaths.Any(i =>
  398. {
  399. if (_fileSystem.AreEqual(i, path))
  400. {
  401. Logger.Debug("Ignoring change to {0}", path);
  402. return true;
  403. }
  404. if (_fileSystem.ContainsSubPath(i, path))
  405. {
  406. Logger.Debug("Ignoring change to {0}", path);
  407. return true;
  408. }
  409. // Go up a level
  410. var parent = _fileSystem.GetDirectoryName(i);
  411. if (!string.IsNullOrEmpty(parent))
  412. {
  413. if (_fileSystem.AreEqual(parent, path))
  414. {
  415. Logger.Debug("Ignoring change to {0}", path);
  416. return true;
  417. }
  418. }
  419. return false;
  420. }))
  421. {
  422. monitorPath = false;
  423. }
  424. if (monitorPath)
  425. {
  426. // Avoid implicitly captured closure
  427. CreateRefresher(path);
  428. }
  429. }
  430. private void CreateRefresher(string path)
  431. {
  432. var parentPath = _fileSystem.GetDirectoryName(path);
  433. lock (_activeRefreshers)
  434. {
  435. var refreshers = _activeRefreshers.ToList();
  436. foreach (var refresher in refreshers)
  437. {
  438. // Path is already being refreshed
  439. if (_fileSystem.AreEqual(path, refresher.Path))
  440. {
  441. refresher.RestartTimer();
  442. return;
  443. }
  444. // Parent folder is already being refreshed
  445. if (_fileSystem.ContainsSubPath(refresher.Path, path))
  446. {
  447. refresher.AddPath(path);
  448. return;
  449. }
  450. // New path is a parent
  451. if (_fileSystem.ContainsSubPath(path, refresher.Path))
  452. {
  453. refresher.ResetPath(path, null);
  454. return;
  455. }
  456. // They are siblings. Rebase the refresher to the parent folder.
  457. if (string.Equals(parentPath, _fileSystem.GetDirectoryName(refresher.Path), StringComparison.Ordinal))
  458. {
  459. refresher.ResetPath(parentPath, path);
  460. return;
  461. }
  462. }
  463. var newRefresher = new FileRefresher(path, _fileSystem, ConfigurationManager, LibraryManager, TaskManager, Logger, _timerFactory, _environmentInfo, LibraryManager);
  464. newRefresher.Completed += NewRefresher_Completed;
  465. _activeRefreshers.Add(newRefresher);
  466. }
  467. }
  468. private void NewRefresher_Completed(object sender, EventArgs e)
  469. {
  470. var refresher = (FileRefresher)sender;
  471. DisposeRefresher(refresher);
  472. }
  473. /// <summary>
  474. /// Stops this instance.
  475. /// </summary>
  476. public void Stop()
  477. {
  478. LibraryManager.ItemAdded -= LibraryManager_ItemAdded;
  479. LibraryManager.ItemRemoved -= LibraryManager_ItemRemoved;
  480. foreach (var watcher in _fileSystemWatchers.Values.ToList())
  481. {
  482. watcher.Created -= watcher_Changed;
  483. watcher.Deleted -= watcher_Changed;
  484. watcher.Renamed -= watcher_Changed;
  485. watcher.Changed -= watcher_Changed;
  486. try
  487. {
  488. watcher.EnableRaisingEvents = false;
  489. }
  490. catch (InvalidOperationException)
  491. {
  492. // Seeing this under mono on linux sometimes
  493. // Collection was modified; enumeration operation may not execute.
  494. }
  495. watcher.Dispose();
  496. }
  497. _fileSystemWatchers.Clear();
  498. DisposeRefreshers();
  499. }
  500. private void DisposeRefresher(FileRefresher refresher)
  501. {
  502. lock (_activeRefreshers)
  503. {
  504. refresher.Dispose();
  505. _activeRefreshers.Remove(refresher);
  506. }
  507. }
  508. private void DisposeRefreshers()
  509. {
  510. lock (_activeRefreshers)
  511. {
  512. foreach (var refresher in _activeRefreshers.ToList())
  513. {
  514. refresher.Dispose();
  515. }
  516. _activeRefreshers.Clear();
  517. }
  518. }
  519. private bool _disposed;
  520. /// <summary>
  521. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  522. /// </summary>
  523. public void Dispose()
  524. {
  525. _disposed = true;
  526. Dispose(true);
  527. GC.SuppressFinalize(this);
  528. }
  529. /// <summary>
  530. /// Releases unmanaged and - optionally - managed resources.
  531. /// </summary>
  532. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  533. protected virtual void Dispose(bool dispose)
  534. {
  535. if (dispose)
  536. {
  537. Stop();
  538. }
  539. }
  540. }
  541. public class LibraryMonitorStartup : IServerEntryPoint
  542. {
  543. private readonly ILibraryMonitor _monitor;
  544. public LibraryMonitorStartup(ILibraryMonitor monitor)
  545. {
  546. _monitor = monitor;
  547. }
  548. public void Run()
  549. {
  550. _monitor.Start();
  551. }
  552. public void Dispose()
  553. {
  554. }
  555. }
  556. }