EpisodeFileOrganizer.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Entities.TV;
  4. using MediaBrowser.Controller.FileOrganization;
  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 EpisodeFileOrganizer
  22. {
  23. private readonly ILibraryMonitor _libraryMonitor;
  24. private readonly ILibraryManager _libraryManager;
  25. private readonly ILogger _logger;
  26. private readonly IFileSystem _fileSystem;
  27. private readonly IFileOrganizationService _organizationService;
  28. private readonly IServerConfigurationManager _config;
  29. private readonly IProviderManager _providerManager;
  30. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  31. public EpisodeFileOrganizer(IFileOrganizationService organizationService, IServerConfigurationManager config, IFileSystem fileSystem, ILogger logger, ILibraryManager libraryManager, ILibraryMonitor libraryMonitor, IProviderManager providerManager)
  32. {
  33. _organizationService = organizationService;
  34. _config = config;
  35. _fileSystem = fileSystem;
  36. _logger = logger;
  37. _libraryManager = libraryManager;
  38. _libraryMonitor = libraryMonitor;
  39. _providerManager = providerManager;
  40. }
  41. public async Task<FileOrganizationResult> OrganizeEpisodeFile(string path, TvFileOrganizationOptions options, bool overwriteExisting, CancellationToken cancellationToken)
  42. {
  43. _logger.Info("Sorting file {0}", path);
  44. var result = new FileOrganizationResult
  45. {
  46. Date = DateTime.UtcNow,
  47. OriginalPath = path,
  48. OriginalFileName = Path.GetFileName(path),
  49. Type = FileOrganizerType.Episode,
  50. FileSize = new FileInfo(path).Length
  51. };
  52. var seriesName = TVUtils.GetSeriesNameFromEpisodeFile(path);
  53. if (!string.IsNullOrEmpty(seriesName))
  54. {
  55. var season = TVUtils.GetSeasonNumberFromEpisodeFile(path);
  56. result.ExtractedSeasonNumber = season;
  57. if (season.HasValue)
  58. {
  59. // Passing in true will include a few extra regex's
  60. var episode = TVUtils.GetEpisodeNumberFromFile(path, true);
  61. result.ExtractedEpisodeNumber = episode;
  62. if (episode.HasValue)
  63. {
  64. _logger.Debug("Extracted information from {0}. Series name {1}, Season {2}, Episode {3}", path, seriesName, season, episode);
  65. var endingEpisodeNumber = TVUtils.GetEndingEpisodeNumberFromFile(path);
  66. result.ExtractedEndingEpisodeNumber = endingEpisodeNumber;
  67. await OrganizeEpisode(path, seriesName, season.Value, episode.Value, endingEpisodeNumber, options, overwriteExisting, result, cancellationToken).ConfigureAwait(false);
  68. }
  69. else
  70. {
  71. var msg = string.Format("Unable to determine episode number from {0}", path);
  72. result.Status = FileSortingStatus.Failure;
  73. result.StatusMessage = msg;
  74. _logger.Warn(msg);
  75. }
  76. }
  77. else
  78. {
  79. var msg = string.Format("Unable to determine season number from {0}", path);
  80. result.Status = FileSortingStatus.Failure;
  81. result.StatusMessage = msg;
  82. _logger.Warn(msg);
  83. }
  84. }
  85. else
  86. {
  87. var msg = string.Format("Unable to determine series name from {0}", path);
  88. result.Status = FileSortingStatus.Failure;
  89. result.StatusMessage = msg;
  90. _logger.Warn(msg);
  91. }
  92. var previousResult = _organizationService.GetResultBySourcePath(path);
  93. if (previousResult != null)
  94. {
  95. // Don't keep saving the same result over and over if nothing has changed
  96. if (previousResult.Status == result.Status && result.Status != FileSortingStatus.Success)
  97. {
  98. return previousResult;
  99. }
  100. }
  101. await _organizationService.SaveResult(result, CancellationToken.None).ConfigureAwait(false);
  102. return result;
  103. }
  104. public async Task<FileOrganizationResult> OrganizeWithCorrection(EpisodeFileOrganizationRequest request, TvFileOrganizationOptions options, CancellationToken cancellationToken)
  105. {
  106. var result = _organizationService.GetResult(request.ResultId);
  107. var series = (Series)_libraryManager.GetItemById(new Guid(request.SeriesId));
  108. await OrganizeEpisode(result.OriginalPath, series, request.SeasonNumber, request.EpisodeNumber, request.EndingEpisodeNumber, _config.Configuration.TvFileOrganizationOptions, true, result, cancellationToken).ConfigureAwait(false);
  109. await _organizationService.SaveResult(result, CancellationToken.None).ConfigureAwait(false);
  110. return result;
  111. }
  112. private Task OrganizeEpisode(string sourcePath, string seriesName, int seasonNumber, int episodeNumber, int? endingEpiosdeNumber, TvFileOrganizationOptions options, bool overwriteExisting, FileOrganizationResult result, CancellationToken cancellationToken)
  113. {
  114. var series = GetMatchingSeries(seriesName, result);
  115. if (series == null)
  116. {
  117. var msg = string.Format("Unable to find series in library matching name {0}", seriesName);
  118. result.Status = FileSortingStatus.Failure;
  119. result.StatusMessage = msg;
  120. _logger.Warn(msg);
  121. return Task.FromResult(true);
  122. }
  123. return OrganizeEpisode(sourcePath, series, seasonNumber, episodeNumber, endingEpiosdeNumber, options, overwriteExisting, result, cancellationToken);
  124. }
  125. private async Task OrganizeEpisode(string sourcePath, Series series, int seasonNumber, int episodeNumber, int? endingEpiosdeNumber, TvFileOrganizationOptions options, bool overwriteExisting, FileOrganizationResult result, CancellationToken cancellationToken)
  126. {
  127. _logger.Info("Sorting file {0} into series {1}", sourcePath, series.Path);
  128. // Proceed to sort the file
  129. var newPath = await GetNewPath(sourcePath, series, seasonNumber, episodeNumber, endingEpiosdeNumber, options, cancellationToken).ConfigureAwait(false);
  130. if (string.IsNullOrEmpty(newPath))
  131. {
  132. var msg = string.Format("Unable to sort {0} because target path could not be determined.", sourcePath);
  133. result.Status = FileSortingStatus.Failure;
  134. result.StatusMessage = msg;
  135. _logger.Warn(msg);
  136. return;
  137. }
  138. _logger.Info("Sorting file {0} to new path {1}", sourcePath, newPath);
  139. result.TargetPath = newPath;
  140. var fileExists = File.Exists(result.TargetPath);
  141. var otherDuplicatePaths = GetOtherDuplicatePaths(result.TargetPath, series, seasonNumber, episodeNumber, endingEpiosdeNumber);
  142. if (!overwriteExisting && (fileExists || otherDuplicatePaths.Count > 0))
  143. {
  144. result.Status = FileSortingStatus.SkippedExisting;
  145. result.StatusMessage = string.Empty;
  146. result.DuplicatePaths = otherDuplicatePaths;
  147. return;
  148. }
  149. PerformFileSorting(options, result);
  150. if (overwriteExisting)
  151. {
  152. foreach (var path in otherDuplicatePaths)
  153. {
  154. _logger.Debug("Removing duplicate episode {0}", path);
  155. _libraryMonitor.ReportFileSystemChangeBeginning(path);
  156. try
  157. {
  158. File.Delete(path);
  159. }
  160. catch (IOException ex)
  161. {
  162. _logger.ErrorException("Error removing duplicate episode", ex, path);
  163. }
  164. finally
  165. {
  166. _libraryMonitor.ReportFileSystemChangeComplete(path, true);
  167. }
  168. }
  169. }
  170. }
  171. private List<string> GetOtherDuplicatePaths(string targetPath, Series series, int seasonNumber, int episodeNumber, int? endingEpisodeNumber)
  172. {
  173. var episodePaths = series.RecursiveChildren
  174. .OfType<Episode>()
  175. .Where(i =>
  176. {
  177. var locationType = i.LocationType;
  178. // Must be file system based and match exactly
  179. if (locationType != LocationType.Remote &&
  180. locationType != LocationType.Virtual &&
  181. i.ParentIndexNumber.HasValue &&
  182. i.ParentIndexNumber.Value == seasonNumber &&
  183. i.IndexNumber.HasValue &&
  184. i.IndexNumber.Value == episodeNumber)
  185. {
  186. if (endingEpisodeNumber.HasValue || i.IndexNumberEnd.HasValue)
  187. {
  188. return endingEpisodeNumber.HasValue && i.IndexNumberEnd.HasValue &&
  189. endingEpisodeNumber.Value == i.IndexNumberEnd.Value;
  190. }
  191. return true;
  192. }
  193. return false;
  194. })
  195. .Select(i => i.Path)
  196. .ToList();
  197. var folder = Path.GetDirectoryName(targetPath);
  198. var targetFileNameWithoutExtension = Path.GetFileNameWithoutExtension(targetPath);
  199. try
  200. {
  201. var filesOfOtherExtensions = Directory.EnumerateFiles(folder, "*", SearchOption.TopDirectoryOnly)
  202. .Where(i => EntityResolutionHelper.IsVideoFile(i) && string.Equals(Path.GetFileNameWithoutExtension(i), targetFileNameWithoutExtension, StringComparison.OrdinalIgnoreCase));
  203. episodePaths.AddRange(filesOfOtherExtensions);
  204. }
  205. catch (DirectoryNotFoundException)
  206. {
  207. // No big deal. Maybe the season folder doesn't already exist.
  208. }
  209. return episodePaths.Where(i => !string.Equals(i, targetPath, StringComparison.OrdinalIgnoreCase))
  210. .Distinct(StringComparer.OrdinalIgnoreCase)
  211. .ToList();
  212. }
  213. private void PerformFileSorting(TvFileOrganizationOptions options, FileOrganizationResult result)
  214. {
  215. _libraryMonitor.ReportFileSystemChangeBeginning(result.TargetPath);
  216. Directory.CreateDirectory(Path.GetDirectoryName(result.TargetPath));
  217. var copy = File.Exists(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. result.Status = FileSortingStatus.Success;
  229. result.StatusMessage = string.Empty;
  230. }
  231. catch (Exception ex)
  232. {
  233. var errorMsg = string.Format("Failed to move file from {0} to {1}", result.OriginalPath, result.TargetPath);
  234. result.Status = FileSortingStatus.Failure;
  235. result.StatusMessage = errorMsg;
  236. _logger.ErrorException(errorMsg, ex);
  237. return;
  238. }
  239. finally
  240. {
  241. _libraryMonitor.ReportFileSystemChangeComplete(result.TargetPath, true);
  242. }
  243. if (copy)
  244. {
  245. try
  246. {
  247. File.Delete(result.OriginalPath);
  248. }
  249. catch (Exception ex)
  250. {
  251. _logger.ErrorException("Error deleting {0}", ex, result.OriginalPath);
  252. }
  253. }
  254. }
  255. private Series GetMatchingSeries(string seriesName, FileOrganizationResult result)
  256. {
  257. int? yearInName;
  258. var nameWithoutYear = seriesName;
  259. NameParser.ParseName(nameWithoutYear, out nameWithoutYear, out yearInName);
  260. result.ExtractedName = nameWithoutYear;
  261. result.ExtractedYear = yearInName;
  262. return _libraryManager.RootFolder.RecursiveChildren
  263. .OfType<Series>()
  264. .Select(i => NameUtils.GetMatchScore(nameWithoutYear, yearInName, i))
  265. .Where(i => i.Item2 > 0)
  266. .OrderByDescending(i => i.Item2)
  267. .Select(i => i.Item1)
  268. .FirstOrDefault();
  269. }
  270. /// <summary>
  271. /// Gets the new path.
  272. /// </summary>
  273. /// <param name="sourcePath">The source path.</param>
  274. /// <param name="series">The series.</param>
  275. /// <param name="seasonNumber">The season number.</param>
  276. /// <param name="episodeNumber">The episode number.</param>
  277. /// <param name="endingEpisodeNumber">The ending episode number.</param>
  278. /// <param name="options">The options.</param>
  279. /// <returns>System.String.</returns>
  280. private async Task<string> GetNewPath(string sourcePath, Series series, int seasonNumber, int episodeNumber, int? endingEpisodeNumber, TvFileOrganizationOptions options, CancellationToken cancellationToken)
  281. {
  282. var episodeInfo = new EpisodeInfo
  283. {
  284. IndexNumber = episodeNumber,
  285. IndexNumberEnd = endingEpisodeNumber,
  286. MetadataCountryCode = series.GetPreferredMetadataCountryCode(),
  287. MetadataLanguage = series.GetPreferredMetadataLanguage(),
  288. ParentIndexNumber = seasonNumber,
  289. SeriesProviderIds = series.ProviderIds
  290. };
  291. var searchResults = await _providerManager.GetRemoteSearchResults<Episode, EpisodeInfo>(new RemoteSearchQuery<EpisodeInfo>
  292. {
  293. SearchInfo = episodeInfo
  294. }, cancellationToken).ConfigureAwait(false);
  295. var episode = searchResults.FirstOrDefault();
  296. if (episode == null)
  297. {
  298. return null;
  299. }
  300. var newPath = GetSeasonFolderPath(series, seasonNumber, options);
  301. var episodeFileName = GetEpisodeFileName(sourcePath, series.Name, seasonNumber, episodeNumber, endingEpisodeNumber, episode.Name, options);
  302. newPath = Path.Combine(newPath, episodeFileName);
  303. return newPath;
  304. }
  305. /// <summary>
  306. /// Gets the season folder path.
  307. /// </summary>
  308. /// <param name="series">The series.</param>
  309. /// <param name="seasonNumber">The season number.</param>
  310. /// <param name="options">The options.</param>
  311. /// <returns>System.String.</returns>
  312. private string GetSeasonFolderPath(Series series, int seasonNumber, TvFileOrganizationOptions options)
  313. {
  314. // If there's already a season folder, use that
  315. var season = series
  316. .RecursiveChildren
  317. .OfType<Season>()
  318. .FirstOrDefault(i => i.LocationType == LocationType.FileSystem && i.IndexNumber.HasValue && i.IndexNumber.Value == seasonNumber);
  319. if (season != null)
  320. {
  321. return season.Path;
  322. }
  323. var path = series.Path;
  324. if (series.ContainsEpisodesWithoutSeasonFolders)
  325. {
  326. return path;
  327. }
  328. if (seasonNumber == 0)
  329. {
  330. return Path.Combine(path, _fileSystem.GetValidFilename(options.SeasonZeroFolderName));
  331. }
  332. var seasonFolderName = options.SeasonFolderPattern
  333. .Replace("%s", seasonNumber.ToString(_usCulture))
  334. .Replace("%0s", seasonNumber.ToString("00", _usCulture))
  335. .Replace("%00s", seasonNumber.ToString("000", _usCulture));
  336. return Path.Combine(path, _fileSystem.GetValidFilename(seasonFolderName));
  337. }
  338. private string GetEpisodeFileName(string sourcePath, string seriesName, int seasonNumber, int episodeNumber, int? endingEpisodeNumber, string episodeTitle, TvFileOrganizationOptions options)
  339. {
  340. seriesName = _fileSystem.GetValidFilename(seriesName).Trim();
  341. episodeTitle = _fileSystem.GetValidFilename(episodeTitle).Trim();
  342. var sourceExtension = (Path.GetExtension(sourcePath) ?? string.Empty).TrimStart('.');
  343. var pattern = endingEpisodeNumber.HasValue ? options.MultiEpisodeNamePattern : options.EpisodeNamePattern;
  344. var result = pattern.Replace("%sn", seriesName)
  345. .Replace("%s.n", seriesName.Replace(" ", "."))
  346. .Replace("%s_n", seriesName.Replace(" ", "_"))
  347. .Replace("%s", seasonNumber.ToString(_usCulture))
  348. .Replace("%0s", seasonNumber.ToString("00", _usCulture))
  349. .Replace("%00s", seasonNumber.ToString("000", _usCulture))
  350. .Replace("%ext", sourceExtension)
  351. .Replace("%en", episodeTitle)
  352. .Replace("%e.n", episodeTitle.Replace(" ", "."))
  353. .Replace("%e_n", episodeTitle.Replace(" ", "_"));
  354. if (endingEpisodeNumber.HasValue)
  355. {
  356. result = result.Replace("%ed", endingEpisodeNumber.Value.ToString(_usCulture))
  357. .Replace("%0ed", endingEpisodeNumber.Value.ToString("00", _usCulture))
  358. .Replace("%00ed", endingEpisodeNumber.Value.ToString("000", _usCulture));
  359. }
  360. return result.Replace("%e", episodeNumber.ToString(_usCulture))
  361. .Replace("%0e", episodeNumber.ToString("00", _usCulture))
  362. .Replace("%00e", episodeNumber.ToString("000", _usCulture));
  363. }
  364. }
  365. }