LibraryMonitor.cs 23 KB

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