FileRefresher.cs 7.8 KB

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