DirectoryWatchers.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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 readonly ConcurrentDictionary<string, FileSystemWatcher> _fileSystemWatchers = new ConcurrentDictionary<string,FileSystemWatcher>(StringComparer.OrdinalIgnoreCase);
  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 IReadOnlyList<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.ItemAdded += LibraryManager_ItemAdded;
  95. LibraryManager.ItemRemoved += LibraryManager_ItemRemoved;
  96. var pathsToWatch = new List<string> { LibraryManager.RootFolder.Path };
  97. var paths = LibraryManager.RootFolder.Children.OfType<Folder>()
  98. .SelectMany(f =>
  99. {
  100. try
  101. {
  102. // Accessing ResolveArgs could involve file system access
  103. return f.ResolveArgs.PhysicalLocations;
  104. }
  105. catch (IOException)
  106. {
  107. return new string[] { };
  108. }
  109. })
  110. .Where(Path.IsPathRooted);
  111. foreach (var path in paths)
  112. {
  113. if (!ContainsParentFolder(pathsToWatch, path))
  114. {
  115. pathsToWatch.Add(path);
  116. }
  117. }
  118. foreach (var path in pathsToWatch)
  119. {
  120. StartWatchingPath(path);
  121. }
  122. }
  123. /// <summary>
  124. /// Handles the ItemRemoved event of the LibraryManager control.
  125. /// </summary>
  126. /// <param name="sender">The source of the event.</param>
  127. /// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
  128. void LibraryManager_ItemRemoved(object sender, ItemChangeEventArgs e)
  129. {
  130. if (e.Item.Parent is AggregateFolder)
  131. {
  132. StopWatchingPath(e.Item.Path);
  133. }
  134. }
  135. /// <summary>
  136. /// Handles the ItemAdded event of the LibraryManager control.
  137. /// </summary>
  138. /// <param name="sender">The source of the event.</param>
  139. /// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param>
  140. void LibraryManager_ItemAdded(object sender, ItemChangeEventArgs e)
  141. {
  142. if (e.Item.Parent is AggregateFolder)
  143. {
  144. StartWatchingPath(e.Item.Path);
  145. }
  146. }
  147. /// <summary>
  148. /// Examine a list of strings assumed to be file paths to see if it contains a parent of
  149. /// the provided path.
  150. /// </summary>
  151. /// <param name="lst">The LST.</param>
  152. /// <param name="path">The path.</param>
  153. /// <returns><c>true</c> if [contains parent folder] [the specified LST]; otherwise, <c>false</c>.</returns>
  154. /// <exception cref="System.ArgumentNullException">path</exception>
  155. private static bool ContainsParentFolder(IEnumerable<string> lst, string path)
  156. {
  157. if (string.IsNullOrEmpty(path))
  158. {
  159. throw new ArgumentNullException("path");
  160. }
  161. path = path.TrimEnd(Path.DirectorySeparatorChar);
  162. return lst.Any(str =>
  163. {
  164. //this should be a little quicker than examining each actual parent folder...
  165. var compare = str.TrimEnd(Path.DirectorySeparatorChar);
  166. return (path.Equals(compare, StringComparison.OrdinalIgnoreCase) || (path.StartsWith(compare, StringComparison.OrdinalIgnoreCase) && path[compare.Length] == Path.DirectorySeparatorChar));
  167. });
  168. }
  169. /// <summary>
  170. /// Starts the watching path.
  171. /// </summary>
  172. /// <param name="path">The path.</param>
  173. private void StartWatchingPath(string path)
  174. {
  175. // Creating a FileSystemWatcher over the LAN can take hundreds of milliseconds, so wrap it in a Task to do them all in parallel
  176. Task.Run(() =>
  177. {
  178. var newWatcher = new FileSystemWatcher(path, "*") { IncludeSubdirectories = true, InternalBufferSize = 32767 };
  179. newWatcher.Created += watcher_Changed;
  180. newWatcher.Deleted += watcher_Changed;
  181. newWatcher.Renamed += watcher_Changed;
  182. newWatcher.Changed += watcher_Changed;
  183. newWatcher.Error += watcher_Error;
  184. try
  185. {
  186. if (_fileSystemWatchers.TryAdd(path, newWatcher))
  187. {
  188. newWatcher.EnableRaisingEvents = true;
  189. Logger.Info("Watching directory " + path);
  190. }
  191. else
  192. {
  193. Logger.Info("Unable to add directory watcher for {0}. It already exists in the dictionary." + path);
  194. newWatcher.Dispose();
  195. }
  196. }
  197. catch (IOException ex)
  198. {
  199. Logger.ErrorException("Error watching path: {0}", ex, path);
  200. }
  201. catch (PlatformNotSupportedException ex)
  202. {
  203. Logger.ErrorException("Error watching path: {0}", ex, path);
  204. }
  205. });
  206. }
  207. /// <summary>
  208. /// Stops the watching path.
  209. /// </summary>
  210. /// <param name="path">The path.</param>
  211. private void StopWatchingPath(string path)
  212. {
  213. FileSystemWatcher watcher;
  214. if (_fileSystemWatchers.TryGetValue(path, out watcher))
  215. {
  216. DisposeWatcher(watcher);
  217. }
  218. }
  219. /// <summary>
  220. /// Disposes the watcher.
  221. /// </summary>
  222. /// <param name="watcher">The watcher.</param>
  223. private void DisposeWatcher(FileSystemWatcher watcher)
  224. {
  225. Logger.Info("Stopping directory watching for path {0}", watcher.Path);
  226. watcher.EnableRaisingEvents = false;
  227. watcher.Dispose();
  228. RemoveWatcherFromList(watcher);
  229. }
  230. /// <summary>
  231. /// Removes the watcher from list.
  232. /// </summary>
  233. /// <param name="watcher">The watcher.</param>
  234. private void RemoveWatcherFromList(FileSystemWatcher watcher)
  235. {
  236. FileSystemWatcher removed;
  237. _fileSystemWatchers.TryRemove(watcher.Path, out removed);
  238. }
  239. /// <summary>
  240. /// Handles the Error event of the watcher control.
  241. /// </summary>
  242. /// <param name="sender">The source of the event.</param>
  243. /// <param name="e">The <see cref="ErrorEventArgs" /> instance containing the event data.</param>
  244. async void watcher_Error(object sender, ErrorEventArgs e)
  245. {
  246. var ex = e.GetException();
  247. var dw = (FileSystemWatcher)sender;
  248. Logger.ErrorException("Error in Directory watcher for: " + dw.Path, ex);
  249. //Network either dropped or, we are coming out of sleep and it hasn't reconnected yet - wait and retry
  250. var retries = 0;
  251. var success = false;
  252. while (!success && retries < 10)
  253. {
  254. await Task.Delay(500).ConfigureAwait(false);
  255. try
  256. {
  257. dw.EnableRaisingEvents = false;
  258. dw.EnableRaisingEvents = true;
  259. success = true;
  260. }
  261. catch (ObjectDisposedException)
  262. {
  263. RemoveWatcherFromList(dw);
  264. return;
  265. }
  266. catch (IOException)
  267. {
  268. Logger.Warn("Network still unavailable...");
  269. retries++;
  270. }
  271. }
  272. if (!success)
  273. {
  274. Logger.Warn("Unable to access network. Giving up.");
  275. DisposeWatcher(dw);
  276. }
  277. }
  278. /// <summary>
  279. /// Handles the Changed event of the watcher control.
  280. /// </summary>
  281. /// <param name="sender">The source of the event.</param>
  282. /// <param name="e">The <see cref="FileSystemEventArgs" /> instance containing the event data.</param>
  283. void watcher_Changed(object sender, FileSystemEventArgs e)
  284. {
  285. var name = e.Name;
  286. // Ignore certain files
  287. if (_alwaysIgnoreFiles.Contains(name, StringComparer.OrdinalIgnoreCase))
  288. {
  289. return;
  290. }
  291. // Ignore when someone manually creates a new folder
  292. if (e.ChangeType == WatcherChangeTypes.Created && name == "New folder")
  293. {
  294. return;
  295. }
  296. var tempIgnorePaths = _tempIgnoredPaths.Keys.ToList();
  297. if (e.ChangeType == WatcherChangeTypes.Changed)
  298. {
  299. // If the parent of an ignored path has a change event, ignore that too
  300. if (tempIgnorePaths.Any(i => string.Equals(Path.GetDirectoryName(i), e.FullPath, StringComparison.OrdinalIgnoreCase) || string.Equals(i, e.FullPath, StringComparison.OrdinalIgnoreCase)))
  301. {
  302. return;
  303. }
  304. }
  305. if (tempIgnorePaths.Contains(e.FullPath, StringComparer.OrdinalIgnoreCase))
  306. {
  307. Logger.Debug("Watcher requested to ignore change to " + e.FullPath);
  308. return;
  309. }
  310. Logger.Info("Watcher sees change of type " + e.ChangeType.ToString() + " to " + e.FullPath);
  311. //Since we're watching created, deleted and renamed we always want the parent of the item to be the affected path
  312. var affectedPath = e.FullPath;
  313. _affectedPaths.AddOrUpdate(affectedPath, affectedPath, (key, oldValue) => affectedPath);
  314. lock (_timerLock)
  315. {
  316. if (_updateTimer == null)
  317. {
  318. _updateTimer = new Timer(TimerStopped, null, TimeSpan.FromSeconds(ConfigurationManager.Configuration.FileWatcherDelay), TimeSpan.FromMilliseconds(-1));
  319. }
  320. else
  321. {
  322. _updateTimer.Change(TimeSpan.FromSeconds(ConfigurationManager.Configuration.FileWatcherDelay), TimeSpan.FromMilliseconds(-1));
  323. }
  324. }
  325. }
  326. /// <summary>
  327. /// Timers the stopped.
  328. /// </summary>
  329. /// <param name="stateInfo">The state info.</param>
  330. private async void TimerStopped(object stateInfo)
  331. {
  332. lock (_timerLock)
  333. {
  334. // Extend the timer as long as any of the paths are still being written to.
  335. if (_affectedPaths.Any(p => IsFileLocked(p.Key)))
  336. {
  337. Logger.Info("Timer extended.");
  338. _updateTimer.Change(TimeSpan.FromSeconds(ConfigurationManager.Configuration.FileWatcherDelay), TimeSpan.FromMilliseconds(-1));
  339. return;
  340. }
  341. Logger.Info("Timer stopped.");
  342. _updateTimer.Dispose();
  343. _updateTimer = null;
  344. }
  345. var paths = _affectedPaths.Keys.ToList();
  346. _affectedPaths.Clear();
  347. await ProcessPathChanges(paths).ConfigureAwait(false);
  348. }
  349. /// <summary>
  350. /// Try and determine if a file is locked
  351. /// This is not perfect, and is subject to race conditions, so I'd rather not make this a re-usable library method.
  352. /// </summary>
  353. /// <param name="path">The path.</param>
  354. /// <returns><c>true</c> if [is file locked] [the specified path]; otherwise, <c>false</c>.</returns>
  355. private bool IsFileLocked(string path)
  356. {
  357. try
  358. {
  359. var data = FileSystem.GetFileSystemInfo(path);
  360. if (!data.Exists
  361. || data.Attributes.HasFlag(FileAttributes.Directory)
  362. || data.Attributes.HasFlag(FileAttributes.ReadOnly))
  363. {
  364. return false;
  365. }
  366. }
  367. catch (IOException)
  368. {
  369. return false;
  370. }
  371. try
  372. {
  373. using (new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
  374. {
  375. //file is not locked
  376. return false;
  377. }
  378. }
  379. catch
  380. {
  381. //the file is unavailable because it is:
  382. //still being written to
  383. //or being processed by another thread
  384. //or does not exist (has already been processed)
  385. Logger.Debug("{0} is locked.", path);
  386. return true;
  387. }
  388. }
  389. /// <summary>
  390. /// Processes the path changes.
  391. /// </summary>
  392. /// <param name="paths">The paths.</param>
  393. /// <returns>Task.</returns>
  394. private async Task ProcessPathChanges(List<string> paths)
  395. {
  396. var itemsToRefresh = paths.Select(Path.GetDirectoryName)
  397. .Select(GetAffectedBaseItem)
  398. .Where(item => item != null)
  399. .Distinct()
  400. .ToList();
  401. foreach (var p in paths) Logger.Info(p + " reports change.");
  402. // If the root folder changed, run the library task so the user can see it
  403. if (itemsToRefresh.Any(i => i is AggregateFolder))
  404. {
  405. TaskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  406. return;
  407. }
  408. await Task.WhenAll(itemsToRefresh.Select(i => Task.Run(async () =>
  409. {
  410. Logger.Info(i.Name + " (" + i.Path + ") will be refreshed.");
  411. try
  412. {
  413. await i.ChangedExternally().ConfigureAwait(false);
  414. }
  415. catch (IOException ex)
  416. {
  417. // For now swallow and log.
  418. // Research item: If an IOException occurs, the item may be in a disconnected state (media unavailable)
  419. // Should we remove it from it's parent?
  420. Logger.ErrorException("Error refreshing {0}", ex, i.Name);
  421. }
  422. catch (Exception ex)
  423. {
  424. Logger.ErrorException("Error refreshing {0}", ex, i.Name);
  425. }
  426. }))).ConfigureAwait(false);
  427. }
  428. /// <summary>
  429. /// Gets the affected base item.
  430. /// </summary>
  431. /// <param name="path">The path.</param>
  432. /// <returns>BaseItem.</returns>
  433. private BaseItem GetAffectedBaseItem(string path)
  434. {
  435. BaseItem item = null;
  436. while (item == null && !string.IsNullOrEmpty(path))
  437. {
  438. item = LibraryManager.RootFolder.FindByPath(path);
  439. path = Path.GetDirectoryName(path);
  440. }
  441. if (item != null)
  442. {
  443. // If the item has been deleted find the first valid parent that still exists
  444. while (!Directory.Exists(item.Path) && !File.Exists(item.Path))
  445. {
  446. item = item.Parent;
  447. if (item == null)
  448. {
  449. break;
  450. }
  451. }
  452. }
  453. return item;
  454. }
  455. /// <summary>
  456. /// Stops this instance.
  457. /// </summary>
  458. public void Stop()
  459. {
  460. LibraryManager.ItemAdded -= LibraryManager_ItemAdded;
  461. LibraryManager.ItemRemoved -= LibraryManager_ItemRemoved;
  462. foreach (var watcher in _fileSystemWatchers.Values.ToList())
  463. {
  464. watcher.Changed -= watcher_Changed;
  465. watcher.EnableRaisingEvents = false;
  466. watcher.Dispose();
  467. }
  468. lock (_timerLock)
  469. {
  470. if (_updateTimer != null)
  471. {
  472. _updateTimer.Dispose();
  473. _updateTimer = null;
  474. }
  475. }
  476. _affectedPaths.Clear();
  477. }
  478. /// <summary>
  479. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  480. /// </summary>
  481. public void Dispose()
  482. {
  483. Dispose(true);
  484. GC.SuppressFinalize(this);
  485. }
  486. /// <summary>
  487. /// Releases unmanaged and - optionally - managed resources.
  488. /// </summary>
  489. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  490. protected virtual void Dispose(bool dispose)
  491. {
  492. if (dispose)
  493. {
  494. Stop();
  495. }
  496. }
  497. }
  498. }