LibraryMonitor.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.ScheduledTasks;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.Plugins;
  7. using MediaBrowser.Model.Configuration;
  8. using MediaBrowser.Model.Logging;
  9. using MediaBrowser.Server.Implementations.ScheduledTasks;
  10. using Microsoft.Win32;
  11. using System;
  12. using System.Collections.Concurrent;
  13. using System.Collections.Generic;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. namespace MediaBrowser.Server.Implementations.IO
  19. {
  20. public class LibraryMonitor : ILibraryMonitor
  21. {
  22. /// <summary>
  23. /// The file system watchers
  24. /// </summary>
  25. private readonly ConcurrentDictionary<string, FileSystemWatcher> _fileSystemWatchers = new ConcurrentDictionary<string, FileSystemWatcher>(StringComparer.OrdinalIgnoreCase);
  26. /// <summary>
  27. /// The update timer
  28. /// </summary>
  29. private Timer _updateTimer;
  30. /// <summary>
  31. /// The affected paths
  32. /// </summary>
  33. private readonly ConcurrentDictionary<string, string> _affectedPaths = new ConcurrentDictionary<string, string>();
  34. /// <summary>
  35. /// A dynamic list of paths that should be ignored. Added to during our own file sytem modifications.
  36. /// </summary>
  37. private readonly ConcurrentDictionary<string, string> _tempIgnoredPaths = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  38. /// <summary>
  39. /// Any file name ending in any of these will be ignored by the watchers
  40. /// </summary>
  41. private readonly IReadOnlyList<string> _alwaysIgnoreFiles = new List<string>
  42. {
  43. "thumbs.db",
  44. "small.jpg",
  45. "albumart.jpg",
  46. // WMC temp recording directories that will constantly be written to
  47. "TempRec",
  48. "TempSBE"
  49. };
  50. /// <summary>
  51. /// The timer lock
  52. /// </summary>
  53. private readonly object _timerLock = new object();
  54. /// <summary>
  55. /// Add the path to our temporary ignore list. Use when writing to a path within our listening scope.
  56. /// </summary>
  57. /// <param name="path">The path.</param>
  58. private void TemporarilyIgnore(string path)
  59. {
  60. _tempIgnoredPaths[path] = path;
  61. }
  62. public void ReportFileSystemChangeBeginning(string path)
  63. {
  64. if (string.IsNullOrEmpty(path))
  65. {
  66. throw new ArgumentNullException("path");
  67. }
  68. TemporarilyIgnore(path);
  69. }
  70. public async void ReportFileSystemChangeComplete(string path, bool refreshPath)
  71. {
  72. if (string.IsNullOrEmpty(path))
  73. {
  74. throw new ArgumentNullException("path");
  75. }
  76. // 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.
  77. // Seeing long delays in some situations, especially over the network, sometimes up to 45 seconds
  78. // But if we make this delay too high, we risk missing legitimate changes, such as user adding a new file, or hand-editing metadata
  79. await Task.Delay(20000).ConfigureAwait(false);
  80. string val;
  81. _tempIgnoredPaths.TryRemove(path, out val);
  82. if (refreshPath)
  83. {
  84. ReportFileSystemChanged(path);
  85. }
  86. }
  87. /// <summary>
  88. /// Gets or sets the logger.
  89. /// </summary>
  90. /// <value>The logger.</value>
  91. private ILogger Logger { get; set; }
  92. /// <summary>
  93. /// Gets or sets the task manager.
  94. /// </summary>
  95. /// <value>The task manager.</value>
  96. private ITaskManager TaskManager { get; set; }
  97. private ILibraryManager LibraryManager { get; set; }
  98. private IServerConfigurationManager ConfigurationManager { get; set; }
  99. private readonly IFileSystem _fileSystem;
  100. /// <summary>
  101. /// Initializes a new instance of the <see cref="LibraryMonitor" /> class.
  102. /// </summary>
  103. public LibraryMonitor(ILogManager logManager, ITaskManager taskManager, ILibraryManager libraryManager, IServerConfigurationManager configurationManager, IFileSystem fileSystem)
  104. {
  105. if (taskManager == null)
  106. {
  107. throw new ArgumentNullException("taskManager");
  108. }
  109. LibraryManager = libraryManager;
  110. TaskManager = taskManager;
  111. Logger = logManager.GetLogger(GetType().Name);
  112. ConfigurationManager = configurationManager;
  113. _fileSystem = fileSystem;
  114. SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
  115. }
  116. /// <summary>
  117. /// Handles the PowerModeChanged event of the SystemEvents control.
  118. /// </summary>
  119. /// <param name="sender">The source of the event.</param>
  120. /// <param name="e">The <see cref="PowerModeChangedEventArgs"/> instance containing the event data.</param>
  121. void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
  122. {
  123. Restart();
  124. }
  125. private void Restart()
  126. {
  127. Stop();
  128. Start();
  129. }
  130. private bool EnableLibraryMonitor
  131. {
  132. get
  133. {
  134. switch (ConfigurationManager.Configuration.EnableLibraryMonitor)
  135. {
  136. case AutoOnOff.Auto:
  137. return Environment.OSVersion.Platform == PlatformID.Win32NT;
  138. case AutoOnOff.Enabled:
  139. return true;
  140. default:
  141. return false;
  142. }
  143. }
  144. }
  145. public void Start()
  146. {
  147. if (EnableLibraryMonitor)
  148. {
  149. StartInternal();
  150. }
  151. }
  152. /// <summary>
  153. /// Starts this instance.
  154. /// </summary>
  155. private void StartInternal()
  156. {
  157. LibraryManager.ItemAdded += LibraryManager_ItemAdded;
  158. LibraryManager.ItemRemoved += LibraryManager_ItemRemoved;
  159. var pathsToWatch = new List<string> { LibraryManager.RootFolder.Path };
  160. var paths = LibraryManager
  161. .RootFolder
  162. .Children
  163. .OfType<Folder>()
  164. .SelectMany(f => f.PhysicalLocations)
  165. .Distinct(StringComparer.OrdinalIgnoreCase)
  166. .OrderBy(i => i)
  167. .ToList();
  168. foreach (var path in paths)
  169. {
  170. if (!ContainsParentFolder(pathsToWatch, path))
  171. {
  172. pathsToWatch.Add(path);
  173. }
  174. }
  175. foreach (var path in pathsToWatch)
  176. {
  177. StartWatchingPath(path);
  178. }
  179. }
  180. /// <summary>
  181. /// Handles the ItemRemoved event of the LibraryManager control.
  182. /// </summary>
  183. /// <param name="sender">The source of the event.</param>
  184. /// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
  185. void LibraryManager_ItemRemoved(object sender, ItemChangeEventArgs e)
  186. {
  187. if (e.Item.Parent is AggregateFolder)
  188. {
  189. StopWatchingPath(e.Item.Path);
  190. }
  191. }
  192. /// <summary>
  193. /// Handles the ItemAdded event of the LibraryManager control.
  194. /// </summary>
  195. /// <param name="sender">The source of the event.</param>
  196. /// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
  197. void LibraryManager_ItemAdded(object sender, ItemChangeEventArgs e)
  198. {
  199. if (e.Item.Parent is AggregateFolder)
  200. {
  201. StartWatchingPath(e.Item.Path);
  202. }
  203. }
  204. /// <summary>
  205. /// Examine a list of strings assumed to be file paths to see if it contains a parent of
  206. /// the provided path.
  207. /// </summary>
  208. /// <param name="lst">The LST.</param>
  209. /// <param name="path">The path.</param>
  210. /// <returns><c>true</c> if [contains parent folder] [the specified LST]; otherwise, <c>false</c>.</returns>
  211. /// <exception cref="System.ArgumentNullException">path</exception>
  212. private static bool ContainsParentFolder(IEnumerable<string> lst, string path)
  213. {
  214. if (string.IsNullOrEmpty(path))
  215. {
  216. throw new ArgumentNullException("path");
  217. }
  218. path = path.TrimEnd(Path.DirectorySeparatorChar);
  219. return lst.Any(str =>
  220. {
  221. //this should be a little quicker than examining each actual parent folder...
  222. var compare = str.TrimEnd(Path.DirectorySeparatorChar);
  223. return (path.Equals(compare, StringComparison.OrdinalIgnoreCase) || (path.StartsWith(compare, StringComparison.OrdinalIgnoreCase) && path[compare.Length] == Path.DirectorySeparatorChar));
  224. });
  225. }
  226. /// <summary>
  227. /// Starts the watching path.
  228. /// </summary>
  229. /// <param name="path">The path.</param>
  230. private void StartWatchingPath(string path)
  231. {
  232. // Creating a FileSystemWatcher over the LAN can take hundreds of milliseconds, so wrap it in a Task to do them all in parallel
  233. Task.Run(() =>
  234. {
  235. try
  236. {
  237. var newWatcher = new FileSystemWatcher(path, "*")
  238. {
  239. IncludeSubdirectories = true,
  240. InternalBufferSize = 32767
  241. };
  242. newWatcher.NotifyFilter = NotifyFilters.CreationTime |
  243. NotifyFilters.DirectoryName |
  244. NotifyFilters.FileName |
  245. NotifyFilters.LastWrite |
  246. NotifyFilters.Size |
  247. NotifyFilters.Attributes;
  248. newWatcher.Created += watcher_Changed;
  249. newWatcher.Deleted += watcher_Changed;
  250. newWatcher.Renamed += watcher_Changed;
  251. newWatcher.Changed += watcher_Changed;
  252. newWatcher.Error += watcher_Error;
  253. if (_fileSystemWatchers.TryAdd(path, newWatcher))
  254. {
  255. newWatcher.EnableRaisingEvents = true;
  256. Logger.Info("Watching directory " + path);
  257. }
  258. else
  259. {
  260. Logger.Info("Unable to add directory watcher for {0}. It already exists in the dictionary.", path);
  261. newWatcher.Dispose();
  262. }
  263. }
  264. catch (Exception ex)
  265. {
  266. Logger.ErrorException("Error watching path: {0}", ex, path);
  267. }
  268. });
  269. }
  270. /// <summary>
  271. /// Stops the watching path.
  272. /// </summary>
  273. /// <param name="path">The path.</param>
  274. private void StopWatchingPath(string path)
  275. {
  276. FileSystemWatcher watcher;
  277. if (_fileSystemWatchers.TryGetValue(path, out watcher))
  278. {
  279. DisposeWatcher(watcher);
  280. }
  281. }
  282. /// <summary>
  283. /// Disposes the watcher.
  284. /// </summary>
  285. /// <param name="watcher">The watcher.</param>
  286. private void DisposeWatcher(FileSystemWatcher watcher)
  287. {
  288. try
  289. {
  290. using (watcher)
  291. {
  292. Logger.Info("Stopping directory watching for path {0}", watcher.Path);
  293. watcher.EnableRaisingEvents = false;
  294. }
  295. }
  296. catch
  297. {
  298. }
  299. finally
  300. {
  301. RemoveWatcherFromList(watcher);
  302. }
  303. }
  304. /// <summary>
  305. /// Removes the watcher from list.
  306. /// </summary>
  307. /// <param name="watcher">The watcher.</param>
  308. private void RemoveWatcherFromList(FileSystemWatcher watcher)
  309. {
  310. FileSystemWatcher removed;
  311. _fileSystemWatchers.TryRemove(watcher.Path, out removed);
  312. }
  313. /// <summary>
  314. /// Handles the Error event of the watcher control.
  315. /// </summary>
  316. /// <param name="sender">The source of the event.</param>
  317. /// <param name="e">The <see cref="ErrorEventArgs" /> instance containing the event data.</param>
  318. void watcher_Error(object sender, ErrorEventArgs e)
  319. {
  320. var ex = e.GetException();
  321. var dw = (FileSystemWatcher)sender;
  322. Logger.ErrorException("Error in Directory watcher for: " + dw.Path, ex);
  323. DisposeWatcher(dw);
  324. if (ConfigurationManager.Configuration.EnableLibraryMonitor == AutoOnOff.Auto)
  325. {
  326. Logger.Info("Disabling realtime monitor to prevent future instability");
  327. ConfigurationManager.Configuration.EnableLibraryMonitor = AutoOnOff.Disabled;
  328. Stop();
  329. }
  330. }
  331. /// <summary>
  332. /// Handles the Changed event of the watcher control.
  333. /// </summary>
  334. /// <param name="sender">The source of the event.</param>
  335. /// <param name="e">The <see cref="FileSystemEventArgs" /> instance containing the event data.</param>
  336. void watcher_Changed(object sender, FileSystemEventArgs e)
  337. {
  338. try
  339. {
  340. Logger.Debug("Changed detected of type " + e.ChangeType + " to " + e.FullPath);
  341. ReportFileSystemChanged(e.FullPath);
  342. }
  343. catch (Exception ex)
  344. {
  345. Logger.ErrorException("Exception in ReportFileSystemChanged. Path: {0}", ex, e.FullPath);
  346. }
  347. }
  348. public void ReportFileSystemChanged(string path)
  349. {
  350. if (string.IsNullOrEmpty(path))
  351. {
  352. throw new ArgumentNullException("path");
  353. }
  354. var filename = Path.GetFileName(path);
  355. var monitorPath = !(!string.IsNullOrEmpty(filename) && _alwaysIgnoreFiles.Contains(filename, StringComparer.OrdinalIgnoreCase));
  356. // Ignore certain files
  357. var tempIgnorePaths = _tempIgnoredPaths.Keys.ToList();
  358. // If the parent of an ignored path has a change event, ignore that too
  359. if (tempIgnorePaths.Any(i =>
  360. {
  361. if (string.Equals(i, path, StringComparison.OrdinalIgnoreCase))
  362. {
  363. Logger.Debug("Ignoring change to {0}", path);
  364. return true;
  365. }
  366. if (_fileSystem.ContainsSubPath(i, path))
  367. {
  368. Logger.Debug("Ignoring change to {0}", path);
  369. return true;
  370. }
  371. // Go up a level
  372. var parent = Path.GetDirectoryName(i);
  373. if (!string.IsNullOrEmpty(parent))
  374. {
  375. if (string.Equals(parent, path, StringComparison.OrdinalIgnoreCase))
  376. {
  377. Logger.Debug("Ignoring change to {0}", path);
  378. return true;
  379. }
  380. }
  381. return false;
  382. }))
  383. {
  384. monitorPath = false;
  385. }
  386. if (monitorPath)
  387. {
  388. // Avoid implicitly captured closure
  389. var affectedPath = path;
  390. _affectedPaths.AddOrUpdate(path, path, (key, oldValue) => affectedPath);
  391. }
  392. RestartTimer();
  393. }
  394. private void RestartTimer()
  395. {
  396. lock (_timerLock)
  397. {
  398. if (_updateTimer == null)
  399. {
  400. _updateTimer = new Timer(TimerStopped, null, TimeSpan.FromSeconds(ConfigurationManager.Configuration.RealtimeLibraryMonitorDelay), TimeSpan.FromMilliseconds(-1));
  401. }
  402. else
  403. {
  404. _updateTimer.Change(TimeSpan.FromSeconds(ConfigurationManager.Configuration.RealtimeLibraryMonitorDelay), TimeSpan.FromMilliseconds(-1));
  405. }
  406. }
  407. }
  408. /// <summary>
  409. /// Timers the stopped.
  410. /// </summary>
  411. /// <param name="stateInfo">The state info.</param>
  412. private async void TimerStopped(object stateInfo)
  413. {
  414. // Extend the timer as long as any of the paths are still being written to.
  415. if (_affectedPaths.Any(p => IsFileLocked(p.Key)))
  416. {
  417. Logger.Info("Timer extended.");
  418. RestartTimer();
  419. return;
  420. }
  421. Logger.Debug("Timer stopped.");
  422. DisposeTimer();
  423. var paths = _affectedPaths.Keys.ToList();
  424. _affectedPaths.Clear();
  425. try
  426. {
  427. await ProcessPathChanges(paths).ConfigureAwait(false);
  428. }
  429. catch (Exception ex)
  430. {
  431. Logger.ErrorException("Error processing directory changes", ex);
  432. }
  433. }
  434. private bool IsFileLocked(string path)
  435. {
  436. try
  437. {
  438. var data = _fileSystem.GetFileSystemInfo(path);
  439. if (!data.Exists
  440. || data.Attributes.HasFlag(FileAttributes.Directory)
  441. // Opening a writable stream will fail with readonly files
  442. || data.Attributes.HasFlag(FileAttributes.ReadOnly))
  443. {
  444. return false;
  445. }
  446. }
  447. catch (IOException)
  448. {
  449. return false;
  450. }
  451. catch (Exception ex)
  452. {
  453. Logger.ErrorException("Error getting file system info for: {0}", ex, path);
  454. return false;
  455. }
  456. try
  457. {
  458. using (_fileSystem.GetFileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
  459. {
  460. if (_updateTimer != null)
  461. {
  462. //file is not locked
  463. return false;
  464. }
  465. }
  466. }
  467. catch (DirectoryNotFoundException)
  468. {
  469. // File may have been deleted
  470. return false;
  471. }
  472. catch (FileNotFoundException)
  473. {
  474. // File may have been deleted
  475. return false;
  476. }
  477. catch (IOException)
  478. {
  479. //the file is unavailable because it is:
  480. //still being written to
  481. //or being processed by another thread
  482. //or does not exist (has already been processed)
  483. Logger.Debug("{0} is locked.", path);
  484. return true;
  485. }
  486. catch (Exception ex)
  487. {
  488. Logger.ErrorException("Error determining if file is locked: {0}", ex, path);
  489. return false;
  490. }
  491. return false;
  492. }
  493. private void DisposeTimer()
  494. {
  495. lock (_timerLock)
  496. {
  497. if (_updateTimer != null)
  498. {
  499. _updateTimer.Dispose();
  500. _updateTimer = null;
  501. }
  502. }
  503. }
  504. /// <summary>
  505. /// Processes the path changes.
  506. /// </summary>
  507. /// <param name="paths">The paths.</param>
  508. /// <returns>Task.</returns>
  509. private async Task ProcessPathChanges(List<string> paths)
  510. {
  511. var itemsToRefresh = paths
  512. .Select(GetAffectedBaseItem)
  513. .Where(item => item != null)
  514. .Distinct()
  515. .ToList();
  516. foreach (var p in paths)
  517. {
  518. Logger.Info(p + " reports change.");
  519. }
  520. // If the root folder changed, run the library task so the user can see it
  521. if (itemsToRefresh.Any(i => i is AggregateFolder))
  522. {
  523. TaskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  524. return;
  525. }
  526. foreach (var item in itemsToRefresh)
  527. {
  528. Logger.Info(item.Name + " (" + item.Path + ") will be refreshed.");
  529. try
  530. {
  531. await item.ChangedExternally().ConfigureAwait(false);
  532. }
  533. catch (IOException ex)
  534. {
  535. // For now swallow and log.
  536. // Research item: If an IOException occurs, the item may be in a disconnected state (media unavailable)
  537. // Should we remove it from it's parent?
  538. Logger.ErrorException("Error refreshing {0}", ex, item.Name);
  539. }
  540. catch (Exception ex)
  541. {
  542. Logger.ErrorException("Error refreshing {0}", ex, item.Name);
  543. }
  544. }
  545. }
  546. /// <summary>
  547. /// Gets the affected base item.
  548. /// </summary>
  549. /// <param name="path">The path.</param>
  550. /// <returns>BaseItem.</returns>
  551. private BaseItem GetAffectedBaseItem(string path)
  552. {
  553. BaseItem item = null;
  554. while (item == null && !string.IsNullOrEmpty(path))
  555. {
  556. item = LibraryManager.RootFolder.FindByPath(path);
  557. path = Path.GetDirectoryName(path);
  558. }
  559. if (item != null)
  560. {
  561. // If the item has been deleted find the first valid parent that still exists
  562. while (!Directory.Exists(item.Path) && !File.Exists(item.Path))
  563. {
  564. item = item.Parent;
  565. if (item == null)
  566. {
  567. break;
  568. }
  569. }
  570. }
  571. return item;
  572. }
  573. /// <summary>
  574. /// Stops this instance.
  575. /// </summary>
  576. public void Stop()
  577. {
  578. LibraryManager.ItemAdded -= LibraryManager_ItemAdded;
  579. LibraryManager.ItemRemoved -= LibraryManager_ItemRemoved;
  580. foreach (var watcher in _fileSystemWatchers.Values.ToList())
  581. {
  582. watcher.Changed -= watcher_Changed;
  583. watcher.EnableRaisingEvents = false;
  584. watcher.Dispose();
  585. }
  586. DisposeTimer();
  587. _fileSystemWatchers.Clear();
  588. _affectedPaths.Clear();
  589. }
  590. /// <summary>
  591. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  592. /// </summary>
  593. public void Dispose()
  594. {
  595. Dispose(true);
  596. GC.SuppressFinalize(this);
  597. }
  598. /// <summary>
  599. /// Releases unmanaged and - optionally - managed resources.
  600. /// </summary>
  601. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  602. protected virtual void Dispose(bool dispose)
  603. {
  604. if (dispose)
  605. {
  606. Stop();
  607. }
  608. }
  609. }
  610. public class LibraryMonitorStartup : IServerEntryPoint
  611. {
  612. private readonly ILibraryMonitor _monitor;
  613. public LibraryMonitorStartup(ILibraryMonitor monitor)
  614. {
  615. _monitor = monitor;
  616. }
  617. public void Run()
  618. {
  619. _monitor.Start();
  620. }
  621. public void Dispose()
  622. {
  623. }
  624. }
  625. }