LibraryMonitor.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. using MediaBrowser.Common.ScheduledTasks;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Controller.Plugins;
  6. using MediaBrowser.Model.Configuration;
  7. using MediaBrowser.Model.Logging;
  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.Tasks;
  15. using CommonIO;
  16. using MediaBrowser.Controller;
  17. using MediaBrowser.Model.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 affected paths
  28. /// </summary>
  29. private readonly List<FileRefresher> _activeRefreshers = new List<FileRefresher>();
  30. /// <summary>
  31. /// A dynamic list of paths that should be ignored. Added to during our own file sytem modifications.
  32. /// </summary>
  33. private readonly ConcurrentDictionary<string, string> _tempIgnoredPaths = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  34. /// <summary>
  35. /// Any file name ending in any of these will be ignored by the watchers
  36. /// </summary>
  37. private readonly IReadOnlyList<string> _alwaysIgnoreFiles = new List<string>
  38. {
  39. "small.jpg",
  40. "albumart.jpg",
  41. // WMC temp recording directories that will constantly be written to
  42. "TempRec",
  43. "TempSBE"
  44. };
  45. private readonly IReadOnlyList<string> _alwaysIgnoreSubstrings = new List<string>
  46. {
  47. // Synology
  48. "eaDir",
  49. "#recycle",
  50. ".wd_tv",
  51. ".actors"
  52. };
  53. private readonly IReadOnlyList<string> _alwaysIgnoreExtensions = new List<string>
  54. {
  55. // thumbs.db
  56. ".db",
  57. // bts sync files
  58. ".bts",
  59. ".sync"
  60. };
  61. /// <summary>
  62. /// Add the path to our temporary ignore list. Use when writing to a path within our listening scope.
  63. /// </summary>
  64. /// <param name="path">The path.</param>
  65. private void TemporarilyIgnore(string path)
  66. {
  67. _tempIgnoredPaths[path] = path;
  68. }
  69. public void ReportFileSystemChangeBeginning(string path)
  70. {
  71. if (string.IsNullOrEmpty(path))
  72. {
  73. throw new ArgumentNullException("path");
  74. }
  75. TemporarilyIgnore(path);
  76. }
  77. public bool IsPathLocked(string path)
  78. {
  79. var lockedPaths = _tempIgnoredPaths.Keys.ToList();
  80. return lockedPaths.Any(i => string.Equals(i, path, StringComparison.OrdinalIgnoreCase) || _fileSystem.ContainsSubPath(i, path));
  81. }
  82. public async void ReportFileSystemChangeComplete(string path, bool refreshPath)
  83. {
  84. if (string.IsNullOrEmpty(path))
  85. {
  86. throw new ArgumentNullException("path");
  87. }
  88. // 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.
  89. // Seeing long delays in some situations, especially over the network, sometimes up to 45 seconds
  90. // But if we make this delay too high, we risk missing legitimate changes, such as user adding a new file, or hand-editing metadata
  91. await Task.Delay(45000).ConfigureAwait(false);
  92. string val;
  93. _tempIgnoredPaths.TryRemove(path, out val);
  94. if (refreshPath)
  95. {
  96. try
  97. {
  98. ReportFileSystemChanged(path);
  99. }
  100. catch (Exception ex)
  101. {
  102. Logger.ErrorException("Error in ReportFileSystemChanged for {0}", ex, path);
  103. }
  104. }
  105. }
  106. /// <summary>
  107. /// Gets or sets the logger.
  108. /// </summary>
  109. /// <value>The logger.</value>
  110. private ILogger Logger { get; set; }
  111. /// <summary>
  112. /// Gets or sets the task manager.
  113. /// </summary>
  114. /// <value>The task manager.</value>
  115. private ITaskManager TaskManager { get; set; }
  116. private ILibraryManager LibraryManager { get; set; }
  117. private IServerConfigurationManager ConfigurationManager { get; set; }
  118. private readonly IFileSystem _fileSystem;
  119. private readonly IServerApplicationHost _appHost;
  120. /// <summary>
  121. /// Initializes a new instance of the <see cref="LibraryMonitor" /> class.
  122. /// </summary>
  123. public LibraryMonitor(ILogManager logManager, ITaskManager taskManager, ILibraryManager libraryManager, IServerConfigurationManager configurationManager, IFileSystem fileSystem, IServerApplicationHost appHost)
  124. {
  125. if (taskManager == null)
  126. {
  127. throw new ArgumentNullException("taskManager");
  128. }
  129. LibraryManager = libraryManager;
  130. TaskManager = taskManager;
  131. Logger = logManager.GetLogger(GetType().Name);
  132. ConfigurationManager = configurationManager;
  133. _fileSystem = fileSystem;
  134. _appHost = appHost;
  135. SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
  136. }
  137. /// <summary>
  138. /// Handles the PowerModeChanged event of the SystemEvents control.
  139. /// </summary>
  140. /// <param name="sender">The source of the event.</param>
  141. /// <param name="e">The <see cref="PowerModeChangedEventArgs"/> instance containing the event data.</param>
  142. void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
  143. {
  144. Restart();
  145. }
  146. private void Restart()
  147. {
  148. Stop();
  149. Start();
  150. }
  151. private bool IsLibraryMonitorEnabaled(BaseItem item)
  152. {
  153. var options = LibraryManager.GetLibraryOptions(item);
  154. if (options != null)
  155. {
  156. return options.EnableRealtimeMonitor;
  157. }
  158. return false;
  159. }
  160. public void Start()
  161. {
  162. LibraryManager.ItemAdded += LibraryManager_ItemAdded;
  163. LibraryManager.ItemRemoved += LibraryManager_ItemRemoved;
  164. var pathsToWatch = new List<string> { };
  165. var paths = LibraryManager
  166. .RootFolder
  167. .Children
  168. .Where(IsLibraryMonitorEnabaled)
  169. .OfType<Folder>()
  170. .SelectMany(f => f.PhysicalLocations)
  171. .Distinct(StringComparer.OrdinalIgnoreCase)
  172. .OrderBy(i => i)
  173. .ToList();
  174. foreach (var path in paths)
  175. {
  176. if (!ContainsParentFolder(pathsToWatch, path))
  177. {
  178. pathsToWatch.Add(path);
  179. }
  180. }
  181. foreach (var path in pathsToWatch)
  182. {
  183. StartWatchingPath(path);
  184. }
  185. }
  186. private void StartWatching(BaseItem item)
  187. {
  188. if (IsLibraryMonitorEnabaled(item))
  189. {
  190. StartWatchingPath(item.Path);
  191. }
  192. }
  193. /// <summary>
  194. /// Handles the ItemRemoved event of the LibraryManager control.
  195. /// </summary>
  196. /// <param name="sender">The source of the event.</param>
  197. /// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
  198. void LibraryManager_ItemRemoved(object sender, ItemChangeEventArgs e)
  199. {
  200. if (e.Item.GetParent() is AggregateFolder)
  201. {
  202. StopWatchingPath(e.Item.Path);
  203. }
  204. }
  205. /// <summary>
  206. /// Handles the ItemAdded event of the LibraryManager control.
  207. /// </summary>
  208. /// <param name="sender">The source of the event.</param>
  209. /// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
  210. void LibraryManager_ItemAdded(object sender, ItemChangeEventArgs e)
  211. {
  212. if (e.Item.GetParent() is AggregateFolder)
  213. {
  214. StartWatching(e.Item);
  215. }
  216. }
  217. /// <summary>
  218. /// Examine a list of strings assumed to be file paths to see if it contains a parent of
  219. /// the provided path.
  220. /// </summary>
  221. /// <param name="lst">The LST.</param>
  222. /// <param name="path">The path.</param>
  223. /// <returns><c>true</c> if [contains parent folder] [the specified LST]; otherwise, <c>false</c>.</returns>
  224. /// <exception cref="System.ArgumentNullException">path</exception>
  225. private static bool ContainsParentFolder(IEnumerable<string> lst, string path)
  226. {
  227. if (string.IsNullOrWhiteSpace(path))
  228. {
  229. throw new ArgumentNullException("path");
  230. }
  231. path = path.TrimEnd(Path.DirectorySeparatorChar);
  232. return lst.Any(str =>
  233. {
  234. //this should be a little quicker than examining each actual parent folder...
  235. var compare = str.TrimEnd(Path.DirectorySeparatorChar);
  236. return path.Equals(compare, StringComparison.OrdinalIgnoreCase) || (path.StartsWith(compare, StringComparison.OrdinalIgnoreCase) && path[compare.Length] == Path.DirectorySeparatorChar);
  237. });
  238. }
  239. /// <summary>
  240. /// Starts the watching path.
  241. /// </summary>
  242. /// <param name="path">The path.</param>
  243. private void StartWatchingPath(string path)
  244. {
  245. // Creating a FileSystemWatcher over the LAN can take hundreds of milliseconds, so wrap it in a Task to do them all in parallel
  246. Task.Run(() =>
  247. {
  248. try
  249. {
  250. var newWatcher = new FileSystemWatcher(path, "*")
  251. {
  252. IncludeSubdirectories = true
  253. };
  254. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  255. {
  256. newWatcher.InternalBufferSize = 32767;
  257. }
  258. newWatcher.NotifyFilter = NotifyFilters.CreationTime |
  259. NotifyFilters.DirectoryName |
  260. NotifyFilters.FileName |
  261. NotifyFilters.LastWrite |
  262. NotifyFilters.Size |
  263. NotifyFilters.Attributes;
  264. newWatcher.Created += watcher_Changed;
  265. newWatcher.Deleted += watcher_Changed;
  266. newWatcher.Renamed += watcher_Changed;
  267. newWatcher.Changed += watcher_Changed;
  268. newWatcher.Error += watcher_Error;
  269. if (_fileSystemWatchers.TryAdd(path, newWatcher))
  270. {
  271. newWatcher.EnableRaisingEvents = true;
  272. Logger.Info("Watching directory " + path);
  273. }
  274. else
  275. {
  276. Logger.Info("Unable to add directory watcher for {0}. It already exists in the dictionary.", path);
  277. newWatcher.Dispose();
  278. }
  279. }
  280. catch (Exception ex)
  281. {
  282. Logger.ErrorException("Error watching path: {0}", ex, path);
  283. }
  284. });
  285. }
  286. /// <summary>
  287. /// Stops the watching path.
  288. /// </summary>
  289. /// <param name="path">The path.</param>
  290. private void StopWatchingPath(string path)
  291. {
  292. FileSystemWatcher watcher;
  293. if (_fileSystemWatchers.TryGetValue(path, out watcher))
  294. {
  295. DisposeWatcher(watcher);
  296. }
  297. }
  298. /// <summary>
  299. /// Disposes the watcher.
  300. /// </summary>
  301. /// <param name="watcher">The watcher.</param>
  302. private void DisposeWatcher(FileSystemWatcher watcher)
  303. {
  304. try
  305. {
  306. using (watcher)
  307. {
  308. Logger.Info("Stopping directory watching for path {0}", watcher.Path);
  309. watcher.EnableRaisingEvents = false;
  310. }
  311. }
  312. catch
  313. {
  314. }
  315. finally
  316. {
  317. RemoveWatcherFromList(watcher);
  318. }
  319. }
  320. /// <summary>
  321. /// Removes the watcher from list.
  322. /// </summary>
  323. /// <param name="watcher">The watcher.</param>
  324. private void RemoveWatcherFromList(FileSystemWatcher watcher)
  325. {
  326. FileSystemWatcher removed;
  327. _fileSystemWatchers.TryRemove(watcher.Path, out removed);
  328. }
  329. /// <summary>
  330. /// Handles the Error event of the watcher control.
  331. /// </summary>
  332. /// <param name="sender">The source of the event.</param>
  333. /// <param name="e">The <see cref="ErrorEventArgs" /> instance containing the event data.</param>
  334. void watcher_Error(object sender, ErrorEventArgs e)
  335. {
  336. var ex = e.GetException();
  337. var dw = (FileSystemWatcher)sender;
  338. Logger.ErrorException("Error in Directory watcher for: " + dw.Path, ex);
  339. DisposeWatcher(dw);
  340. }
  341. /// <summary>
  342. /// Handles the Changed event of the watcher control.
  343. /// </summary>
  344. /// <param name="sender">The source of the event.</param>
  345. /// <param name="e">The <see cref="FileSystemEventArgs" /> instance containing the event data.</param>
  346. void watcher_Changed(object sender, FileSystemEventArgs e)
  347. {
  348. try
  349. {
  350. Logger.Debug("Changed detected of type " + e.ChangeType + " to " + e.FullPath);
  351. var path = e.FullPath;
  352. // For deletes, use the parent path
  353. if (e.ChangeType == WatcherChangeTypes.Deleted)
  354. {
  355. var parentPath = Path.GetDirectoryName(path);
  356. if (!string.IsNullOrWhiteSpace(parentPath))
  357. {
  358. path = parentPath;
  359. }
  360. }
  361. ReportFileSystemChanged(path);
  362. }
  363. catch (Exception ex)
  364. {
  365. Logger.ErrorException("Exception in ReportFileSystemChanged. Path: {0}", ex, e.FullPath);
  366. }
  367. }
  368. public void ReportFileSystemChanged(string path)
  369. {
  370. if (string.IsNullOrEmpty(path))
  371. {
  372. throw new ArgumentNullException("path");
  373. }
  374. var filename = Path.GetFileName(path);
  375. var monitorPath = !string.IsNullOrEmpty(filename) &&
  376. !_alwaysIgnoreFiles.Contains(filename, StringComparer.OrdinalIgnoreCase) &&
  377. !_alwaysIgnoreExtensions.Contains(Path.GetExtension(path) ?? string.Empty, StringComparer.OrdinalIgnoreCase) &&
  378. _alwaysIgnoreSubstrings.All(i => path.IndexOf(i, StringComparison.OrdinalIgnoreCase) == -1);
  379. // Ignore certain files
  380. var tempIgnorePaths = _tempIgnoredPaths.Keys.ToList();
  381. // If the parent of an ignored path has a change event, ignore that too
  382. if (tempIgnorePaths.Any(i =>
  383. {
  384. if (string.Equals(i, path, StringComparison.OrdinalIgnoreCase))
  385. {
  386. Logger.Debug("Ignoring change to {0}", path);
  387. return true;
  388. }
  389. if (_fileSystem.ContainsSubPath(i, path))
  390. {
  391. Logger.Debug("Ignoring change to {0}", path);
  392. return true;
  393. }
  394. // Go up a level
  395. var parent = Path.GetDirectoryName(i);
  396. if (!string.IsNullOrEmpty(parent))
  397. {
  398. if (string.Equals(parent, path, StringComparison.OrdinalIgnoreCase))
  399. {
  400. Logger.Debug("Ignoring change to {0}", path);
  401. return true;
  402. }
  403. }
  404. return false;
  405. }))
  406. {
  407. monitorPath = false;
  408. }
  409. if (monitorPath)
  410. {
  411. // Avoid implicitly captured closure
  412. CreateRefresher(path);
  413. }
  414. }
  415. private void CreateRefresher(string path)
  416. {
  417. var parentPath = Path.GetDirectoryName(path);
  418. lock (_activeRefreshers)
  419. {
  420. var refreshers = _activeRefreshers.ToList();
  421. foreach (var refresher in refreshers)
  422. {
  423. // Path is already being refreshed
  424. if (string.Equals(path, refresher.Path, StringComparison.Ordinal))
  425. {
  426. refresher.RestartTimer();
  427. return;
  428. }
  429. // Parent folder is already being refreshed
  430. if (_fileSystem.ContainsSubPath(refresher.Path, path))
  431. {
  432. refresher.AddPath(path);
  433. return;
  434. }
  435. // New path is a parent
  436. if (_fileSystem.ContainsSubPath(path, refresher.Path))
  437. {
  438. refresher.ResetPath(path, null);
  439. return;
  440. }
  441. // They are siblings. Rebase the refresher to the parent folder.
  442. if (string.Equals(parentPath, Path.GetDirectoryName(refresher.Path), StringComparison.Ordinal))
  443. {
  444. refresher.ResetPath(parentPath, path);
  445. return;
  446. }
  447. }
  448. var newRefresher = new FileRefresher(path, _fileSystem, ConfigurationManager, LibraryManager, TaskManager, Logger);
  449. newRefresher.Completed += NewRefresher_Completed;
  450. _activeRefreshers.Add(newRefresher);
  451. }
  452. }
  453. private void NewRefresher_Completed(object sender, EventArgs e)
  454. {
  455. var refresher = (FileRefresher)sender;
  456. DisposeRefresher(refresher);
  457. }
  458. /// <summary>
  459. /// Stops this instance.
  460. /// </summary>
  461. public void Stop()
  462. {
  463. LibraryManager.ItemAdded -= LibraryManager_ItemAdded;
  464. LibraryManager.ItemRemoved -= LibraryManager_ItemRemoved;
  465. foreach (var watcher in _fileSystemWatchers.Values.ToList())
  466. {
  467. watcher.Created -= watcher_Changed;
  468. watcher.Deleted -= watcher_Changed;
  469. watcher.Renamed -= watcher_Changed;
  470. watcher.Changed -= watcher_Changed;
  471. try
  472. {
  473. watcher.EnableRaisingEvents = false;
  474. }
  475. catch (InvalidOperationException)
  476. {
  477. // Seeing this under mono on linux sometimes
  478. // Collection was modified; enumeration operation may not execute.
  479. }
  480. watcher.Dispose();
  481. }
  482. _fileSystemWatchers.Clear();
  483. DisposeRefreshers();
  484. }
  485. private void DisposeRefresher(FileRefresher refresher)
  486. {
  487. lock (_activeRefreshers)
  488. {
  489. refresher.Dispose();
  490. _activeRefreshers.Remove(refresher);
  491. }
  492. }
  493. private void DisposeRefreshers()
  494. {
  495. lock (_activeRefreshers)
  496. {
  497. foreach (var refresher in _activeRefreshers.ToList())
  498. {
  499. refresher.Dispose();
  500. }
  501. _activeRefreshers.Clear();
  502. }
  503. }
  504. /// <summary>
  505. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  506. /// </summary>
  507. public void Dispose()
  508. {
  509. Dispose(true);
  510. GC.SuppressFinalize(this);
  511. }
  512. /// <summary>
  513. /// Releases unmanaged and - optionally - managed resources.
  514. /// </summary>
  515. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  516. protected virtual void Dispose(bool dispose)
  517. {
  518. if (dispose)
  519. {
  520. Stop();
  521. }
  522. }
  523. }
  524. public class LibraryMonitorStartup : IServerEntryPoint
  525. {
  526. private readonly ILibraryMonitor _monitor;
  527. public LibraryMonitorStartup(ILibraryMonitor monitor)
  528. {
  529. _monitor = monitor;
  530. }
  531. public void Run()
  532. {
  533. _monitor.Start();
  534. }
  535. public void Dispose()
  536. {
  537. }
  538. }
  539. }