TvFileSorter.cs 20 KB

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