LibraryMonitor.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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.
  76. // Seeing delays up to 40 seconds, but not going to ignore changes for that long.
  77. await Task.Delay(1500).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 | NotifyFilters.DirectoryName |
  226. NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.Size;
  227. newWatcher.Created += watcher_Changed;
  228. newWatcher.Deleted += watcher_Changed;
  229. newWatcher.Renamed += watcher_Changed;
  230. newWatcher.Changed += watcher_Changed;
  231. newWatcher.Error += watcher_Error;
  232. if (_fileSystemWatchers.TryAdd(path, newWatcher))
  233. {
  234. newWatcher.EnableRaisingEvents = true;
  235. Logger.Info("Watching directory " + path);
  236. }
  237. else
  238. {
  239. Logger.Info("Unable to add directory watcher for {0}. It already exists in the dictionary.", path);
  240. newWatcher.Dispose();
  241. }
  242. }
  243. catch (Exception ex)
  244. {
  245. Logger.ErrorException("Error watching path: {0}", ex, path);
  246. }
  247. });
  248. }
  249. /// <summary>
  250. /// Stops the watching path.
  251. /// </summary>
  252. /// <param name="path">The path.</param>
  253. private void StopWatchingPath(string path)
  254. {
  255. FileSystemWatcher watcher;
  256. if (_fileSystemWatchers.TryGetValue(path, out watcher))
  257. {
  258. DisposeWatcher(watcher);
  259. }
  260. }
  261. /// <summary>
  262. /// Disposes the watcher.
  263. /// </summary>
  264. /// <param name="watcher">The watcher.</param>
  265. private void DisposeWatcher(FileSystemWatcher watcher)
  266. {
  267. Logger.Info("Stopping directory watching for path {0}", watcher.Path);
  268. watcher.EnableRaisingEvents = false;
  269. watcher.Dispose();
  270. RemoveWatcherFromList(watcher);
  271. }
  272. /// <summary>
  273. /// Removes the watcher from list.
  274. /// </summary>
  275. /// <param name="watcher">The watcher.</param>
  276. private void RemoveWatcherFromList(FileSystemWatcher watcher)
  277. {
  278. FileSystemWatcher removed;
  279. _fileSystemWatchers.TryRemove(watcher.Path, out removed);
  280. }
  281. /// <summary>
  282. /// Handles the Error event of the watcher control.
  283. /// </summary>
  284. /// <param name="sender">The source of the event.</param>
  285. /// <param name="e">The <see cref="ErrorEventArgs" /> instance containing the event data.</param>
  286. void watcher_Error(object sender, ErrorEventArgs e)
  287. {
  288. var ex = e.GetException();
  289. var dw = (FileSystemWatcher)sender;
  290. Logger.ErrorException("Error in Directory watcher for: " + dw.Path, ex);
  291. DisposeWatcher(dw);
  292. }
  293. /// <summary>
  294. /// Handles the Changed event of the watcher control.
  295. /// </summary>
  296. /// <param name="sender">The source of the event.</param>
  297. /// <param name="e">The <see cref="FileSystemEventArgs" /> instance containing the event data.</param>
  298. void watcher_Changed(object sender, FileSystemEventArgs e)
  299. {
  300. try
  301. {
  302. Logger.Debug("Watcher sees change of type " + e.ChangeType + " to " + e.FullPath);
  303. ReportFileSystemChanged(e.FullPath);
  304. }
  305. catch (Exception ex)
  306. {
  307. Logger.ErrorException("Exception in watcher changed. Path: {0}", ex, e.FullPath);
  308. }
  309. }
  310. public void ReportFileSystemChanged(string path)
  311. {
  312. if (string.IsNullOrEmpty(path))
  313. {
  314. throw new ArgumentNullException("path");
  315. }
  316. var filename = Path.GetFileName(path);
  317. var monitorPath = !(!string.IsNullOrEmpty(filename) && _alwaysIgnoreFiles.Contains(filename, StringComparer.OrdinalIgnoreCase));
  318. // Ignore certain files
  319. var tempIgnorePaths = _tempIgnoredPaths.Keys.ToList();
  320. // If the parent of an ignored path has a change event, ignore that too
  321. if (tempIgnorePaths.Any(i =>
  322. {
  323. if (string.Equals(i, path, StringComparison.OrdinalIgnoreCase))
  324. {
  325. Logger.Debug("Ignoring change to {0}", path);
  326. return true;
  327. }
  328. if (_fileSystem.ContainsSubPath(i, path))
  329. {
  330. Logger.Debug("Ignoring change to {0}", path);
  331. return true;
  332. }
  333. // Go up a level
  334. var parent = Path.GetDirectoryName(i);
  335. if (!string.IsNullOrEmpty(parent))
  336. {
  337. if (string.Equals(parent, path, StringComparison.OrdinalIgnoreCase))
  338. {
  339. Logger.Debug("Ignoring change to {0}", path);
  340. return true;
  341. }
  342. // Go up another level
  343. parent = Path.GetDirectoryName(i);
  344. if (string.Equals(parent, path, StringComparison.OrdinalIgnoreCase))
  345. {
  346. Logger.Debug("Ignoring change to {0}", path);
  347. return true;
  348. }
  349. }
  350. return false;
  351. }))
  352. {
  353. monitorPath = false;
  354. }
  355. if (monitorPath)
  356. {
  357. // Avoid implicitly captured closure
  358. var affectedPath = path;
  359. _affectedPaths.AddOrUpdate(path, path, (key, oldValue) => affectedPath);
  360. }
  361. lock (_timerLock)
  362. {
  363. if (_updateTimer == null)
  364. {
  365. _updateTimer = new Timer(TimerStopped, null, TimeSpan.FromSeconds(ConfigurationManager.Configuration.RealtimeMonitorDelay), TimeSpan.FromMilliseconds(-1));
  366. }
  367. else
  368. {
  369. _updateTimer.Change(TimeSpan.FromSeconds(ConfigurationManager.Configuration.RealtimeMonitorDelay), TimeSpan.FromMilliseconds(-1));
  370. }
  371. }
  372. }
  373. /// <summary>
  374. /// Timers the stopped.
  375. /// </summary>
  376. /// <param name="stateInfo">The state info.</param>
  377. private async void TimerStopped(object stateInfo)
  378. {
  379. Logger.Debug("Timer stopped.");
  380. DisposeTimer();
  381. var paths = _affectedPaths.Keys.ToList();
  382. _affectedPaths.Clear();
  383. try
  384. {
  385. await ProcessPathChanges(paths).ConfigureAwait(false);
  386. }
  387. catch (Exception ex)
  388. {
  389. Logger.ErrorException("Error processing directory changes", ex);
  390. }
  391. }
  392. private void DisposeTimer()
  393. {
  394. lock (_timerLock)
  395. {
  396. if (_updateTimer != null)
  397. {
  398. _updateTimer.Dispose();
  399. _updateTimer = null;
  400. }
  401. }
  402. }
  403. /// <summary>
  404. /// Processes the path changes.
  405. /// </summary>
  406. /// <param name="paths">The paths.</param>
  407. /// <returns>Task.</returns>
  408. private async Task ProcessPathChanges(List<string> paths)
  409. {
  410. var itemsToRefresh = paths.Select(Path.GetDirectoryName)
  411. .Select(GetAffectedBaseItem)
  412. .Where(item => item != null)
  413. .Distinct()
  414. .ToList();
  415. foreach (var p in paths) Logger.Info(p + " reports change.");
  416. // If the root folder changed, run the library task so the user can see it
  417. if (itemsToRefresh.Any(i => i is AggregateFolder))
  418. {
  419. TaskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  420. return;
  421. }
  422. foreach (var item in itemsToRefresh)
  423. {
  424. Logger.Info(item.Name + " (" + item.Path + ") will be refreshed.");
  425. try
  426. {
  427. await item.ChangedExternally().ConfigureAwait(false);
  428. }
  429. catch (IOException ex)
  430. {
  431. // For now swallow and log.
  432. // Research item: If an IOException occurs, the item may be in a disconnected state (media unavailable)
  433. // Should we remove it from it's parent?
  434. Logger.ErrorException("Error refreshing {0}", ex, item.Name);
  435. }
  436. catch (Exception ex)
  437. {
  438. Logger.ErrorException("Error refreshing {0}", ex, item.Name);
  439. }
  440. }
  441. }
  442. /// <summary>
  443. /// Gets the affected base item.
  444. /// </summary>
  445. /// <param name="path">The path.</param>
  446. /// <returns>BaseItem.</returns>
  447. private BaseItem GetAffectedBaseItem(string path)
  448. {
  449. BaseItem item = null;
  450. while (item == null && !string.IsNullOrEmpty(path))
  451. {
  452. item = LibraryManager.RootFolder.FindByPath(path);
  453. path = Path.GetDirectoryName(path);
  454. }
  455. if (item != null)
  456. {
  457. // If the item has been deleted find the first valid parent that still exists
  458. while (!Directory.Exists(item.Path) && !File.Exists(item.Path))
  459. {
  460. item = item.Parent;
  461. if (item == null)
  462. {
  463. break;
  464. }
  465. }
  466. }
  467. return item;
  468. }
  469. /// <summary>
  470. /// Stops this instance.
  471. /// </summary>
  472. public void Stop()
  473. {
  474. LibraryManager.ItemAdded -= LibraryManager_ItemAdded;
  475. LibraryManager.ItemRemoved -= LibraryManager_ItemRemoved;
  476. foreach (var watcher in _fileSystemWatchers.Values.ToList())
  477. {
  478. watcher.Changed -= watcher_Changed;
  479. watcher.EnableRaisingEvents = false;
  480. watcher.Dispose();
  481. }
  482. DisposeTimer();
  483. _fileSystemWatchers.Clear();
  484. _affectedPaths.Clear();
  485. }
  486. /// <summary>
  487. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  488. /// </summary>
  489. public void Dispose()
  490. {
  491. Dispose(true);
  492. GC.SuppressFinalize(this);
  493. }
  494. /// <summary>
  495. /// Releases unmanaged and - optionally - managed resources.
  496. /// </summary>
  497. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  498. protected virtual void Dispose(bool dispose)
  499. {
  500. if (dispose)
  501. {
  502. Stop();
  503. }
  504. }
  505. }
  506. }