TvFileSorter.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. using MediaBrowser.Controller.Entities.TV;
  2. using MediaBrowser.Controller.Library;
  3. using MediaBrowser.Controller.Providers;
  4. using MediaBrowser.Controller.Resolvers;
  5. using MediaBrowser.Model.Configuration;
  6. using MediaBrowser.Model.Entities;
  7. using MediaBrowser.Model.Logging;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.IO;
  11. using System.Linq;
  12. namespace MediaBrowser.Server.Implementations.FileSorting
  13. {
  14. public class TvFileSorter
  15. {
  16. private readonly ILibraryManager _libraryManager;
  17. private readonly ILogger _logger;
  18. public TvFileSorter(ILibraryManager libraryManager, ILogger logger)
  19. {
  20. _libraryManager = libraryManager;
  21. _logger = logger;
  22. }
  23. public void Sort(string path, FileSortingOptions options)
  24. {
  25. var minFileBytes = options.MinFileSizeMb * 1024 * 1024;
  26. var eligibleFiles = new DirectoryInfo(path)
  27. .EnumerateFiles("*", SearchOption.AllDirectories)
  28. .Where(i => EntityResolutionHelper.IsVideoFile(i.FullName) && i.Length >= minFileBytes)
  29. .ToList();
  30. if (eligibleFiles.Count == 0)
  31. {
  32. // Nothing to do
  33. return;
  34. }
  35. var allSeries = _libraryManager.RootFolder
  36. .RecursiveChildren.OfType<Series>()
  37. .Where(i => i.LocationType == LocationType.FileSystem)
  38. .ToList();
  39. foreach (var file in eligibleFiles)
  40. {
  41. SortFile(file.FullName, options, allSeries);
  42. }
  43. if (options.LeftOverFileExtensionsToDelete.Length > 0)
  44. {
  45. DeleteLeftOverFiles(path, options.LeftOverFileExtensionsToDelete);
  46. }
  47. if (options.DeleteEmptyFolders)
  48. {
  49. DeleteEmptyFolders(path);
  50. }
  51. }
  52. private void SortFile(string path, FileSortingOptions options, IEnumerable<Series> allSeries)
  53. {
  54. _logger.Info("Sorting file {0}", path);
  55. var seriesName = TVUtils.GetSeriesNameFromEpisodeFile(path);
  56. if (!string.IsNullOrEmpty(seriesName))
  57. {
  58. var season = TVUtils.GetSeasonNumberFromEpisodeFile(path);
  59. if (season.HasValue)
  60. {
  61. // Passing in true will include a few extra regex's
  62. var episode = TVUtils.GetEpisodeNumberFromFile(path, true);
  63. if (episode.HasValue)
  64. {
  65. _logger.Debug("Extracted information from {0}. Series name {1}, Season {2}, Episode {3}", path, seriesName, season, episode);
  66. SortFile(path, seriesName, season.Value, episode.Value, options, allSeries);
  67. }
  68. else
  69. {
  70. _logger.Warn("Unable to determine episode number from {0}", path);
  71. }
  72. }
  73. else
  74. {
  75. _logger.Warn("Unable to determine season number from {0}", path);
  76. }
  77. }
  78. else
  79. {
  80. _logger.Warn("Unable to determine series name from {0}", path);
  81. }
  82. }
  83. private void SortFile(string path, string seriesName, int seasonNumber, int episodeNumber, FileSortingOptions options, IEnumerable<Series> allSeries)
  84. {
  85. var series = GetMatchingSeries(seriesName, allSeries);
  86. if (series == null)
  87. {
  88. _logger.Warn("Unable to find series in library matching name {0}", seriesName);
  89. return;
  90. }
  91. _logger.Info("Sorting file {0} into series {1}", path, series.Path);
  92. // Proceed to sort the file
  93. }
  94. private Series GetMatchingSeries(string seriesName, IEnumerable<Series> allSeries)
  95. {
  96. int? yearInName;
  97. var nameWithoutYear = seriesName;
  98. NameParser.ParseName(nameWithoutYear, out nameWithoutYear, out yearInName);
  99. return allSeries.Select(i => GetMatchScore(nameWithoutYear, yearInName, i))
  100. .Where(i => i.Item2 > 0)
  101. .OrderByDescending(i => i.Item2)
  102. .Select(i => i.Item1)
  103. .FirstOrDefault();
  104. }
  105. private Tuple<Series, int> GetMatchScore(string sortedName, int? year, Series series)
  106. {
  107. var score = 0;
  108. // TODO: Improve this
  109. if (string.Equals(sortedName, series.Name, StringComparison.OrdinalIgnoreCase))
  110. {
  111. score++;
  112. if (year.HasValue && series.ProductionYear.HasValue)
  113. {
  114. if (year.Value == series.ProductionYear.Value)
  115. {
  116. score++;
  117. }
  118. else
  119. {
  120. // Regardless of name, return a 0 score if the years don't match
  121. return new Tuple<Series, int>(series, 0);
  122. }
  123. }
  124. }
  125. return new Tuple<Series, int>(series, score);
  126. }
  127. /// <summary>
  128. /// Deletes the left over files.
  129. /// </summary>
  130. /// <param name="path">The path.</param>
  131. /// <param name="extensions">The extensions.</param>
  132. private void DeleteLeftOverFiles(string path, IEnumerable<string> extensions)
  133. {
  134. var eligibleFiles = new DirectoryInfo(path)
  135. .EnumerateFiles("*", SearchOption.AllDirectories)
  136. .Where(i => extensions.Contains(i.Extension, StringComparer.OrdinalIgnoreCase))
  137. .ToList();
  138. foreach (var file in eligibleFiles)
  139. {
  140. try
  141. {
  142. File.Delete(file.FullName);
  143. }
  144. catch (IOException ex)
  145. {
  146. _logger.ErrorException("Error deleting file {0}", ex, file.FullName);
  147. }
  148. }
  149. }
  150. /// <summary>
  151. /// Deletes the empty folders.
  152. /// </summary>
  153. /// <param name="path">The path.</param>
  154. private void DeleteEmptyFolders(string path)
  155. {
  156. try
  157. {
  158. foreach (var d in Directory.EnumerateDirectories(path))
  159. {
  160. DeleteEmptyFolders(d);
  161. }
  162. var entries = Directory.EnumerateFileSystemEntries(path);
  163. if (!entries.Any())
  164. {
  165. try
  166. {
  167. Directory.Delete(path);
  168. }
  169. catch (UnauthorizedAccessException) { }
  170. catch (DirectoryNotFoundException) { }
  171. }
  172. }
  173. catch (UnauthorizedAccessException) { }
  174. }
  175. }
  176. }