EpisodeFileOrganizer.cs 20 KB

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