LibraryMonitor.cs 21 KB

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