EpisodeFileOrganizer.cs 20 KB

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