TvFileSorter.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. using System.Globalization;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller.Entities.TV;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Controller.Providers;
  6. using MediaBrowser.Controller.Resolvers;
  7. using MediaBrowser.Model.Configuration;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Model.Logging;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Linq;
  14. namespace MediaBrowser.Server.Implementations.FileSorting
  15. {
  16. public class TvFileSorter
  17. {
  18. private readonly ILibraryManager _libraryManager;
  19. private readonly ILogger _logger;
  20. private readonly IFileSystem _fileSystem;
  21. private static CultureInfo _usCulture = new CultureInfo("en-US");
  22. public TvFileSorter(ILibraryManager libraryManager, ILogger logger)
  23. {
  24. _libraryManager = libraryManager;
  25. _logger = logger;
  26. }
  27. public void Sort(string path, FileSortingOptions options)
  28. {
  29. var minFileBytes = options.MinFileSizeMb * 1024 * 1024;
  30. var eligibleFiles = new DirectoryInfo(path)
  31. .EnumerateFiles("*", SearchOption.AllDirectories)
  32. .Where(i => EntityResolutionHelper.IsVideoFile(i.FullName) && i.Length >= minFileBytes)
  33. .ToList();
  34. if (eligibleFiles.Count > 0)
  35. {
  36. var allSeries = _libraryManager.RootFolder
  37. .RecursiveChildren.OfType<Series>()
  38. .Where(i => i.LocationType == LocationType.FileSystem)
  39. .ToList();
  40. foreach (var file in eligibleFiles)
  41. {
  42. SortFile(file.FullName, options, allSeries);
  43. }
  44. }
  45. if (options.LeftOverFileExtensionsToDelete.Length > 0)
  46. {
  47. DeleteLeftOverFiles(path, options.LeftOverFileExtensionsToDelete);
  48. }
  49. if (options.DeleteEmptyFolders)
  50. {
  51. DeleteEmptyFolders(path);
  52. }
  53. }
  54. private void SortFile(string path, FileSortingOptions options, IEnumerable<Series> allSeries)
  55. {
  56. _logger.Info("Sorting file {0}", path);
  57. var seriesName = TVUtils.GetSeriesNameFromEpisodeFile(path);
  58. if (!string.IsNullOrEmpty(seriesName))
  59. {
  60. var season = TVUtils.GetSeasonNumberFromEpisodeFile(path);
  61. if (season.HasValue)
  62. {
  63. // Passing in true will include a few extra regex's
  64. var episode = TVUtils.GetEpisodeNumberFromFile(path, true);
  65. if (episode.HasValue)
  66. {
  67. _logger.Debug("Extracted information from {0}. Series name {1}, Season {2}, Episode {3}", path, seriesName, season, episode);
  68. SortFile(path, seriesName, season.Value, episode.Value, options, allSeries);
  69. }
  70. else
  71. {
  72. _logger.Warn("Unable to determine episode number from {0}", path);
  73. }
  74. }
  75. else
  76. {
  77. _logger.Warn("Unable to determine season number from {0}", path);
  78. }
  79. }
  80. else
  81. {
  82. _logger.Warn("Unable to determine series name from {0}", path);
  83. }
  84. }
  85. private void SortFile(string path, string seriesName, int seasonNumber, int episodeNumber, FileSortingOptions options, IEnumerable<Series> allSeries)
  86. {
  87. var series = GetMatchingSeries(seriesName, allSeries);
  88. if (series == null)
  89. {
  90. _logger.Warn("Unable to find series in library matching name {0}", seriesName);
  91. return;
  92. }
  93. _logger.Info("Sorting file {0} into series {1}", path, series.Path);
  94. // Proceed to sort the file
  95. var newPath = GetNewPath(series, seasonNumber, episodeNumber, options);
  96. if (string.IsNullOrEmpty(newPath))
  97. {
  98. _logger.Warn("Unable to sort {0} because target path could not be found.", path);
  99. return;
  100. }
  101. _logger.Info("Sorting file {0} to new path {1}", path, newPath);
  102. }
  103. private string GetNewPath(Series series, int seasonNumber, int episodeNumber, FileSortingOptions options)
  104. {
  105. var currentEpisodes = series.RecursiveChildren.OfType<Episode>()
  106. .Where(i => i.IndexNumber.HasValue && i.IndexNumber.Value == episodeNumber && i.ParentIndexNumber.HasValue && i.ParentIndexNumber.Value == seasonNumber)
  107. .ToList();
  108. if (currentEpisodes.Count == 0)
  109. {
  110. return null;
  111. }
  112. var newPath = currentEpisodes
  113. .Where(i => i.LocationType == LocationType.FileSystem)
  114. .Select(i => i.Path)
  115. .FirstOrDefault();
  116. if (string.IsNullOrEmpty(newPath))
  117. {
  118. newPath = GetSeasonFolderPath(series, seasonNumber, options);
  119. var episode = currentEpisodes.First();
  120. var episodeFileName = string.Format("{0} - {1}x{2} - {3}",
  121. _fileSystem.GetValidFilename(series.Name),
  122. seasonNumber.ToString(_usCulture),
  123. episodeNumber.ToString("00", _usCulture),
  124. _fileSystem.GetValidFilename(episode.Name)
  125. );
  126. newPath = Path.Combine(newPath, episodeFileName);
  127. }
  128. return newPath;
  129. }
  130. private string GetSeasonFolderPath(Series series, int seasonNumber, FileSortingOptions options)
  131. {
  132. // If there's already a season folder, use that
  133. var season = series
  134. .RecursiveChildren
  135. .OfType<Season>()
  136. .FirstOrDefault(i => i.LocationType == LocationType.FileSystem && i.IndexNumber.HasValue && i.IndexNumber.Value == seasonNumber);
  137. if (season != null)
  138. {
  139. return season.Path;
  140. }
  141. var path = series.Path;
  142. if (series.ContainsEpisodesWithoutSeasonFolders)
  143. {
  144. return path;
  145. }
  146. if (seasonNumber == 0)
  147. {
  148. return Path.Combine(path, _fileSystem.GetValidFilename(options.SeasonZeroFolderName));
  149. }
  150. var seasonFolderName = options.SeasonFolderPattern
  151. .Replace("%s", seasonNumber.ToString(_usCulture))
  152. .Replace("%0s", seasonNumber.ToString("00", _usCulture))
  153. .Replace("%00s", seasonNumber.ToString("000", _usCulture));
  154. return Path.Combine(path, _fileSystem.GetValidFilename(seasonFolderName));
  155. }
  156. private Series GetMatchingSeries(string seriesName, IEnumerable<Series> allSeries)
  157. {
  158. int? yearInName;
  159. var nameWithoutYear = seriesName;
  160. NameParser.ParseName(nameWithoutYear, out nameWithoutYear, out yearInName);
  161. return allSeries.Select(i => GetMatchScore(nameWithoutYear, yearInName, i))
  162. .Where(i => i.Item2 > 0)
  163. .OrderByDescending(i => i.Item2)
  164. .Select(i => i.Item1)
  165. .FirstOrDefault();
  166. }
  167. private Tuple<Series, int> GetMatchScore(string sortedName, int? year, Series series)
  168. {
  169. var score = 0;
  170. // TODO: Improve this
  171. if (string.Equals(sortedName, series.Name, StringComparison.OrdinalIgnoreCase))
  172. {
  173. score++;
  174. if (year.HasValue && series.ProductionYear.HasValue)
  175. {
  176. if (year.Value == series.ProductionYear.Value)
  177. {
  178. score++;
  179. }
  180. else
  181. {
  182. // Regardless of name, return a 0 score if the years don't match
  183. return new Tuple<Series, int>(series, 0);
  184. }
  185. }
  186. }
  187. return new Tuple<Series, int>(series, score);
  188. }
  189. /// <summary>
  190. /// Deletes the left over files.
  191. /// </summary>
  192. /// <param name="path">The path.</param>
  193. /// <param name="extensions">The extensions.</param>
  194. private void DeleteLeftOverFiles(string path, IEnumerable<string> extensions)
  195. {
  196. var eligibleFiles = new DirectoryInfo(path)
  197. .EnumerateFiles("*", SearchOption.AllDirectories)
  198. .Where(i => extensions.Contains(i.Extension, StringComparer.OrdinalIgnoreCase))
  199. .ToList();
  200. foreach (var file in eligibleFiles)
  201. {
  202. try
  203. {
  204. File.Delete(file.FullName);
  205. }
  206. catch (IOException ex)
  207. {
  208. _logger.ErrorException("Error deleting file {0}", ex, file.FullName);
  209. }
  210. }
  211. }
  212. /// <summary>
  213. /// Deletes the empty folders.
  214. /// </summary>
  215. /// <param name="path">The path.</param>
  216. private void DeleteEmptyFolders(string path)
  217. {
  218. try
  219. {
  220. foreach (var d in Directory.EnumerateDirectories(path))
  221. {
  222. DeleteEmptyFolders(d);
  223. }
  224. var entries = Directory.EnumerateFileSystemEntries(path);
  225. if (!entries.Any())
  226. {
  227. try
  228. {
  229. Directory.Delete(path);
  230. }
  231. catch (UnauthorizedAccessException) { }
  232. catch (DirectoryNotFoundException) { }
  233. }
  234. }
  235. catch (UnauthorizedAccessException) { }
  236. }
  237. }
  238. }