LibraryMonitor.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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. "@eaDir",
  44. "eaDir",
  45. "#recycle"
  46. };
  47. private readonly IReadOnlyList<string> _alwaysIgnoreSubstrings = new List<string>
  48. {
  49. // Synology
  50. "@eaDir",
  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. var options = LibraryManager.GetLibraryOptions(item);
  155. if (options != null)
  156. {
  157. return options.EnableRealtimeMonitor;
  158. }
  159. return false;
  160. }
  161. public void Start()
  162. {
  163. LibraryManager.ItemAdded += LibraryManager_ItemAdded;
  164. LibraryManager.ItemRemoved += LibraryManager_ItemRemoved;
  165. var pathsToWatch = new List<string> { };
  166. var paths = LibraryManager
  167. .RootFolder
  168. .Children
  169. .Where(IsLibraryMonitorEnabaled)
  170. .OfType<Folder>()
  171. .SelectMany(f => f.PhysicalLocations)
  172. .Distinct(StringComparer.OrdinalIgnoreCase)
  173. .OrderBy(i => i)
  174. .ToList();
  175. foreach (var path in paths)
  176. {
  177. if (!ContainsParentFolder(pathsToWatch, path))
  178. {
  179. pathsToWatch.Add(path);
  180. }
  181. }
  182. foreach (var path in pathsToWatch)
  183. {
  184. StartWatchingPath(path);
  185. }
  186. }
  187. private void StartWatching(BaseItem item)
  188. {
  189. if (IsLibraryMonitorEnabaled(item))
  190. {
  191. StartWatchingPath(item.Path);
  192. }
  193. }
  194. /// <summary>
  195. /// Handles the ItemRemoved event of the LibraryManager control.
  196. /// </summary>
  197. /// <param name="sender">The source of the event.</param>
  198. /// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
  199. void LibraryManager_ItemRemoved(object sender, ItemChangeEventArgs e)
  200. {
  201. if (e.Item.GetParent() is AggregateFolder)
  202. {
  203. StopWatchingPath(e.Item.Path);
  204. }
  205. }
  206. /// <summary>
  207. /// Handles the ItemAdded event of the LibraryManager control.
  208. /// </summary>
  209. /// <param name="sender">The source of the event.</param>
  210. /// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
  211. void LibraryManager_ItemAdded(object sender, ItemChangeEventArgs e)
  212. {
  213. if (e.Item.GetParent() is AggregateFolder)
  214. {
  215. StartWatching(e.Item);
  216. }
  217. }
  218. /// <summary>
  219. /// Examine a list of strings assumed to be file paths to see if it contains a parent of
  220. /// the provided path.
  221. /// </summary>
  222. /// <param name="lst">The LST.</param>
  223. /// <param name="path">The path.</param>
  224. /// <returns><c>true</c> if [contains parent folder] [the specified LST]; otherwise, <c>false</c>.</returns>
  225. /// <exception cref="System.ArgumentNullException">path</exception>
  226. private static bool ContainsParentFolder(IEnumerable<string> lst, string path)
  227. {
  228. if (string.IsNullOrWhiteSpace(path))
  229. {
  230. throw new ArgumentNullException("path");
  231. }
  232. path = path.TrimEnd(Path.DirectorySeparatorChar);
  233. return lst.Any(str =>
  234. {
  235. //this should be a little quicker than examining each actual parent folder...
  236. var compare = str.TrimEnd(Path.DirectorySeparatorChar);
  237. return path.Equals(compare, StringComparison.OrdinalIgnoreCase) || (path.StartsWith(compare, StringComparison.OrdinalIgnoreCase) && path[compare.Length] == Path.DirectorySeparatorChar);
  238. });
  239. }
  240. /// <summary>
  241. /// Starts the watching path.
  242. /// </summary>
  243. /// <param name="path">The path.</param>
  244. private void StartWatchingPath(string path)
  245. {
  246. // Creating a FileSystemWatcher over the LAN can take hundreds of milliseconds, so wrap it in a Task to do them all in parallel
  247. Task.Run(() =>
  248. {
  249. try
  250. {
  251. var newWatcher = new FileSystemWatcher(path, "*")
  252. {
  253. IncludeSubdirectories = true
  254. };
  255. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  256. {
  257. newWatcher.InternalBufferSize = 32767;
  258. }
  259. newWatcher.NotifyFilter = NotifyFilters.CreationTime |
  260. NotifyFilters.DirectoryName |
  261. NotifyFilters.FileName |
  262. NotifyFilters.LastWrite |
  263. NotifyFilters.Size |
  264. NotifyFilters.Attributes;
  265. newWatcher.Created += watcher_Changed;
  266. newWatcher.Deleted += watcher_Changed;
  267. newWatcher.Renamed += watcher_Changed;
  268. newWatcher.Changed += watcher_Changed;
  269. newWatcher.Error += watcher_Error;
  270. if (_fileSystemWatchers.TryAdd(path, newWatcher))
  271. {
  272. newWatcher.EnableRaisingEvents = true;
  273. Logger.Info("Watching directory " + path);
  274. }
  275. else
  276. {
  277. Logger.Info("Unable to add directory watcher for {0}. It already exists in the dictionary.", path);
  278. newWatcher.Dispose();
  279. }
  280. }
  281. catch (Exception ex)
  282. {
  283. Logger.ErrorException("Error watching path: {0}", ex, path);
  284. }
  285. });
  286. }
  287. /// <summary>
  288. /// Stops the watching path.
  289. /// </summary>
  290. /// <param name="path">The path.</param>
  291. private void StopWatchingPath(string path)
  292. {
  293. FileSystemWatcher watcher;
  294. if (_fileSystemWatchers.TryGetValue(path, out watcher))
  295. {
  296. DisposeWatcher(watcher);
  297. }
  298. }
  299. /// <summary>
  300. /// Disposes the watcher.
  301. /// </summary>
  302. /// <param name="watcher">The watcher.</param>
  303. private void DisposeWatcher(FileSystemWatcher watcher)
  304. {
  305. try
  306. {
  307. using (watcher)
  308. {
  309. Logger.Info("Stopping directory watching for path {0}", watcher.Path);
  310. watcher.EnableRaisingEvents = false;
  311. }
  312. }
  313. catch
  314. {
  315. }
  316. finally
  317. {
  318. RemoveWatcherFromList(watcher);
  319. }
  320. }
  321. /// <summary>
  322. /// Removes the watcher from list.
  323. /// </summary>
  324. /// <param name="watcher">The watcher.</param>
  325. private void RemoveWatcherFromList(FileSystemWatcher watcher)
  326. {
  327. FileSystemWatcher removed;
  328. _fileSystemWatchers.TryRemove(watcher.Path, out removed);
  329. }
  330. /// <summary>
  331. /// Handles the Error event of the watcher control.
  332. /// </summary>
  333. /// <param name="sender">The source of the event.</param>
  334. /// <param name="e">The <see cref="ErrorEventArgs" /> instance containing the event data.</param>
  335. void watcher_Error(object sender, ErrorEventArgs e)
  336. {
  337. var ex = e.GetException();
  338. var dw = (FileSystemWatcher)sender;
  339. Logger.ErrorException("Error in Directory watcher for: " + dw.Path, ex);
  340. DisposeWatcher(dw);
  341. }
  342. /// <summary>
  343. /// Handles the Changed event of the watcher control.
  344. /// </summary>
  345. /// <param name="sender">The source of the event.</param>
  346. /// <param name="e">The <see cref="FileSystemEventArgs" /> instance containing the event data.</param>
  347. void watcher_Changed(object sender, FileSystemEventArgs e)
  348. {
  349. try
  350. {
  351. Logger.Debug("Changed detected of type " + e.ChangeType + " to " + e.FullPath);
  352. var path = e.FullPath;
  353. // For deletes, use the parent path
  354. if (e.ChangeType == WatcherChangeTypes.Deleted)
  355. {
  356. var parentPath = Path.GetDirectoryName(path);
  357. if (!string.IsNullOrWhiteSpace(parentPath))
  358. {
  359. path = parentPath;
  360. }
  361. }
  362. ReportFileSystemChanged(path);
  363. }
  364. catch (Exception ex)
  365. {
  366. Logger.ErrorException("Exception in ReportFileSystemChanged. Path: {0}", ex, e.FullPath);
  367. }
  368. }
  369. public void ReportFileSystemChanged(string path)
  370. {
  371. if (string.IsNullOrEmpty(path))
  372. {
  373. throw new ArgumentNullException("path");
  374. }
  375. var filename = Path.GetFileName(path);
  376. var monitorPath = !string.IsNullOrEmpty(filename) &&
  377. !_alwaysIgnoreFiles.Contains(filename, StringComparer.OrdinalIgnoreCase) &&
  378. !_alwaysIgnoreExtensions.Contains(Path.GetExtension(path) ?? string.Empty, StringComparer.OrdinalIgnoreCase) &&
  379. _alwaysIgnoreSubstrings.All(i => path.IndexOf(i, StringComparison.OrdinalIgnoreCase) == -1);
  380. // Ignore certain files
  381. var tempIgnorePaths = _tempIgnoredPaths.Keys.ToList();
  382. // If the parent of an ignored path has a change event, ignore that too
  383. if (tempIgnorePaths.Any(i =>
  384. {
  385. if (string.Equals(i, path, StringComparison.OrdinalIgnoreCase))
  386. {
  387. Logger.Debug("Ignoring change to {0}", path);
  388. return true;
  389. }
  390. if (_fileSystem.ContainsSubPath(i, path))
  391. {
  392. Logger.Debug("Ignoring change to {0}", path);
  393. return true;
  394. }
  395. // Go up a level
  396. var parent = Path.GetDirectoryName(i);
  397. if (!string.IsNullOrEmpty(parent))
  398. {
  399. if (string.Equals(parent, path, StringComparison.OrdinalIgnoreCase))
  400. {
  401. Logger.Debug("Ignoring change to {0}", path);
  402. return true;
  403. }
  404. }
  405. return false;
  406. }))
  407. {
  408. monitorPath = false;
  409. }
  410. if (monitorPath)
  411. {
  412. // Avoid implicitly captured closure
  413. CreateRefresher(path);
  414. }
  415. }
  416. private void CreateRefresher(string path)
  417. {
  418. var parentPath = Path.GetDirectoryName(path);
  419. lock (_activeRefreshers)
  420. {
  421. var refreshers = _activeRefreshers.ToList();
  422. foreach (var refresher in refreshers)
  423. {
  424. // Path is already being refreshed
  425. if (string.Equals(path, refresher.Path, StringComparison.Ordinal))
  426. {
  427. refresher.RestartTimer();
  428. return;
  429. }
  430. // Parent folder is already being refreshed
  431. if (_fileSystem.ContainsSubPath(refresher.Path, path))
  432. {
  433. refresher.AddPath(path);
  434. return;
  435. }
  436. // New path is a parent
  437. if (_fileSystem.ContainsSubPath(path, refresher.Path))
  438. {
  439. refresher.ResetPath(path, null);
  440. return;
  441. }
  442. // They are siblings. Rebase the refresher to the parent folder.
  443. if (string.Equals(parentPath, Path.GetDirectoryName(refresher.Path), StringComparison.Ordinal))
  444. {
  445. refresher.ResetPath(parentPath, path);
  446. return;
  447. }
  448. }
  449. var newRefresher = new FileRefresher(path, _fileSystem, ConfigurationManager, LibraryManager, TaskManager, Logger);
  450. newRefresher.Completed += NewRefresher_Completed;
  451. _activeRefreshers.Add(newRefresher);
  452. }
  453. }
  454. private void NewRefresher_Completed(object sender, EventArgs e)
  455. {
  456. var refresher = (FileRefresher)sender;
  457. DisposeRefresher(refresher);
  458. }
  459. /// <summary>
  460. /// Stops this instance.
  461. /// </summary>
  462. public void Stop()
  463. {
  464. LibraryManager.ItemAdded -= LibraryManager_ItemAdded;
  465. LibraryManager.ItemRemoved -= LibraryManager_ItemRemoved;
  466. foreach (var watcher in _fileSystemWatchers.Values.ToList())
  467. {
  468. watcher.Created -= watcher_Changed;
  469. watcher.Deleted -= watcher_Changed;
  470. watcher.Renamed -= watcher_Changed;
  471. watcher.Changed -= watcher_Changed;
  472. try
  473. {
  474. watcher.EnableRaisingEvents = false;
  475. }
  476. catch (InvalidOperationException)
  477. {
  478. // Seeing this under mono on linux sometimes
  479. // Collection was modified; enumeration operation may not execute.
  480. }
  481. watcher.Dispose();
  482. }
  483. _fileSystemWatchers.Clear();
  484. DisposeRefreshers();
  485. }
  486. private void DisposeRefresher(FileRefresher refresher)
  487. {
  488. lock (_activeRefreshers)
  489. {
  490. refresher.Dispose();
  491. _activeRefreshers.Remove(refresher);
  492. }
  493. }
  494. private void DisposeRefreshers()
  495. {
  496. lock (_activeRefreshers)
  497. {
  498. foreach (var refresher in _activeRefreshers.ToList())
  499. {
  500. refresher.Dispose();
  501. }
  502. _activeRefreshers.Clear();
  503. }
  504. }
  505. /// <summary>
  506. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  507. /// </summary>
  508. public void Dispose()
  509. {
  510. Dispose(true);
  511. GC.SuppressFinalize(this);
  512. }
  513. /// <summary>
  514. /// Releases unmanaged and - optionally - managed resources.
  515. /// </summary>
  516. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  517. protected virtual void Dispose(bool dispose)
  518. {
  519. if (dispose)
  520. {
  521. Stop();
  522. }
  523. }
  524. }
  525. public class LibraryMonitorStartup : IServerEntryPoint
  526. {
  527. private readonly ILibraryMonitor _monitor;
  528. public LibraryMonitorStartup(ILibraryMonitor monitor)
  529. {
  530. _monitor = monitor;
  531. }
  532. public void Run()
  533. {
  534. _monitor.Start();
  535. }
  536. public void Dispose()
  537. {
  538. }
  539. }
  540. }