FileRefresher.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using CommonIO;
  8. using MediaBrowser.Common.Events;
  9. using MediaBrowser.Common.ScheduledTasks;
  10. using MediaBrowser.Controller.Configuration;
  11. using MediaBrowser.Controller.Entities;
  12. using MediaBrowser.Controller.Library;
  13. using MediaBrowser.Model.Logging;
  14. using MediaBrowser.Server.Implementations.ScheduledTasks;
  15. namespace MediaBrowser.Server.Implementations.IO
  16. {
  17. public class FileRefresher : IDisposable
  18. {
  19. private ILogger Logger { get; set; }
  20. private ITaskManager TaskManager { get; set; }
  21. private ILibraryManager LibraryManager { get; set; }
  22. private IServerConfigurationManager ConfigurationManager { get; set; }
  23. private readonly IFileSystem _fileSystem;
  24. private readonly List<string> _affectedPaths = new List<string>();
  25. private Timer _timer;
  26. private readonly object _timerLock = new object();
  27. public string Path { get; private set; }
  28. public event EventHandler<EventArgs> Completed;
  29. public FileRefresher(string path, IFileSystem fileSystem, IServerConfigurationManager configurationManager, ILibraryManager libraryManager, ITaskManager taskManager, ILogger logger)
  30. {
  31. logger.Debug("New file refresher created for {0}", path);
  32. Path = path;
  33. _affectedPaths.Add(path);
  34. _fileSystem = fileSystem;
  35. ConfigurationManager = configurationManager;
  36. LibraryManager = libraryManager;
  37. TaskManager = taskManager;
  38. Logger = logger;
  39. }
  40. private void AddAffectedPath(string path)
  41. {
  42. if (!_affectedPaths.Contains(path, StringComparer.Ordinal))
  43. {
  44. _affectedPaths.Add(path);
  45. }
  46. }
  47. public void AddPath(string path)
  48. {
  49. lock (_timerLock)
  50. {
  51. AddAffectedPath(path);
  52. }
  53. RestartTimer();
  54. }
  55. public void RestartTimer()
  56. {
  57. lock (_timerLock)
  58. {
  59. if (_timer == null)
  60. {
  61. _timer = new Timer(OnTimerCallback, null, TimeSpan.FromSeconds(ConfigurationManager.Configuration.LibraryMonitorDelay), TimeSpan.FromMilliseconds(-1));
  62. }
  63. else
  64. {
  65. _timer.Change(TimeSpan.FromSeconds(ConfigurationManager.Configuration.LibraryMonitorDelay), TimeSpan.FromMilliseconds(-1));
  66. }
  67. }
  68. }
  69. public void ResetPath(string path, string affectedFile)
  70. {
  71. lock (_timerLock)
  72. {
  73. Logger.Debug("Resetting file refresher from {0} to {1}", Path, path);
  74. Path = path;
  75. AddAffectedPath(path);
  76. if (!string.IsNullOrWhiteSpace(affectedFile))
  77. {
  78. AddAffectedPath(affectedFile);
  79. }
  80. }
  81. RestartTimer();
  82. }
  83. private async void OnTimerCallback(object state)
  84. {
  85. // Extend the timer as long as any of the paths are still being written to.
  86. if (_affectedPaths.Any(IsFileLocked))
  87. {
  88. Logger.Info("Timer extended.");
  89. RestartTimer();
  90. return;
  91. }
  92. Logger.Debug("Timer stopped.");
  93. DisposeTimer();
  94. EventHelper.FireEventIfNotNull(Completed, this, EventArgs.Empty, Logger);
  95. try
  96. {
  97. await ProcessPathChanges(_affectedPaths.ToList()).ConfigureAwait(false);
  98. }
  99. catch (Exception ex)
  100. {
  101. Logger.ErrorException("Error processing directory changes", ex);
  102. }
  103. }
  104. private async Task ProcessPathChanges(List<string> paths)
  105. {
  106. var itemsToRefresh = paths
  107. .Select(GetAffectedBaseItem)
  108. .Where(item => item != null)
  109. .Distinct()
  110. .ToList();
  111. foreach (var p in paths)
  112. {
  113. Logger.Info(p + " reports change.");
  114. }
  115. // If the root folder changed, run the library task so the user can see it
  116. if (itemsToRefresh.Any(i => i is AggregateFolder))
  117. {
  118. TaskManager.CancelIfRunningAndQueue<RefreshMediaLibraryTask>();
  119. return;
  120. }
  121. foreach (var item in itemsToRefresh)
  122. {
  123. Logger.Info(item.Name + " (" + item.Path + ") will be refreshed.");
  124. try
  125. {
  126. await item.ChangedExternally().ConfigureAwait(false);
  127. }
  128. catch (IOException ex)
  129. {
  130. // For now swallow and log.
  131. // Research item: If an IOException occurs, the item may be in a disconnected state (media unavailable)
  132. // Should we remove it from it's parent?
  133. Logger.ErrorException("Error refreshing {0}", ex, item.Name);
  134. }
  135. catch (Exception ex)
  136. {
  137. Logger.ErrorException("Error refreshing {0}", ex, item.Name);
  138. }
  139. }
  140. }
  141. /// <summary>
  142. /// Gets the affected base item.
  143. /// </summary>
  144. /// <param name="path">The path.</param>
  145. /// <returns>BaseItem.</returns>
  146. private BaseItem GetAffectedBaseItem(string path)
  147. {
  148. BaseItem item = null;
  149. while (item == null && !string.IsNullOrEmpty(path))
  150. {
  151. item = LibraryManager.FindByPath(path, null);
  152. path = System.IO.Path.GetDirectoryName(path);
  153. }
  154. if (item != null)
  155. {
  156. // If the item has been deleted find the first valid parent that still exists
  157. while (!_fileSystem.DirectoryExists(item.Path) && !_fileSystem.FileExists(item.Path))
  158. {
  159. item = item.GetParent();
  160. if (item == null)
  161. {
  162. break;
  163. }
  164. }
  165. }
  166. return item;
  167. }
  168. private bool IsFileLocked(string path)
  169. {
  170. if (Environment.OSVersion.Platform != PlatformID.Win32NT)
  171. {
  172. // Causing lockups on linux
  173. return false;
  174. }
  175. try
  176. {
  177. var data = _fileSystem.GetFileSystemInfo(path);
  178. if (!data.Exists
  179. || data.IsDirectory
  180. // Opening a writable stream will fail with readonly files
  181. || data.Attributes.HasFlag(FileAttributes.ReadOnly))
  182. {
  183. return false;
  184. }
  185. }
  186. catch (IOException)
  187. {
  188. return false;
  189. }
  190. catch (Exception ex)
  191. {
  192. Logger.ErrorException("Error getting file system info for: {0}", ex, path);
  193. return false;
  194. }
  195. // In order to determine if the file is being written to, we have to request write access
  196. // But if the server only has readonly access, this is going to cause this entire algorithm to fail
  197. // So we'll take a best guess about our access level
  198. var requestedFileAccess = ConfigurationManager.Configuration.SaveLocalMeta
  199. ? FileAccess.ReadWrite
  200. : FileAccess.Read;
  201. try
  202. {
  203. using (_fileSystem.GetFileStream(path, FileMode.Open, requestedFileAccess, FileShare.ReadWrite))
  204. {
  205. //file is not locked
  206. return false;
  207. }
  208. }
  209. catch (DirectoryNotFoundException)
  210. {
  211. // File may have been deleted
  212. return false;
  213. }
  214. catch (FileNotFoundException)
  215. {
  216. // File may have been deleted
  217. return false;
  218. }
  219. catch (IOException)
  220. {
  221. //the file is unavailable because it is:
  222. //still being written to
  223. //or being processed by another thread
  224. //or does not exist (has already been processed)
  225. Logger.Debug("{0} is locked.", path);
  226. return true;
  227. }
  228. catch (Exception ex)
  229. {
  230. Logger.ErrorException("Error determining if file is locked: {0}", ex, path);
  231. return false;
  232. }
  233. }
  234. private void DisposeTimer()
  235. {
  236. lock (_timerLock)
  237. {
  238. if (_timer != null)
  239. {
  240. _timer.Dispose();
  241. }
  242. }
  243. }
  244. public void Dispose()
  245. {
  246. DisposeTimer();
  247. }
  248. }
  249. }