FileRefresher.cs 9.9 KB

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