FileRefresher.cs 11 KB

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