LibraryMonitor.cs 21 KB

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