DirectoryWatchers.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. using MediaBrowser.Common.ScheduledTasks;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.IO;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Server.Implementations.ScheduledTasks;
  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;
  14. using System.Threading.Tasks;
  15. namespace MediaBrowser.Server.Implementations.IO
  16. {
  17. /// <summary>
  18. /// Class DirectoryWatchers
  19. /// </summary>
  20. public class DirectoryWatchers : IDirectoryWatchers
  21. {
  22. /// <summary>
  23. /// The file system watchers
  24. /// </summary>
  25. private ConcurrentBag<FileSystemWatcher> _fileSystemWatchers = new ConcurrentBag<FileSystemWatcher>();
  26. /// <summary>
  27. /// The update timer
  28. /// </summary>
  29. private Timer _updateTimer;
  30. /// <summary>
  31. /// The affected paths
  32. /// </summary>
  33. private readonly ConcurrentDictionary<string, string> _affectedPaths = new ConcurrentDictionary<string, string>();
  34. /// <summary>
  35. /// A dynamic list of paths that should be ignored. Added to during our own file sytem modifications.
  36. /// </summary>
  37. private readonly ConcurrentDictionary<string,string> _tempIgnoredPaths = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  38. /// <summary>
  39. /// Any file name ending in any of these will be ignored by the watchers
  40. /// </summary>
  41. private readonly List<string> _alwaysIgnoreFiles = new List<string> {"thumbs.db","small.jpg","albumart.jpg"};
  42. /// <summary>
  43. /// The timer lock
  44. /// </summary>
  45. private readonly object _timerLock = new object();
  46. /// <summary>
  47. /// Add the path to our temporary ignore list. Use when writing to a path within our listening scope.
  48. /// </summary>
  49. /// <param name="path">The path.</param>
  50. public void TemporarilyIgnore(string path)
  51. {
  52. _tempIgnoredPaths[path] = path;
  53. }
  54. /// <summary>
  55. /// Removes the temp ignore.
  56. /// </summary>
  57. /// <param name="path">The path.</param>
  58. public void RemoveTempIgnore(string path)
  59. {
  60. string val;
  61. _tempIgnoredPaths.TryRemove(path, out val);
  62. }
  63. /// <summary>
  64. /// Gets or sets the logger.
  65. /// </summary>
  66. /// <value>The logger.</value>
  67. private ILogger Logger { get; set; }
  68. /// <summary>
  69. /// Gets or sets the task manager.
  70. /// </summary>
  71. /// <value>The task manager.</value>
  72. private ITaskManager TaskManager { get; set; }
  73. private ILibraryManager LibraryManager { get; set; }
  74. private IServerConfigurationManager ConfigurationManager { get; set; }
  75. /// <summary>
  76. /// Initializes a new instance of the <see cref="DirectoryWatchers" /> class.
  77. /// </summary>
  78. public DirectoryWatchers(ILogManager logManager, ITaskManager taskManager, ILibraryManager libraryManager, IServerConfigurationManager configurationManager)
  79. {
  80. if (taskManager == null)
  81. {
  82. throw new ArgumentNullException("taskManager");
  83. }
  84. LibraryManager = libraryManager;
  85. TaskManager = taskManager;
  86. Logger = logManager.GetLogger("DirectoryWatchers");
  87. ConfigurationManager = configurationManager;
  88. }
  89. /// <summary>
  90. /// Starts this instance.
  91. /// </summary>
  92. public void Start()
  93. {
  94. LibraryManager.LibraryChanged += Instance_LibraryChanged;
  95. var pathsToWatch = new List<string> { LibraryManager.RootFolder.Path };
  96. var paths = LibraryManager.RootFolder.Children.OfType<Folder>()
  97. .SelectMany(f =>
  98. {
  99. try
  100. {
  101. // Accessing ResolveArgs could involve file system access
  102. return f.ResolveArgs.PhysicalLocations;
  103. }
  104. catch (IOException)
  105. {
  106. return new string[] {};
  107. }
  108. })
  109. .Where(Path.IsPathRooted);
  110. foreach (var path in paths)
  111. {
  112. if (!ContainsParentFolder(pathsToWatch, path))
  113. {
  114. pathsToWatch.Add(path);
  115. }
  116. }
  117. foreach (var path in pathsToWatch)
  118. {
  119. StartWatchingPath(path);
  120. }
  121. }
  122. /// <summary>
  123. /// Examine a list of strings assumed to be file paths to see if it contains a parent of
  124. /// the provided path.
  125. /// </summary>
  126. /// <param name="lst">The LST.</param>
  127. /// <param name="path">The path.</param>
  128. /// <returns><c>true</c> if [contains parent folder] [the specified LST]; otherwise, <c>false</c>.</returns>
  129. /// <exception cref="System.ArgumentNullException">path</exception>
  130. private static bool ContainsParentFolder(IEnumerable<string> lst, string path)
  131. {
  132. if (string.IsNullOrEmpty(path))
  133. {
  134. throw new ArgumentNullException("path");
  135. }
  136. path = path.TrimEnd(Path.DirectorySeparatorChar);
  137. return lst.Any(str =>
  138. {
  139. //this should be a little quicker than examining each actual parent folder...
  140. var compare = str.TrimEnd(Path.DirectorySeparatorChar);
  141. return (path.Equals(compare, StringComparison.OrdinalIgnoreCase) || (path.StartsWith(compare, StringComparison.OrdinalIgnoreCase) && path[compare.Length] == Path.DirectorySeparatorChar));
  142. });
  143. }
  144. /// <summary>
  145. /// Starts the watching path.
  146. /// </summary>
  147. /// <param name="path">The path.</param>
  148. private void StartWatchingPath(string path)
  149. {
  150. // Creating a FileSystemWatcher over the LAN can take hundreds of milliseconds, so wrap it in a Task to do them all in parallel
  151. Task.Run(() =>
  152. {
  153. var newWatcher = new FileSystemWatcher(path, "*") { IncludeSubdirectories = true, InternalBufferSize = 32767 };
  154. newWatcher.Created += watcher_Changed;
  155. newWatcher.Deleted += watcher_Changed;
  156. newWatcher.Renamed += watcher_Changed;
  157. newWatcher.Changed += watcher_Changed;
  158. newWatcher.Error += watcher_Error;
  159. try
  160. {
  161. newWatcher.EnableRaisingEvents = true;
  162. _fileSystemWatchers.Add(newWatcher);
  163. Logger.Info("Watching directory " + path);
  164. }
  165. catch (IOException ex)
  166. {
  167. Logger.ErrorException("Error watching path: {0}", ex, path);
  168. }
  169. catch (PlatformNotSupportedException ex)
  170. {
  171. Logger.ErrorException("Error watching path: {0}", ex, path);
  172. }
  173. });
  174. }
  175. /// <summary>
  176. /// Stops the watching path.
  177. /// </summary>
  178. /// <param name="path">The path.</param>
  179. private void StopWatchingPath(string path)
  180. {
  181. var watcher = _fileSystemWatchers.FirstOrDefault(f => f.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
  182. if (watcher != null)
  183. {
  184. DisposeWatcher(watcher);
  185. }
  186. }
  187. /// <summary>
  188. /// Disposes the watcher.
  189. /// </summary>
  190. /// <param name="watcher">The watcher.</param>
  191. private void DisposeWatcher(FileSystemWatcher watcher)
  192. {
  193. Logger.Info("Stopping directory watching for path {0}", watcher.Path);
  194. watcher.EnableRaisingEvents = false;
  195. watcher.Dispose();
  196. var watchers = _fileSystemWatchers.ToList();
  197. watchers.Remove(watcher);
  198. _fileSystemWatchers = new ConcurrentBag<FileSystemWatcher>(watchers);
  199. }
  200. /// <summary>
  201. /// Handles the LibraryChanged event of the Kernel
  202. /// </summary>
  203. /// <param name="sender">The source of the event.</param>
  204. /// <param name="e">The <see cref="MediaBrowser.Controller.Library.ChildrenChangedEventArgs" /> instance containing the event data.</param>
  205. void Instance_LibraryChanged(object sender, ChildrenChangedEventArgs e)
  206. {
  207. if (e.Folder is AggregateFolder && e.HasAddOrRemoveChange)
  208. {
  209. if (e.ItemsRemoved != null)
  210. {
  211. foreach (var item in e.ItemsRemoved.OfType<Folder>())
  212. {
  213. StopWatchingPath(item.Path);
  214. }
  215. }
  216. if (e.ItemsAdded != null)
  217. {
  218. foreach (var item in e.ItemsAdded.OfType<Folder>())
  219. {
  220. StartWatchingPath(item.Path);
  221. }
  222. }
  223. }
  224. }
  225. /// <summary>
  226. /// Handles the Error event of the watcher control.
  227. /// </summary>
  228. /// <param name="sender">The source of the event.</param>
  229. /// <param name="e">The <see cref="ErrorEventArgs" /> instance containing the event data.</param>
  230. async void watcher_Error(object sender, ErrorEventArgs e)
  231. {
  232. var ex = e.GetException();
  233. var dw = (FileSystemWatcher) sender;
  234. Logger.ErrorException("Error in Directory watcher for: "+dw.Path, ex);
  235. if (ex.Message.Contains("network name is no longer available"))
  236. {
  237. //Network either dropped or, we are coming out of sleep and it hasn't reconnected yet - wait and retry
  238. Logger.Warn("Network connection lost - will retry...");
  239. var retries = 0;
  240. var success = false;
  241. while (!success && retries < 10)
  242. {
  243. await Task.Delay(500).ConfigureAwait(false);
  244. try
  245. {
  246. dw.EnableRaisingEvents = false;
  247. dw.EnableRaisingEvents = true;
  248. success = true;
  249. }
  250. catch (IOException)
  251. {
  252. Logger.Warn("Network still unavailable...");
  253. retries++;
  254. }
  255. }
  256. if (!success)
  257. {
  258. Logger.Warn("Unable to access network. Giving up.");
  259. DisposeWatcher(dw);
  260. }
  261. }
  262. else
  263. {
  264. if (!ex.Message.Contains("BIOS command limit"))
  265. {
  266. Logger.Info("Attempting to re-start watcher.");
  267. dw.EnableRaisingEvents = false;
  268. dw.EnableRaisingEvents = true;
  269. }
  270. }
  271. }
  272. /// <summary>
  273. /// Handles the Changed event of the watcher control.
  274. /// </summary>
  275. /// <param name="sender">The source of the event.</param>
  276. /// <param name="e">The <see cref="FileSystemEventArgs" /> instance containing the event data.</param>
  277. void watcher_Changed(object sender, FileSystemEventArgs e)
  278. {
  279. // Ignore when someone manually creates a new folder
  280. if (e.ChangeType == WatcherChangeTypes.Created && e.Name == "New folder")
  281. {
  282. return;
  283. }
  284. // Ignore certain files
  285. if (_alwaysIgnoreFiles.Any(f => e.Name.EndsWith(f, StringComparison.OrdinalIgnoreCase)))
  286. {
  287. return;
  288. }
  289. if (_tempIgnoredPaths.ContainsKey(e.FullPath))
  290. {
  291. Logger.Info("Watcher requested to ignore change to " + e.FullPath);
  292. return;
  293. }
  294. Logger.Info("Watcher sees change of type " + e.ChangeType.ToString() + " to " + e.FullPath);
  295. //Since we're watching created, deleted and renamed we always want the parent of the item to be the affected path
  296. var affectedPath = e.FullPath;
  297. _affectedPaths.AddOrUpdate(affectedPath, affectedPath, (key, oldValue) => affectedPath);
  298. lock (_timerLock)
  299. {
  300. if (_updateTimer == null)
  301. {
  302. _updateTimer = new Timer(TimerStopped, null, TimeSpan.FromSeconds(ConfigurationManager.Configuration.FileWatcherDelay), TimeSpan.FromMilliseconds(-1));
  303. }
  304. else
  305. {
  306. _updateTimer.Change(TimeSpan.FromSeconds(ConfigurationManager.Configuration.FileWatcherDelay), TimeSpan.FromMilliseconds(-1));
  307. }
  308. }
  309. }
  310. /// <summary>
  311. /// Timers the stopped.
  312. /// </summary>
  313. /// <param name="stateInfo">The state info.</param>
  314. private async void TimerStopped(object stateInfo)
  315. {
  316. lock (_timerLock)
  317. {
  318. // Extend the timer as long as any of the paths are still being written to.
  319. if (_affectedPaths.Any(p => IsFileLocked(p.Key)))
  320. {
  321. Logger.Info("Timer extended.");
  322. _updateTimer.Change(TimeSpan.FromSeconds(ConfigurationManager.Configuration.FileWatcherDelay), TimeSpan.FromMilliseconds(-1));
  323. return;
  324. }
  325. Logger.Info("Timer stopped.");
  326. _updateTimer.Dispose();
  327. _updateTimer = null;
  328. }
  329. var paths = _affectedPaths.Keys.ToList();
  330. _affectedPaths.Clear();
  331. await ProcessPathChanges(paths).ConfigureAwait(false);
  332. }
  333. /// <summary>
  334. /// Try and determine if a file is locked
  335. /// This is not perfect, and is subject to race conditions, so I'd rather not make this a re-usable library method.
  336. /// </summary>
  337. /// <param name="path">The path.</param>
  338. /// <returns><c>true</c> if [is file locked] [the specified path]; otherwise, <c>false</c>.</returns>
  339. private bool IsFileLocked(string path)
  340. {
  341. try
  342. {
  343. var data = FileSystem.GetFileData(path);
  344. if (!data.HasValue || data.Value.IsDirectory)
  345. {
  346. return false;
  347. }
  348. }
  349. catch (IOException)
  350. {
  351. return false;
  352. }
  353. FileStream stream = null;
  354. try
  355. {
  356. stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
  357. }
  358. catch
  359. {
  360. //the file is unavailable because it is:
  361. //still being written to
  362. //or being processed by another thread
  363. //or does not exist (has already been processed)
  364. return true;
  365. }
  366. finally
  367. {
  368. if (stream != null)
  369. stream.Close();
  370. }
  371. //file is not locked
  372. return false;
  373. }
  374. /// <summary>
  375. /// Processes the path changes.
  376. /// </summary>
  377. /// <param name="paths">The paths.</param>
  378. /// <returns>Task.</returns>
  379. private async Task ProcessPathChanges(List<string> paths)
  380. {
  381. var itemsToRefresh = paths.Select(Path.GetDirectoryName)
  382. .Select(GetAffectedBaseItem)
  383. .Where(item => item != null)
  384. .Distinct()
  385. .ToList();
  386. foreach (var p in paths) Logger.Info(p + " reports change.");
  387. // If the root folder changed, run the library task so the user can see it
  388. if (itemsToRefresh.Any(i => i is AggregateFolder))
  389. {
  390. TaskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  391. return;
  392. }
  393. await Task.WhenAll(itemsToRefresh.Select(i => Task.Run(async () =>
  394. {
  395. Logger.Info(i.Name + " (" + i.Path + ") will be refreshed.");
  396. try
  397. {
  398. await i.ChangedExternally().ConfigureAwait(false);
  399. }
  400. catch (IOException ex)
  401. {
  402. // For now swallow and log.
  403. // Research item: If an IOException occurs, the item may be in a disconnected state (media unavailable)
  404. // Should we remove it from it's parent?
  405. Logger.ErrorException("Error refreshing {0}", ex, i.Name);
  406. }
  407. catch (Exception ex)
  408. {
  409. Logger.ErrorException("Error refreshing {0}", ex, i.Name);
  410. }
  411. }))).ConfigureAwait(false);
  412. }
  413. /// <summary>
  414. /// Gets the affected base item.
  415. /// </summary>
  416. /// <param name="path">The path.</param>
  417. /// <returns>BaseItem.</returns>
  418. private BaseItem GetAffectedBaseItem(string path)
  419. {
  420. BaseItem item = null;
  421. while (item == null && !string.IsNullOrEmpty(path))
  422. {
  423. item = LibraryManager.RootFolder.FindByPath(path);
  424. path = Path.GetDirectoryName(path);
  425. }
  426. if (item != null)
  427. {
  428. // If the item has been deleted find the first valid parent that still exists
  429. while (!Directory.Exists(item.Path) && !File.Exists(item.Path))
  430. {
  431. item = item.Parent;
  432. if (item == null)
  433. {
  434. break;
  435. }
  436. }
  437. }
  438. return item;
  439. }
  440. /// <summary>
  441. /// Stops this instance.
  442. /// </summary>
  443. public void Stop()
  444. {
  445. LibraryManager.LibraryChanged -= Instance_LibraryChanged;
  446. FileSystemWatcher watcher;
  447. while (_fileSystemWatchers.TryTake(out watcher))
  448. {
  449. watcher.Changed -= watcher_Changed;
  450. watcher.EnableRaisingEvents = false;
  451. watcher.Dispose();
  452. }
  453. lock (_timerLock)
  454. {
  455. if (_updateTimer != null)
  456. {
  457. _updateTimer.Dispose();
  458. _updateTimer = null;
  459. }
  460. }
  461. _affectedPaths.Clear();
  462. }
  463. /// <summary>
  464. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  465. /// </summary>
  466. public void Dispose()
  467. {
  468. Dispose(true);
  469. GC.SuppressFinalize(this);
  470. }
  471. /// <summary>
  472. /// Releases unmanaged and - optionally - managed resources.
  473. /// </summary>
  474. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  475. protected virtual void Dispose(bool dispose)
  476. {
  477. if (dispose)
  478. {
  479. Stop();
  480. }
  481. }
  482. }
  483. }