2
0

TvFolderOrganizer.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.FileOrganization;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Controller.Providers;
  6. using MediaBrowser.Model.FileOrganization;
  7. using MediaBrowser.Model.Logging;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. namespace MediaBrowser.Server.Implementations.FileOrganization
  15. {
  16. public class TvFolderOrganizer
  17. {
  18. private readonly ILibraryMonitor _libraryMonitor;
  19. private readonly ILibraryManager _libraryManager;
  20. private readonly ILogger _logger;
  21. private readonly IFileSystem _fileSystem;
  22. private readonly IFileOrganizationService _organizationService;
  23. private readonly IServerConfigurationManager _config;
  24. private readonly IProviderManager _providerManager;
  25. public TvFolderOrganizer(ILibraryManager libraryManager, ILogger logger, IFileSystem fileSystem, ILibraryMonitor libraryMonitor, IFileOrganizationService organizationService, IServerConfigurationManager config, IProviderManager providerManager)
  26. {
  27. _libraryManager = libraryManager;
  28. _logger = logger;
  29. _fileSystem = fileSystem;
  30. _libraryMonitor = libraryMonitor;
  31. _organizationService = organizationService;
  32. _config = config;
  33. _providerManager = providerManager;
  34. }
  35. public async Task Organize(TvFileOrganizationOptions options, CancellationToken cancellationToken, IProgress<double> progress)
  36. {
  37. var minFileBytes = options.MinFileSizeMb * 1024 * 1024;
  38. var watchLocations = options.WatchLocations.ToList();
  39. var eligibleFiles = watchLocations.SelectMany(GetFilesToOrganize)
  40. .OrderBy(_fileSystem.GetCreationTimeUtc)
  41. .Where(i => _libraryManager.IsVideoFile(i.FullName) && i.Length >= minFileBytes)
  42. .ToList();
  43. var processedFolders = new HashSet<string>();
  44. progress.Report(10);
  45. if (eligibleFiles.Count > 0)
  46. {
  47. var numComplete = 0;
  48. foreach (var file in eligibleFiles)
  49. {
  50. var organizer = new EpisodeFileOrganizer(_organizationService, _config, _fileSystem, _logger, _libraryManager,
  51. _libraryMonitor, _providerManager);
  52. try
  53. {
  54. var result = await organizer.OrganizeEpisodeFile(file.FullName, options, options.OverwriteExistingEpisodes, cancellationToken).ConfigureAwait(false);
  55. if (result.Status == FileSortingStatus.Success && !processedFolders.Contains(file.DirectoryName))
  56. {
  57. processedFolders.Add(file.DirectoryName);
  58. }
  59. }
  60. catch (Exception ex)
  61. {
  62. _logger.ErrorException("Error organizing episode {0}", ex, file);
  63. }
  64. numComplete++;
  65. double percent = numComplete;
  66. percent /= eligibleFiles.Count;
  67. progress.Report(10 + (89 * percent));
  68. }
  69. }
  70. cancellationToken.ThrowIfCancellationRequested();
  71. progress.Report(99);
  72. foreach (var path in processedFolders)
  73. {
  74. var deleteExtensions = options.LeftOverFileExtensionsToDelete
  75. .Select(i => i.Trim().TrimStart('.'))
  76. .Where(i => !string.IsNullOrEmpty(i))
  77. .Select(i => "." + i)
  78. .ToList();
  79. if (deleteExtensions.Count > 0)
  80. {
  81. DeleteLeftOverFiles(path, deleteExtensions);
  82. }
  83. if (options.DeleteEmptyFolders)
  84. {
  85. if (!IsWatchFolder(path, watchLocations))
  86. {
  87. DeleteEmptyFolders(path);
  88. }
  89. }
  90. }
  91. progress.Report(100);
  92. }
  93. /// <summary>
  94. /// Gets the files to organize.
  95. /// </summary>
  96. /// <param name="path">The path.</param>
  97. /// <returns>IEnumerable{FileInfo}.</returns>
  98. private IEnumerable<FileInfo> GetFilesToOrganize(string path)
  99. {
  100. try
  101. {
  102. return _fileSystem.GetFiles(path, true)
  103. .ToList();
  104. }
  105. catch (IOException ex)
  106. {
  107. _logger.ErrorException("Error getting files from {0}", ex, path);
  108. return new List<FileInfo>();
  109. }
  110. }
  111. /// <summary>
  112. /// Deletes the left over files.
  113. /// </summary>
  114. /// <param name="path">The path.</param>
  115. /// <param name="extensions">The extensions.</param>
  116. private void DeleteLeftOverFiles(string path, IEnumerable<string> extensions)
  117. {
  118. var eligibleFiles = _fileSystem.GetFiles(path, true)
  119. .Where(i => extensions.Contains(i.Extension, StringComparer.OrdinalIgnoreCase))
  120. .ToList();
  121. foreach (var file in eligibleFiles)
  122. {
  123. try
  124. {
  125. _fileSystem.DeleteFile(file.FullName);
  126. }
  127. catch (Exception ex)
  128. {
  129. _logger.ErrorException("Error deleting file {0}", ex, file.FullName);
  130. }
  131. }
  132. }
  133. /// <summary>
  134. /// Deletes the empty folders.
  135. /// </summary>
  136. /// <param name="path">The path.</param>
  137. private void DeleteEmptyFolders(string path)
  138. {
  139. try
  140. {
  141. foreach (var d in _fileSystem.GetDirectoryPaths(path))
  142. {
  143. DeleteEmptyFolders(d);
  144. }
  145. var entries = _fileSystem.GetFileSystemEntryPaths(path);
  146. if (!entries.Any())
  147. {
  148. try
  149. {
  150. _logger.Debug("Deleting empty directory {0}", path);
  151. _fileSystem.DeleteDirectory(path, false);
  152. }
  153. catch (UnauthorizedAccessException) { }
  154. catch (DirectoryNotFoundException) { }
  155. }
  156. }
  157. catch (UnauthorizedAccessException) { }
  158. }
  159. /// <summary>
  160. /// Determines if a given folder path is contained in a folder list
  161. /// </summary>
  162. /// <param name="path">The folder path to check.</param>
  163. /// <param name="watchLocations">A list of folders.</param>
  164. private bool IsWatchFolder(string path, IEnumerable<string> watchLocations)
  165. {
  166. // Use GetFullPath to resolve 8.3 naming and path indirections
  167. path = Path.GetFullPath(path);
  168. foreach (var watchFolder in watchLocations)
  169. {
  170. if (String.Equals(path, Path.GetFullPath(watchFolder), StringComparison.OrdinalIgnoreCase))
  171. {
  172. return true;
  173. }
  174. }
  175. return false;
  176. }
  177. }
  178. }