DirectoryWatchers.cs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. using MediaBrowser.Controller.Entities;
  2. using MediaBrowser.Common.Logging;
  3. using MediaBrowser.Common.Extensions;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. namespace MediaBrowser.Controller.IO
  11. {
  12. public class DirectoryWatchers
  13. {
  14. private readonly List<FileSystemWatcher> FileSystemWatchers = new List<FileSystemWatcher>();
  15. private Timer updateTimer;
  16. private List<string> affectedPaths = new List<string>();
  17. private const int TimerDelayInSeconds = 30;
  18. public void Start()
  19. {
  20. var pathsToWatch = new List<string>();
  21. var rootFolder = Kernel.Instance.RootFolder;
  22. pathsToWatch.Add(rootFolder.Path);
  23. foreach (Folder folder in rootFolder.Children.OfType<Folder>())
  24. {
  25. foreach (string path in folder.PhysicalLocations)
  26. {
  27. if (Path.IsPathRooted(path) && !pathsToWatch.ContainsParentFolder(path))
  28. {
  29. pathsToWatch.Add(path);
  30. }
  31. }
  32. }
  33. foreach (string path in pathsToWatch)
  34. {
  35. Logger.LogInfo("Watching directory " + path + " for changes.");
  36. var watcher = new FileSystemWatcher(path, "*") { };
  37. watcher.IncludeSubdirectories = true;
  38. //watcher.Changed += watcher_Changed;
  39. // All the others seem to trigger change events on the parent, so let's keep it simple for now.
  40. // Actually, we really need to only watch created, deleted and renamed as changed fires too much -ebr
  41. watcher.Created += watcher_Changed;
  42. watcher.Deleted += watcher_Changed;
  43. watcher.Renamed += watcher_Changed;
  44. watcher.EnableRaisingEvents = true;
  45. FileSystemWatchers.Add(watcher);
  46. }
  47. }
  48. void watcher_Changed(object sender, FileSystemEventArgs e)
  49. {
  50. Logger.LogDebugInfo("****** Watcher sees change of type " + e.ChangeType.ToString() + " to " + e.FullPath);
  51. lock (affectedPaths)
  52. {
  53. if (!affectedPaths.Contains(e.FullPath))
  54. {
  55. Logger.LogDebugInfo("****** Adding " + e.FullPath + " to affected paths.");
  56. affectedPaths.Add(e.FullPath);
  57. }
  58. if (e.ChangeType == WatcherChangeTypes.Renamed)
  59. {
  60. var renamedArgs = e as RenamedEventArgs;
  61. if (affectedPaths.Contains(renamedArgs.OldFullPath))
  62. {
  63. Logger.LogDebugInfo("****** Removing " + renamedArgs.OldFullPath + " from affected paths.");
  64. affectedPaths.Remove(renamedArgs.OldFullPath);
  65. }
  66. }
  67. }
  68. if (updateTimer == null)
  69. {
  70. updateTimer = new Timer(TimerStopped, null, TimeSpan.FromSeconds(TimerDelayInSeconds), TimeSpan.FromMilliseconds(-1));
  71. }
  72. else
  73. {
  74. updateTimer.Change(TimeSpan.FromSeconds(TimerDelayInSeconds), TimeSpan.FromMilliseconds(-1));
  75. }
  76. }
  77. private async void TimerStopped(object stateInfo)
  78. {
  79. updateTimer.Dispose();
  80. updateTimer = null;
  81. List<string> paths;
  82. lock (affectedPaths)
  83. {
  84. paths = affectedPaths;
  85. affectedPaths = new List<string>();
  86. }
  87. await ProcessPathChanges(paths).ConfigureAwait(false);
  88. }
  89. private Task ProcessPathChanges(IEnumerable<string> paths)
  90. {
  91. var itemsToRefresh = new List<BaseItem>();
  92. foreach (BaseItem item in paths.Select(p => GetAffectedBaseItem(p)))
  93. {
  94. if (item != null && !itemsToRefresh.Contains(item))
  95. {
  96. itemsToRefresh.Add(item);
  97. }
  98. }
  99. if (itemsToRefresh.Any(i =>
  100. {
  101. var folder = i as Folder;
  102. return folder != null && folder.IsRoot;
  103. }))
  104. {
  105. return Kernel.Instance.ReloadRoot();
  106. }
  107. foreach (var p in paths) Logger.LogDebugInfo("********* "+ p + " reports change.");
  108. foreach (var i in itemsToRefresh) Logger.LogDebugInfo("********* "+i.Name + " will be refreshed.");
  109. return Task.WhenAll(itemsToRefresh.Select(i => i.ChangedExternally()));
  110. }
  111. private BaseItem GetAffectedBaseItem(string path)
  112. {
  113. BaseItem item = null;
  114. while (item == null && !string.IsNullOrEmpty(path))
  115. {
  116. item = Kernel.Instance.RootFolder.FindByPath(path);
  117. path = Path.GetDirectoryName(path);
  118. }
  119. return item;
  120. }
  121. public void Stop()
  122. {
  123. foreach (FileSystemWatcher watcher in FileSystemWatchers)
  124. {
  125. watcher.Changed -= watcher_Changed;
  126. watcher.EnableRaisingEvents = false;
  127. watcher.Dispose();
  128. }
  129. if (updateTimer != null)
  130. {
  131. updateTimer.Dispose();
  132. updateTimer = null;
  133. }
  134. FileSystemWatchers.Clear();
  135. affectedPaths.Clear();
  136. }
  137. }
  138. }