FileRefresher.cs 10.0 KB

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