FileRefresher.cs 10 KB

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