EpisodeFileOrganizer.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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)
  143. {
  144. if (options.CopyOriginalFile && fileExists && IsSameEpisode(sourcePath, newPath))
  145. {
  146. _logger.Info("File {0} already copied to new path {1}, stopping organization", sourcePath, newPath);
  147. result.Status = FileSortingStatus.SkippedExisting;
  148. result.StatusMessage = string.Empty;
  149. return;
  150. }
  151. if (fileExists || otherDuplicatePaths.Count > 0)
  152. {
  153. result.Status = FileSortingStatus.SkippedExisting;
  154. result.StatusMessage = string.Empty;
  155. result.DuplicatePaths = otherDuplicatePaths;
  156. return;
  157. }
  158. }
  159. PerformFileSorting(options, result);
  160. if (overwriteExisting)
  161. {
  162. foreach (var path in otherDuplicatePaths)
  163. {
  164. _logger.Debug("Removing duplicate episode {0}", path);
  165. _libraryMonitor.ReportFileSystemChangeBeginning(path);
  166. try
  167. {
  168. File.Delete(path);
  169. }
  170. catch (IOException ex)
  171. {
  172. _logger.ErrorException("Error removing duplicate episode", ex, path);
  173. }
  174. finally
  175. {
  176. _libraryMonitor.ReportFileSystemChangeComplete(path, true);
  177. }
  178. }
  179. }
  180. }
  181. private List<string> GetOtherDuplicatePaths(string targetPath, Series series, int seasonNumber, int episodeNumber, int? endingEpisodeNumber)
  182. {
  183. var episodePaths = series.RecursiveChildren
  184. .OfType<Episode>()
  185. .Where(i =>
  186. {
  187. var locationType = i.LocationType;
  188. // Must be file system based and match exactly
  189. if (locationType != LocationType.Remote &&
  190. locationType != LocationType.Virtual &&
  191. i.ParentIndexNumber.HasValue &&
  192. i.ParentIndexNumber.Value == seasonNumber &&
  193. i.IndexNumber.HasValue &&
  194. i.IndexNumber.Value == episodeNumber)
  195. {
  196. if (endingEpisodeNumber.HasValue || i.IndexNumberEnd.HasValue)
  197. {
  198. return endingEpisodeNumber.HasValue && i.IndexNumberEnd.HasValue &&
  199. endingEpisodeNumber.Value == i.IndexNumberEnd.Value;
  200. }
  201. return true;
  202. }
  203. return false;
  204. })
  205. .Select(i => i.Path)
  206. .ToList();
  207. var folder = Path.GetDirectoryName(targetPath);
  208. var targetFileNameWithoutExtension = Path.GetFileNameWithoutExtension(targetPath);
  209. try
  210. {
  211. var filesOfOtherExtensions = Directory.EnumerateFiles(folder, "*", SearchOption.TopDirectoryOnly)
  212. .Where(i => EntityResolutionHelper.IsVideoFile(i) && string.Equals(Path.GetFileNameWithoutExtension(i), targetFileNameWithoutExtension, StringComparison.OrdinalIgnoreCase));
  213. episodePaths.AddRange(filesOfOtherExtensions);
  214. }
  215. catch (DirectoryNotFoundException)
  216. {
  217. // No big deal. Maybe the season folder doesn't already exist.
  218. }
  219. return episodePaths.Where(i => !string.Equals(i, targetPath, StringComparison.OrdinalIgnoreCase))
  220. .Distinct(StringComparer.OrdinalIgnoreCase)
  221. .ToList();
  222. }
  223. private void PerformFileSorting(TvFileOrganizationOptions options, FileOrganizationResult result)
  224. {
  225. _libraryMonitor.ReportFileSystemChangeBeginning(result.TargetPath);
  226. Directory.CreateDirectory(Path.GetDirectoryName(result.TargetPath));
  227. var copy = File.Exists(result.TargetPath);
  228. try
  229. {
  230. if (copy || options.CopyOriginalFile)
  231. {
  232. File.Copy(result.OriginalPath, result.TargetPath, true);
  233. }
  234. else
  235. {
  236. File.Move(result.OriginalPath, result.TargetPath);
  237. }
  238. result.Status = FileSortingStatus.Success;
  239. result.StatusMessage = string.Empty;
  240. }
  241. catch (Exception ex)
  242. {
  243. var errorMsg = string.Format("Failed to move file from {0} to {1}", result.OriginalPath, result.TargetPath);
  244. result.Status = FileSortingStatus.Failure;
  245. result.StatusMessage = errorMsg;
  246. _logger.ErrorException(errorMsg, ex);
  247. return;
  248. }
  249. finally
  250. {
  251. _libraryMonitor.ReportFileSystemChangeComplete(result.TargetPath, true);
  252. }
  253. if (copy && !options.CopyOriginalFile)
  254. {
  255. try
  256. {
  257. File.Delete(result.OriginalPath);
  258. }
  259. catch (Exception ex)
  260. {
  261. _logger.ErrorException("Error deleting {0}", ex, result.OriginalPath);
  262. }
  263. }
  264. }
  265. private Series GetMatchingSeries(string seriesName, FileOrganizationResult result)
  266. {
  267. int? yearInName;
  268. var nameWithoutYear = seriesName;
  269. NameParser.ParseName(nameWithoutYear, out nameWithoutYear, out yearInName);
  270. result.ExtractedName = nameWithoutYear;
  271. result.ExtractedYear = yearInName;
  272. return _libraryManager.RootFolder.RecursiveChildren
  273. .OfType<Series>()
  274. .Select(i => NameUtils.GetMatchScore(nameWithoutYear, yearInName, i))
  275. .Where(i => i.Item2 > 0)
  276. .OrderByDescending(i => i.Item2)
  277. .Select(i => i.Item1)
  278. .FirstOrDefault();
  279. }
  280. /// <summary>
  281. /// Gets the new path.
  282. /// </summary>
  283. /// <param name="sourcePath">The source path.</param>
  284. /// <param name="series">The series.</param>
  285. /// <param name="seasonNumber">The season number.</param>
  286. /// <param name="episodeNumber">The episode number.</param>
  287. /// <param name="endingEpisodeNumber">The ending episode number.</param>
  288. /// <param name="options">The options.</param>
  289. /// <returns>System.String.</returns>
  290. private async Task<string> GetNewPath(string sourcePath, Series series, int seasonNumber, int episodeNumber, int? endingEpisodeNumber, TvFileOrganizationOptions options, CancellationToken cancellationToken)
  291. {
  292. var episodeInfo = new EpisodeInfo
  293. {
  294. IndexNumber = episodeNumber,
  295. IndexNumberEnd = endingEpisodeNumber,
  296. MetadataCountryCode = series.GetPreferredMetadataCountryCode(),
  297. MetadataLanguage = series.GetPreferredMetadataLanguage(),
  298. ParentIndexNumber = seasonNumber,
  299. SeriesProviderIds = series.ProviderIds
  300. };
  301. var searchResults = await _providerManager.GetRemoteSearchResults<Episode, EpisodeInfo>(new RemoteSearchQuery<EpisodeInfo>
  302. {
  303. SearchInfo = episodeInfo
  304. }, cancellationToken).ConfigureAwait(false);
  305. var episode = searchResults.FirstOrDefault();
  306. if (episode == null)
  307. {
  308. return null;
  309. }
  310. var newPath = GetSeasonFolderPath(series, seasonNumber, options);
  311. var episodeFileName = GetEpisodeFileName(sourcePath, series.Name, seasonNumber, episodeNumber, endingEpisodeNumber, episode.Name, options);
  312. newPath = Path.Combine(newPath, episodeFileName);
  313. return newPath;
  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. private string GetEpisodeFileName(string sourcePath, string seriesName, int seasonNumber, int episodeNumber, int? endingEpisodeNumber, string episodeTitle, TvFileOrganizationOptions options)
  349. {
  350. seriesName = _fileSystem.GetValidFilename(seriesName).Trim();
  351. episodeTitle = _fileSystem.GetValidFilename(episodeTitle).Trim();
  352. var sourceExtension = (Path.GetExtension(sourcePath) ?? string.Empty).TrimStart('.');
  353. var pattern = endingEpisodeNumber.HasValue ? options.MultiEpisodeNamePattern : options.EpisodeNamePattern;
  354. var result = pattern.Replace("%sn", seriesName)
  355. .Replace("%s.n", seriesName.Replace(" ", "."))
  356. .Replace("%s_n", seriesName.Replace(" ", "_"))
  357. .Replace("%s", seasonNumber.ToString(_usCulture))
  358. .Replace("%0s", seasonNumber.ToString("00", _usCulture))
  359. .Replace("%00s", seasonNumber.ToString("000", _usCulture))
  360. .Replace("%ext", sourceExtension)
  361. .Replace("%en", episodeTitle)
  362. .Replace("%e.n", episodeTitle.Replace(" ", "."))
  363. .Replace("%e_n", episodeTitle.Replace(" ", "_"));
  364. if (endingEpisodeNumber.HasValue)
  365. {
  366. result = result.Replace("%ed", endingEpisodeNumber.Value.ToString(_usCulture))
  367. .Replace("%0ed", endingEpisodeNumber.Value.ToString("00", _usCulture))
  368. .Replace("%00ed", endingEpisodeNumber.Value.ToString("000", _usCulture));
  369. }
  370. return result.Replace("%e", episodeNumber.ToString(_usCulture))
  371. .Replace("%0e", episodeNumber.ToString("00", _usCulture))
  372. .Replace("%00e", episodeNumber.ToString("000", _usCulture));
  373. }
  374. private bool IsSameEpisode(string sourcePath, string newPath)
  375. {
  376. FileInfo sourceFileInfo = new FileInfo(sourcePath);
  377. FileInfo destinationFileInfo = new FileInfo(newPath);
  378. try
  379. {
  380. if (sourceFileInfo.Length == destinationFileInfo.Length)
  381. {
  382. return true;
  383. }
  384. }
  385. catch (FileNotFoundException)
  386. {
  387. return false;
  388. }
  389. return false;
  390. }
  391. }
  392. }