LibraryMonitor.cs 21 KB

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