EpisodeFileOrganizer.cs 20 KB

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