LibraryMonitor.cs 22 KB

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