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