FileRefresher.cs 9.8 KB

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