LibraryMonitor.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  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. }
  324. /// <summary>
  325. /// Handles the Changed event of the watcher control.
  326. /// </summary>
  327. /// <param name="sender">The source of the event.</param>
  328. /// <param name="e">The <see cref="FileSystemEventArgs" /> instance containing the event data.</param>
  329. void watcher_Changed(object sender, FileSystemEventArgs e)
  330. {
  331. try
  332. {
  333. Logger.Debug("Changed detected of type " + e.ChangeType + " to " + e.FullPath);
  334. ReportFileSystemChanged(e.FullPath);
  335. }
  336. catch (Exception ex)
  337. {
  338. Logger.ErrorException("Exception in ReportFileSystemChanged. Path: {0}", ex, e.FullPath);
  339. }
  340. }
  341. public void ReportFileSystemChanged(string path)
  342. {
  343. if (string.IsNullOrEmpty(path))
  344. {
  345. throw new ArgumentNullException("path");
  346. }
  347. var filename = Path.GetFileName(path);
  348. var monitorPath = !(!string.IsNullOrEmpty(filename) && _alwaysIgnoreFiles.Contains(filename, StringComparer.OrdinalIgnoreCase));
  349. // Ignore certain files
  350. var tempIgnorePaths = _tempIgnoredPaths.Keys.ToList();
  351. // If the parent of an ignored path has a change event, ignore that too
  352. if (tempIgnorePaths.Any(i =>
  353. {
  354. if (string.Equals(i, path, StringComparison.OrdinalIgnoreCase))
  355. {
  356. Logger.Debug("Ignoring change to {0}", path);
  357. return true;
  358. }
  359. if (_fileSystem.ContainsSubPath(i, path))
  360. {
  361. Logger.Debug("Ignoring change to {0}", path);
  362. return true;
  363. }
  364. // Go up a level
  365. var parent = Path.GetDirectoryName(i);
  366. if (!string.IsNullOrEmpty(parent))
  367. {
  368. if (string.Equals(parent, path, StringComparison.OrdinalIgnoreCase))
  369. {
  370. Logger.Debug("Ignoring change to {0}", path);
  371. return true;
  372. }
  373. }
  374. return false;
  375. }))
  376. {
  377. monitorPath = false;
  378. }
  379. if (monitorPath)
  380. {
  381. // Avoid implicitly captured closure
  382. var affectedPath = path;
  383. _affectedPaths.AddOrUpdate(path, path, (key, oldValue) => affectedPath);
  384. }
  385. RestartTimer();
  386. }
  387. private void RestartTimer()
  388. {
  389. lock (_timerLock)
  390. {
  391. if (_updateTimer == null)
  392. {
  393. _updateTimer = new Timer(TimerStopped, null, TimeSpan.FromSeconds(ConfigurationManager.Configuration.RealtimeLibraryMonitorDelay), TimeSpan.FromMilliseconds(-1));
  394. }
  395. else
  396. {
  397. _updateTimer.Change(TimeSpan.FromSeconds(ConfigurationManager.Configuration.RealtimeLibraryMonitorDelay), TimeSpan.FromMilliseconds(-1));
  398. }
  399. }
  400. }
  401. /// <summary>
  402. /// Timers the stopped.
  403. /// </summary>
  404. /// <param name="stateInfo">The state info.</param>
  405. private async void TimerStopped(object stateInfo)
  406. {
  407. // Extend the timer as long as any of the paths are still being written to.
  408. if (_affectedPaths.Any(p => IsFileLocked(p.Key)))
  409. {
  410. Logger.Info("Timer extended.");
  411. RestartTimer();
  412. return;
  413. }
  414. Logger.Debug("Timer stopped.");
  415. DisposeTimer();
  416. var paths = _affectedPaths.Keys.ToList();
  417. _affectedPaths.Clear();
  418. try
  419. {
  420. await ProcessPathChanges(paths).ConfigureAwait(false);
  421. }
  422. catch (Exception ex)
  423. {
  424. Logger.ErrorException("Error processing directory changes", ex);
  425. }
  426. }
  427. private bool IsFileLocked(string path)
  428. {
  429. try
  430. {
  431. var data = _fileSystem.GetFileSystemInfo(path);
  432. if (!data.Exists
  433. || data.Attributes.HasFlag(FileAttributes.Directory)
  434. // Opening a writable stream will fail with readonly files
  435. || data.Attributes.HasFlag(FileAttributes.ReadOnly))
  436. {
  437. return false;
  438. }
  439. }
  440. catch (IOException)
  441. {
  442. return false;
  443. }
  444. catch (Exception ex)
  445. {
  446. Logger.ErrorException("Error getting file system info for: {0}", ex, path);
  447. return false;
  448. }
  449. try
  450. {
  451. using (_fileSystem.GetFileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
  452. {
  453. if (_updateTimer != null)
  454. {
  455. //file is not locked
  456. return false;
  457. }
  458. }
  459. }
  460. catch (DirectoryNotFoundException)
  461. {
  462. // File may have been deleted
  463. return false;
  464. }
  465. catch (FileNotFoundException)
  466. {
  467. // File may have been deleted
  468. return false;
  469. }
  470. catch (IOException)
  471. {
  472. //the file is unavailable because it is:
  473. //still being written to
  474. //or being processed by another thread
  475. //or does not exist (has already been processed)
  476. Logger.Debug("{0} is locked.", path);
  477. return true;
  478. }
  479. catch (Exception ex)
  480. {
  481. Logger.ErrorException("Error determining if file is locked: {0}", ex, path);
  482. return false;
  483. }
  484. return false;
  485. }
  486. private void DisposeTimer()
  487. {
  488. lock (_timerLock)
  489. {
  490. if (_updateTimer != null)
  491. {
  492. _updateTimer.Dispose();
  493. _updateTimer = null;
  494. }
  495. }
  496. }
  497. /// <summary>
  498. /// Processes the path changes.
  499. /// </summary>
  500. /// <param name="paths">The paths.</param>
  501. /// <returns>Task.</returns>
  502. private async Task ProcessPathChanges(List<string> paths)
  503. {
  504. var itemsToRefresh = paths
  505. .Select(GetAffectedBaseItem)
  506. .Where(item => item != null)
  507. .Distinct()
  508. .ToList();
  509. foreach (var p in paths)
  510. {
  511. Logger.Info(p + " reports change.");
  512. }
  513. // If the root folder changed, run the library task so the user can see it
  514. if (itemsToRefresh.Any(i => i is AggregateFolder))
  515. {
  516. TaskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  517. return;
  518. }
  519. foreach (var item in itemsToRefresh)
  520. {
  521. Logger.Info(item.Name + " (" + item.Path + ") will be refreshed.");
  522. try
  523. {
  524. await item.ChangedExternally().ConfigureAwait(false);
  525. }
  526. catch (IOException ex)
  527. {
  528. // For now swallow and log.
  529. // Research item: If an IOException occurs, the item may be in a disconnected state (media unavailable)
  530. // Should we remove it from it's parent?
  531. Logger.ErrorException("Error refreshing {0}", ex, item.Name);
  532. }
  533. catch (Exception ex)
  534. {
  535. Logger.ErrorException("Error refreshing {0}", ex, item.Name);
  536. }
  537. }
  538. }
  539. /// <summary>
  540. /// Gets the affected base item.
  541. /// </summary>
  542. /// <param name="path">The path.</param>
  543. /// <returns>BaseItem.</returns>
  544. private BaseItem GetAffectedBaseItem(string path)
  545. {
  546. BaseItem item = null;
  547. while (item == null && !string.IsNullOrEmpty(path))
  548. {
  549. item = LibraryManager.RootFolder.FindByPath(path);
  550. path = Path.GetDirectoryName(path);
  551. }
  552. if (item != null)
  553. {
  554. // If the item has been deleted find the first valid parent that still exists
  555. while (!Directory.Exists(item.Path) && !File.Exists(item.Path))
  556. {
  557. item = item.Parent;
  558. if (item == null)
  559. {
  560. break;
  561. }
  562. }
  563. }
  564. return item;
  565. }
  566. /// <summary>
  567. /// Stops this instance.
  568. /// </summary>
  569. public void Stop()
  570. {
  571. LibraryManager.ItemAdded -= LibraryManager_ItemAdded;
  572. LibraryManager.ItemRemoved -= LibraryManager_ItemRemoved;
  573. foreach (var watcher in _fileSystemWatchers.Values.ToList())
  574. {
  575. watcher.Changed -= watcher_Changed;
  576. watcher.EnableRaisingEvents = false;
  577. watcher.Dispose();
  578. }
  579. DisposeTimer();
  580. _fileSystemWatchers.Clear();
  581. _affectedPaths.Clear();
  582. }
  583. /// <summary>
  584. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  585. /// </summary>
  586. public void Dispose()
  587. {
  588. Dispose(true);
  589. GC.SuppressFinalize(this);
  590. }
  591. /// <summary>
  592. /// Releases unmanaged and - optionally - managed resources.
  593. /// </summary>
  594. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  595. protected virtual void Dispose(bool dispose)
  596. {
  597. if (dispose)
  598. {
  599. Stop();
  600. }
  601. }
  602. }
  603. }