FileRefresher.cs 9.9 KB

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