LibraryMonitor.cs 21 KB

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