TvFileSorter.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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.Threading;
  18. using System.Threading.Tasks;
  19. namespace MediaBrowser.Server.Implementations.FileOrganization
  20. {
  21. public class TvFileSorter
  22. {
  23. private readonly ILibraryManager _libraryManager;
  24. private readonly ILogger _logger;
  25. private readonly IFileSystem _fileSystem;
  26. private readonly IFileOrganizationService _iFileSortingRepository;
  27. private readonly IDirectoryWatchers _directoryWatchers;
  28. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  29. public TvFileSorter(ILibraryManager libraryManager, ILogger logger, IFileSystem fileSystem, IFileOrganizationService iFileSortingRepository, IDirectoryWatchers directoryWatchers)
  30. {
  31. _libraryManager = libraryManager;
  32. _logger = logger;
  33. _fileSystem = fileSystem;
  34. _iFileSortingRepository = iFileSortingRepository;
  35. _directoryWatchers = directoryWatchers;
  36. }
  37. public async Task Sort(TvFileOrganizationOptions options, CancellationToken cancellationToken, IProgress<double> progress)
  38. {
  39. var minFileBytes = options.MinFileSizeMb * 1024 * 1024;
  40. var watchLocations = options.WatchLocations.ToList();
  41. var eligibleFiles = watchLocations.SelectMany(GetFilesToSort)
  42. .OrderBy(_fileSystem.GetCreationTimeUtc)
  43. .Where(i => EntityResolutionHelper.IsVideoFile(i.FullName) && i.Length >= minFileBytes)
  44. .ToList();
  45. progress.Report(10);
  46. var scanLibrary = false;
  47. if (eligibleFiles.Count > 0)
  48. {
  49. var allSeries = _libraryManager.RootFolder
  50. .RecursiveChildren.OfType<Series>()
  51. .Where(i => i.LocationType == LocationType.FileSystem)
  52. .ToList();
  53. var numComplete = 0;
  54. foreach (var file in eligibleFiles)
  55. {
  56. var result = await SortFile(file.FullName, options, allSeries).ConfigureAwait(false);
  57. if (result.Status == FileSortingStatus.Success)
  58. {
  59. scanLibrary = true;
  60. }
  61. numComplete++;
  62. double percent = numComplete;
  63. percent /= eligibleFiles.Count;
  64. progress.Report(10 + (89 * percent));
  65. }
  66. }
  67. cancellationToken.ThrowIfCancellationRequested();
  68. progress.Report(99);
  69. if (!options.EnableTrialMode)
  70. {
  71. foreach (var path in watchLocations)
  72. {
  73. if (options.LeftOverFileExtensionsToDelete.Length > 0)
  74. {
  75. DeleteLeftOverFiles(path, options.LeftOverFileExtensionsToDelete);
  76. }
  77. if (options.DeleteEmptyFolders)
  78. {
  79. DeleteEmptyFolders(path);
  80. }
  81. }
  82. }
  83. if (scanLibrary)
  84. {
  85. await _libraryManager.ValidateMediaLibrary(new Progress<double>(), CancellationToken.None)
  86. .ConfigureAwait(false);
  87. }
  88. progress.Report(100);
  89. }
  90. /// <summary>
  91. /// Gets the eligible files.
  92. /// </summary>
  93. /// <param name="path">The path.</param>
  94. /// <returns>IEnumerable{FileInfo}.</returns>
  95. private IEnumerable<FileInfo> GetFilesToSort(string path)
  96. {
  97. try
  98. {
  99. return new DirectoryInfo(path)
  100. .EnumerateFiles("*", SearchOption.AllDirectories)
  101. .ToList();
  102. }
  103. catch (IOException ex)
  104. {
  105. _logger.ErrorException("Error getting files from {0}", ex, path);
  106. return new List<FileInfo>();
  107. }
  108. }
  109. /// <summary>
  110. /// Sorts the file.
  111. /// </summary>
  112. /// <param name="path">The path.</param>
  113. /// <param name="options">The options.</param>
  114. /// <param name="allSeries">All series.</param>
  115. private async Task<FileOrganizationResult> SortFile(string path, TvFileOrganizationOptions options, IEnumerable<Series> allSeries)
  116. {
  117. _logger.Info("Sorting file {0}", path);
  118. var result = new FileOrganizationResult
  119. {
  120. Date = DateTime.UtcNow,
  121. OriginalPath = path
  122. };
  123. var seriesName = TVUtils.GetSeriesNameFromEpisodeFile(path);
  124. if (!string.IsNullOrEmpty(seriesName))
  125. {
  126. var season = TVUtils.GetSeasonNumberFromEpisodeFile(path);
  127. if (season.HasValue)
  128. {
  129. // Passing in true will include a few extra regex's
  130. var episode = TVUtils.GetEpisodeNumberFromFile(path, true);
  131. if (episode.HasValue)
  132. {
  133. _logger.Debug("Extracted information from {0}. Series name {1}, Season {2}, Episode {3}", path, seriesName, season, episode);
  134. SortFile(path, seriesName, season.Value, episode.Value, options, allSeries, result);
  135. }
  136. else
  137. {
  138. var msg = string.Format("Unable to determine episode number from {0}", path);
  139. result.Status = FileSortingStatus.Failure;
  140. result.ErrorMessage = msg;
  141. _logger.Warn(msg);
  142. }
  143. }
  144. else
  145. {
  146. var msg = string.Format("Unable to determine season number from {0}", path);
  147. result.Status = FileSortingStatus.Failure;
  148. result.ErrorMessage = msg;
  149. _logger.Warn(msg);
  150. }
  151. }
  152. else
  153. {
  154. var msg = string.Format("Unable to determine series name from {0}", path);
  155. result.Status = FileSortingStatus.Failure;
  156. result.ErrorMessage = msg;
  157. _logger.Warn(msg);
  158. }
  159. await LogResult(result).ConfigureAwait(false);
  160. return result;
  161. }
  162. /// <summary>
  163. /// Sorts the file.
  164. /// </summary>
  165. /// <param name="path">The path.</param>
  166. /// <param name="seriesName">Name of the series.</param>
  167. /// <param name="seasonNumber">The season number.</param>
  168. /// <param name="episodeNumber">The episode number.</param>
  169. /// <param name="options">The options.</param>
  170. /// <param name="allSeries">All series.</param>
  171. /// <param name="result">The result.</param>
  172. private void SortFile(string path, string seriesName, int seasonNumber, int episodeNumber, TvFileOrganizationOptions options, IEnumerable<Series> allSeries, FileOrganizationResult result)
  173. {
  174. var series = GetMatchingSeries(seriesName, allSeries);
  175. if (series == null)
  176. {
  177. var msg = string.Format("Unable to find series in library matching name {0}", seriesName);
  178. result.Status = FileSortingStatus.Failure;
  179. result.ErrorMessage = msg;
  180. _logger.Warn(msg);
  181. return;
  182. }
  183. _logger.Info("Sorting file {0} into series {1}", path, series.Path);
  184. // Proceed to sort the file
  185. var newPath = GetNewPath(path, series, seasonNumber, episodeNumber, options);
  186. if (string.IsNullOrEmpty(newPath))
  187. {
  188. var msg = string.Format("Unable to sort {0} because target path could not be determined.", path);
  189. result.Status = FileSortingStatus.Failure;
  190. result.ErrorMessage = msg;
  191. _logger.Warn(msg);
  192. return;
  193. }
  194. _logger.Info("Sorting file {0} to new path {1}", path, newPath);
  195. result.TargetPath = newPath;
  196. if (options.EnableTrialMode)
  197. {
  198. result.Status = FileSortingStatus.SkippedTrial;
  199. return;
  200. }
  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.ErrorMessage = 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="options">The options.</param>
  270. /// <returns>System.String.</returns>
  271. private string GetNewPath(string sourcePath, Series series, int seasonNumber, int episodeNumber, TvFileOrganizationOptions options)
  272. {
  273. var currentEpisodes = series.RecursiveChildren.OfType<Episode>()
  274. .Where(i => i.IndexNumber.HasValue && i.IndexNumber.Value == episodeNumber && i.ParentIndexNumber.HasValue && i.ParentIndexNumber.Value == seasonNumber)
  275. .ToList();
  276. if (currentEpisodes.Count == 0)
  277. {
  278. return null;
  279. }
  280. var newPath = currentEpisodes
  281. .Where(i => i.LocationType == LocationType.FileSystem)
  282. .Select(i => i.Path)
  283. .FirstOrDefault();
  284. if (string.IsNullOrEmpty(newPath))
  285. {
  286. newPath = GetSeasonFolderPath(series, seasonNumber, options);
  287. var episode = currentEpisodes.First();
  288. var episodeFileName = GetEpisodeFileName(sourcePath, series.Name, seasonNumber, episodeNumber, episode.Name, options);
  289. newPath = Path.Combine(newPath, episodeFileName);
  290. }
  291. return newPath;
  292. }
  293. private string GetEpisodeFileName(string sourcePath, string seriesName, int seasonNumber, int episodeNumber, string episodeTitle, TvFileOrganizationOptions options)
  294. {
  295. seriesName = _fileSystem.GetValidFilename(seriesName);
  296. episodeTitle = _fileSystem.GetValidFilename(episodeTitle);
  297. var sourceExtension = (Path.GetExtension(sourcePath) ?? string.Empty).TrimStart('.');
  298. return options.EpisodeNamePattern.Replace("%sn", seriesName)
  299. .Replace("%s.n", seriesName.Replace(" ", "."))
  300. .Replace("%s_n", seriesName.Replace(" ", "_"))
  301. .Replace("%s", seasonNumber.ToString(UsCulture))
  302. .Replace("%0s", seasonNumber.ToString("00", UsCulture))
  303. .Replace("%00s", seasonNumber.ToString("000", UsCulture))
  304. .Replace("%ext", sourceExtension)
  305. .Replace("%en", episodeTitle)
  306. .Replace("%e.n", episodeTitle.Replace(" ", "."))
  307. .Replace("%e_n", episodeTitle.Replace(" ", "_"))
  308. .Replace("%e", episodeNumber.ToString(UsCulture))
  309. .Replace("%0e", episodeNumber.ToString("00", UsCulture))
  310. .Replace("%00e", episodeNumber.ToString("000", UsCulture));
  311. }
  312. /// <summary>
  313. /// Gets the season folder path.
  314. /// </summary>
  315. /// <param name="series">The series.</param>
  316. /// <param name="seasonNumber">The season number.</param>
  317. /// <param name="options">The options.</param>
  318. /// <returns>System.String.</returns>
  319. private string GetSeasonFolderPath(Series series, int seasonNumber, TvFileOrganizationOptions options)
  320. {
  321. // If there's already a season folder, use that
  322. var season = series
  323. .RecursiveChildren
  324. .OfType<Season>()
  325. .FirstOrDefault(i => i.LocationType == LocationType.FileSystem && i.IndexNumber.HasValue && i.IndexNumber.Value == seasonNumber);
  326. if (season != null)
  327. {
  328. return season.Path;
  329. }
  330. var path = series.Path;
  331. if (series.ContainsEpisodesWithoutSeasonFolders)
  332. {
  333. return path;
  334. }
  335. if (seasonNumber == 0)
  336. {
  337. return Path.Combine(path, _fileSystem.GetValidFilename(options.SeasonZeroFolderName));
  338. }
  339. var seasonFolderName = options.SeasonFolderPattern
  340. .Replace("%s", seasonNumber.ToString(UsCulture))
  341. .Replace("%0s", seasonNumber.ToString("00", UsCulture))
  342. .Replace("%00s", seasonNumber.ToString("000", UsCulture));
  343. return Path.Combine(path, _fileSystem.GetValidFilename(seasonFolderName));
  344. }
  345. /// <summary>
  346. /// Gets the matching series.
  347. /// </summary>
  348. /// <param name="seriesName">Name of the series.</param>
  349. /// <param name="allSeries">All series.</param>
  350. /// <returns>Series.</returns>
  351. private Series GetMatchingSeries(string seriesName, IEnumerable<Series> allSeries)
  352. {
  353. int? yearInName;
  354. var nameWithoutYear = seriesName;
  355. NameParser.ParseName(nameWithoutYear, out nameWithoutYear, out yearInName);
  356. return allSeries.Select(i => GetMatchScore(nameWithoutYear, yearInName, i))
  357. .Where(i => i.Item2 > 0)
  358. .OrderByDescending(i => i.Item2)
  359. .Select(i => i.Item1)
  360. .FirstOrDefault();
  361. }
  362. private Tuple<Series, int> GetMatchScore(string sortedName, int? year, Series series)
  363. {
  364. var score = 0;
  365. // TODO: Improve this - should ignore spaces, periods, underscores, most likely all symbols and
  366. // possibly remove sorting words like "the", "and", etc.
  367. if (string.Equals(sortedName, series.Name, StringComparison.OrdinalIgnoreCase))
  368. {
  369. score++;
  370. if (year.HasValue && series.ProductionYear.HasValue)
  371. {
  372. if (year.Value == series.ProductionYear.Value)
  373. {
  374. score++;
  375. }
  376. else
  377. {
  378. // Regardless of name, return a 0 score if the years don't match
  379. return new Tuple<Series, int>(series, 0);
  380. }
  381. }
  382. }
  383. return new Tuple<Series, int>(series, score);
  384. }
  385. /// <summary>
  386. /// Deletes the left over files.
  387. /// </summary>
  388. /// <param name="path">The path.</param>
  389. /// <param name="extensions">The extensions.</param>
  390. private void DeleteLeftOverFiles(string path, IEnumerable<string> extensions)
  391. {
  392. var eligibleFiles = new DirectoryInfo(path)
  393. .EnumerateFiles("*", SearchOption.AllDirectories)
  394. .Where(i => extensions.Contains(i.Extension, StringComparer.OrdinalIgnoreCase))
  395. .ToList();
  396. foreach (var file in eligibleFiles)
  397. {
  398. try
  399. {
  400. File.Delete(file.FullName);
  401. }
  402. catch (IOException ex)
  403. {
  404. _logger.ErrorException("Error deleting file {0}", ex, file.FullName);
  405. }
  406. }
  407. }
  408. /// <summary>
  409. /// Deletes the empty folders.
  410. /// </summary>
  411. /// <param name="path">The path.</param>
  412. private void DeleteEmptyFolders(string path)
  413. {
  414. try
  415. {
  416. foreach (var d in Directory.EnumerateDirectories(path))
  417. {
  418. DeleteEmptyFolders(d);
  419. }
  420. var entries = Directory.EnumerateFileSystemEntries(path);
  421. if (!entries.Any())
  422. {
  423. try
  424. {
  425. Directory.Delete(path);
  426. }
  427. catch (UnauthorizedAccessException) { }
  428. catch (DirectoryNotFoundException) { }
  429. }
  430. }
  431. catch (UnauthorizedAccessException) { }
  432. }
  433. }
  434. }