TvFileSorter.cs 21 KB

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