FileRefresher.cs 9.6 KB

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