FileRefresher.cs 10 KB

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