TvFileSorter.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Controller.Entities.TV;
  3. using MediaBrowser.Controller.Library;
  4. using MediaBrowser.Controller.Persistence;
  5. using MediaBrowser.Controller.Providers;
  6. using MediaBrowser.Controller.Resolvers;
  7. using MediaBrowser.Model.Configuration;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Model.FileSorting;
  10. using MediaBrowser.Model.Logging;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Globalization;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. namespace MediaBrowser.Server.Implementations.FileSorting
  19. {
  20. public class TvFileSorter
  21. {
  22. private readonly ILibraryManager _libraryManager;
  23. private readonly ILogger _logger;
  24. private readonly IFileSystem _fileSystem;
  25. private readonly IFileSortingRepository _iFileSortingRepository;
  26. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  27. public TvFileSorter(ILibraryManager libraryManager, ILogger logger, IFileSystem fileSystem, IFileSortingRepository iFileSortingRepository)
  28. {
  29. _libraryManager = libraryManager;
  30. _logger = logger;
  31. _fileSystem = fileSystem;
  32. _iFileSortingRepository = iFileSortingRepository;
  33. }
  34. public async Task Sort(TvFileSortingOptions options, CancellationToken cancellationToken, IProgress<double> progress)
  35. {
  36. var minFileBytes = options.MinFileSizeMb * 1024 * 1024;
  37. var watchLocations = options.WatchLocations.ToList();
  38. var eligibleFiles = watchLocations.SelectMany(GetFilesToSort)
  39. .OrderBy(_fileSystem.GetCreationTimeUtc)
  40. .Where(i => EntityResolutionHelper.IsVideoFile(i.FullName) && i.Length >= minFileBytes)
  41. .ToList();
  42. progress.Report(10);
  43. if (eligibleFiles.Count > 0)
  44. {
  45. var allSeries = _libraryManager.RootFolder
  46. .RecursiveChildren.OfType<Series>()
  47. .Where(i => i.LocationType == LocationType.FileSystem)
  48. .ToList();
  49. var numComplete = 0;
  50. foreach (var file in eligibleFiles)
  51. {
  52. await SortFile(file.FullName, options, allSeries).ConfigureAwait(false);
  53. numComplete++;
  54. double percent = numComplete;
  55. percent /= eligibleFiles.Count;
  56. progress.Report(10 + (89 * percent));
  57. }
  58. }
  59. cancellationToken.ThrowIfCancellationRequested();
  60. progress.Report(99);
  61. if (!options.EnableTrialMode)
  62. {
  63. foreach (var path in watchLocations)
  64. {
  65. if (options.LeftOverFileExtensionsToDelete.Length > 0)
  66. {
  67. DeleteLeftOverFiles(path, options.LeftOverFileExtensionsToDelete);
  68. }
  69. if (options.DeleteEmptyFolders)
  70. {
  71. DeleteEmptyFolders(path);
  72. }
  73. }
  74. }
  75. progress.Report(100);
  76. }
  77. /// <summary>
  78. /// Gets the eligible files.
  79. /// </summary>
  80. /// <param name="path">The path.</param>
  81. /// <returns>IEnumerable{FileInfo}.</returns>
  82. private IEnumerable<FileInfo> GetFilesToSort(string path)
  83. {
  84. try
  85. {
  86. return new DirectoryInfo(path)
  87. .EnumerateFiles("*", SearchOption.AllDirectories)
  88. .ToList();
  89. }
  90. catch (IOException ex)
  91. {
  92. _logger.ErrorException("Error getting files from {0}", ex, path);
  93. return new List<FileInfo>();
  94. }
  95. }
  96. /// <summary>
  97. /// Sorts the file.
  98. /// </summary>
  99. /// <param name="path">The path.</param>
  100. /// <param name="options">The options.</param>
  101. /// <param name="allSeries">All series.</param>
  102. private Task SortFile(string path, TvFileSortingOptions options, IEnumerable<Series> allSeries)
  103. {
  104. _logger.Info("Sorting file {0}", path);
  105. var result = new FileSortingResult
  106. {
  107. Date = DateTime.UtcNow,
  108. OriginalPath = path
  109. };
  110. var seriesName = TVUtils.GetSeriesNameFromEpisodeFile(path);
  111. if (!string.IsNullOrEmpty(seriesName))
  112. {
  113. var season = TVUtils.GetSeasonNumberFromEpisodeFile(path);
  114. if (season.HasValue)
  115. {
  116. // Passing in true will include a few extra regex's
  117. var episode = TVUtils.GetEpisodeNumberFromFile(path, true);
  118. if (episode.HasValue)
  119. {
  120. _logger.Debug("Extracted information from {0}. Series name {1}, Season {2}, Episode {3}", path, seriesName, season, episode);
  121. SortFile(path, seriesName, season.Value, episode.Value, options, allSeries, result);
  122. }
  123. else
  124. {
  125. var msg = string.Format("Unable to determine episode number from {0}", path);
  126. result.Status = FileSortingStatus.Failure;
  127. result.ErrorMessage = msg;
  128. _logger.Warn(msg);
  129. }
  130. }
  131. else
  132. {
  133. var msg = string.Format("Unable to determine season number from {0}", path);
  134. result.Status = FileSortingStatus.Failure;
  135. result.ErrorMessage = msg;
  136. _logger.Warn(msg);
  137. }
  138. }
  139. else
  140. {
  141. var msg = string.Format("Unable to determine series name from {0}", path);
  142. result.Status = FileSortingStatus.Failure;
  143. result.ErrorMessage = msg;
  144. _logger.Warn(msg);
  145. }
  146. return LogResult(result);
  147. }
  148. /// <summary>
  149. /// Sorts the file.
  150. /// </summary>
  151. /// <param name="path">The path.</param>
  152. /// <param name="seriesName">Name of the series.</param>
  153. /// <param name="seasonNumber">The season number.</param>
  154. /// <param name="episodeNumber">The episode number.</param>
  155. /// <param name="options">The options.</param>
  156. /// <param name="allSeries">All series.</param>
  157. /// <param name="result">The result.</param>
  158. private void SortFile(string path, string seriesName, int seasonNumber, int episodeNumber, TvFileSortingOptions options, IEnumerable<Series> allSeries, FileSortingResult result)
  159. {
  160. var series = GetMatchingSeries(seriesName, allSeries);
  161. if (series == null)
  162. {
  163. var msg = string.Format("Unable to find series in library matching name {0}", seriesName);
  164. result.Status = FileSortingStatus.Failure;
  165. result.ErrorMessage = msg;
  166. _logger.Warn(msg);
  167. return;
  168. }
  169. _logger.Info("Sorting file {0} into series {1}", path, series.Path);
  170. // Proceed to sort the file
  171. var newPath = GetNewPath(series, seasonNumber, episodeNumber, options);
  172. if (string.IsNullOrEmpty(newPath))
  173. {
  174. var msg = string.Format("Unable to sort {0} because target path could not be determined.", path);
  175. result.Status = FileSortingStatus.Failure;
  176. result.ErrorMessage = msg;
  177. _logger.Warn(msg);
  178. return;
  179. }
  180. _logger.Info("Sorting file {0} to new path {1}", path, newPath);
  181. result.TargetPath = newPath;
  182. if (options.EnableTrialMode)
  183. {
  184. result.Status = FileSortingStatus.SkippedTrial;
  185. return;
  186. }
  187. var targetExists = File.Exists(result.TargetPath);
  188. if (!options.OverwriteExistingEpisodes && targetExists)
  189. {
  190. result.Status = FileSortingStatus.SkippedExisting;
  191. return;
  192. }
  193. PerformFileSorting(options, result, targetExists);
  194. }
  195. /// <summary>
  196. /// Performs the file sorting.
  197. /// </summary>
  198. /// <param name="options">The options.</param>
  199. /// <param name="result">The result.</param>
  200. /// <param name="copy">if set to <c>true</c> [copy].</param>
  201. private void PerformFileSorting(TvFileSortingOptions options, FileSortingResult result, bool copy)
  202. {
  203. try
  204. {
  205. if (copy)
  206. {
  207. File.Copy(result.OriginalPath, result.TargetPath, true);
  208. }
  209. else
  210. {
  211. File.Move(result.OriginalPath, result.TargetPath);
  212. }
  213. }
  214. catch (Exception ex)
  215. {
  216. var errorMsg = string.Format("Failed to move file from {0} to {1}", result.OriginalPath, result.TargetPath);
  217. result.Status = FileSortingStatus.Failure;
  218. result.ErrorMessage = errorMsg;
  219. _logger.ErrorException(errorMsg, ex);
  220. return;
  221. }
  222. if (copy)
  223. {
  224. try
  225. {
  226. File.Delete(result.OriginalPath);
  227. }
  228. catch (Exception ex)
  229. {
  230. _logger.ErrorException("Error deleting {0}", ex, result.OriginalPath);
  231. }
  232. }
  233. }
  234. /// <summary>
  235. /// Logs the result.
  236. /// </summary>
  237. /// <param name="result">The result.</param>
  238. /// <returns>Task.</returns>
  239. private Task LogResult(FileSortingResult result)
  240. {
  241. return _iFileSortingRepository.SaveResult(result, CancellationToken.None);
  242. }
  243. /// <summary>
  244. /// Gets the new path.
  245. /// </summary>
  246. /// <param name="series">The series.</param>
  247. /// <param name="seasonNumber">The season number.</param>
  248. /// <param name="episodeNumber">The episode number.</param>
  249. /// <param name="options">The options.</param>
  250. /// <returns>System.String.</returns>
  251. private string GetNewPath(Series series, int seasonNumber, int episodeNumber, TvFileSortingOptions options)
  252. {
  253. var currentEpisodes = series.RecursiveChildren.OfType<Episode>()
  254. .Where(i => i.IndexNumber.HasValue && i.IndexNumber.Value == episodeNumber && i.ParentIndexNumber.HasValue && i.ParentIndexNumber.Value == seasonNumber)
  255. .ToList();
  256. if (currentEpisodes.Count == 0)
  257. {
  258. return null;
  259. }
  260. var newPath = currentEpisodes
  261. .Where(i => i.LocationType == LocationType.FileSystem)
  262. .Select(i => i.Path)
  263. .FirstOrDefault();
  264. if (string.IsNullOrEmpty(newPath))
  265. {
  266. newPath = GetSeasonFolderPath(series, seasonNumber, options);
  267. var episode = currentEpisodes.First();
  268. var episodeFileName = string.Format("{0} - {1}x{2} - {3}",
  269. _fileSystem.GetValidFilename(series.Name),
  270. seasonNumber.ToString(UsCulture),
  271. episodeNumber.ToString("00", UsCulture),
  272. _fileSystem.GetValidFilename(episode.Name)
  273. );
  274. newPath = Path.Combine(newPath, episodeFileName);
  275. }
  276. return newPath;
  277. }
  278. /// <summary>
  279. /// Gets the season folder path.
  280. /// </summary>
  281. /// <param name="series">The series.</param>
  282. /// <param name="seasonNumber">The season number.</param>
  283. /// <param name="options">The options.</param>
  284. /// <returns>System.String.</returns>
  285. private string GetSeasonFolderPath(Series series, int seasonNumber, TvFileSortingOptions options)
  286. {
  287. // If there's already a season folder, use that
  288. var season = series
  289. .RecursiveChildren
  290. .OfType<Season>()
  291. .FirstOrDefault(i => i.LocationType == LocationType.FileSystem && i.IndexNumber.HasValue && i.IndexNumber.Value == seasonNumber);
  292. if (season != null)
  293. {
  294. return season.Path;
  295. }
  296. var path = series.Path;
  297. if (series.ContainsEpisodesWithoutSeasonFolders)
  298. {
  299. return path;
  300. }
  301. if (seasonNumber == 0)
  302. {
  303. return Path.Combine(path, _fileSystem.GetValidFilename(options.SeasonZeroFolderName));
  304. }
  305. var seasonFolderName = options.SeasonFolderPattern
  306. .Replace("%s", seasonNumber.ToString(UsCulture))
  307. .Replace("%0s", seasonNumber.ToString("00", UsCulture))
  308. .Replace("%00s", seasonNumber.ToString("000", UsCulture));
  309. return Path.Combine(path, _fileSystem.GetValidFilename(seasonFolderName));
  310. }
  311. /// <summary>
  312. /// Gets the matching series.
  313. /// </summary>
  314. /// <param name="seriesName">Name of the series.</param>
  315. /// <param name="allSeries">All series.</param>
  316. /// <returns>Series.</returns>
  317. private Series GetMatchingSeries(string seriesName, IEnumerable<Series> allSeries)
  318. {
  319. int? yearInName;
  320. var nameWithoutYear = seriesName;
  321. NameParser.ParseName(nameWithoutYear, out nameWithoutYear, out yearInName);
  322. return allSeries.Select(i => GetMatchScore(nameWithoutYear, yearInName, i))
  323. .Where(i => i.Item2 > 0)
  324. .OrderByDescending(i => i.Item2)
  325. .Select(i => i.Item1)
  326. .FirstOrDefault();
  327. }
  328. private Tuple<Series, int> GetMatchScore(string sortedName, int? year, Series series)
  329. {
  330. var score = 0;
  331. // TODO: Improve this
  332. if (string.Equals(sortedName, series.Name, StringComparison.OrdinalIgnoreCase))
  333. {
  334. score++;
  335. if (year.HasValue && series.ProductionYear.HasValue)
  336. {
  337. if (year.Value == series.ProductionYear.Value)
  338. {
  339. score++;
  340. }
  341. else
  342. {
  343. // Regardless of name, return a 0 score if the years don't match
  344. return new Tuple<Series, int>(series, 0);
  345. }
  346. }
  347. }
  348. return new Tuple<Series, int>(series, score);
  349. }
  350. /// <summary>
  351. /// Deletes the left over files.
  352. /// </summary>
  353. /// <param name="path">The path.</param>
  354. /// <param name="extensions">The extensions.</param>
  355. private void DeleteLeftOverFiles(string path, IEnumerable<string> extensions)
  356. {
  357. var eligibleFiles = new DirectoryInfo(path)
  358. .EnumerateFiles("*", SearchOption.AllDirectories)
  359. .Where(i => extensions.Contains(i.Extension, StringComparer.OrdinalIgnoreCase))
  360. .ToList();
  361. foreach (var file in eligibleFiles)
  362. {
  363. try
  364. {
  365. File.Delete(file.FullName);
  366. }
  367. catch (IOException ex)
  368. {
  369. _logger.ErrorException("Error deleting file {0}", ex, file.FullName);
  370. }
  371. }
  372. }
  373. /// <summary>
  374. /// Deletes the empty folders.
  375. /// </summary>
  376. /// <param name="path">The path.</param>
  377. private void DeleteEmptyFolders(string path)
  378. {
  379. try
  380. {
  381. foreach (var d in Directory.EnumerateDirectories(path))
  382. {
  383. DeleteEmptyFolders(d);
  384. }
  385. var entries = Directory.EnumerateFileSystemEntries(path);
  386. if (!entries.Any())
  387. {
  388. try
  389. {
  390. Directory.Delete(path);
  391. }
  392. catch (UnauthorizedAccessException) { }
  393. catch (DirectoryNotFoundException) { }
  394. }
  395. }
  396. catch (UnauthorizedAccessException) { }
  397. }
  398. }
  399. }