LibraryMonitor.cs 22 KB

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