EpisodeFileOrganizer.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Threading;
  6. using MediaBrowser.Common.IO;
  7. using MediaBrowser.Controller.Configuration;
  8. using MediaBrowser.Controller.Entities.TV;
  9. using MediaBrowser.Controller.FileOrganization;
  10. using MediaBrowser.Controller.IO;
  11. using MediaBrowser.Controller.Library;
  12. using MediaBrowser.Controller.Providers;
  13. using MediaBrowser.Model.Configuration;
  14. using MediaBrowser.Model.Entities;
  15. using MediaBrowser.Model.FileOrganization;
  16. using MediaBrowser.Model.Logging;
  17. using System.Globalization;
  18. using System.Threading.Tasks;
  19. namespace MediaBrowser.Server.Implementations.FileOrganization
  20. {
  21. public class EpisodeFileOrganizer
  22. {
  23. private readonly IDirectoryWatchers _directoryWatchers;
  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 CultureInfo _usCulture = new CultureInfo("en-US");
  30. public EpisodeFileOrganizer(IFileOrganizationService organizationService, IServerConfigurationManager config, IFileSystem fileSystem, ILogger logger, ILibraryManager libraryManager, IDirectoryWatchers directoryWatchers)
  31. {
  32. _organizationService = organizationService;
  33. _config = config;
  34. _fileSystem = fileSystem;
  35. _logger = logger;
  36. _libraryManager = libraryManager;
  37. _directoryWatchers = directoryWatchers;
  38. }
  39. public async Task<FileOrganizationResult> OrganizeEpisodeFile(string path, TvFileOrganizationOptions options, bool overwriteExisting)
  40. {
  41. _logger.Info("Sorting file {0}", path);
  42. var result = new FileOrganizationResult
  43. {
  44. Date = DateTime.UtcNow,
  45. OriginalPath = path,
  46. OriginalFileName = Path.GetFileName(path),
  47. Type = FileOrganizerType.Episode
  48. };
  49. var seriesName = TVUtils.GetSeriesNameFromEpisodeFile(path);
  50. if (!string.IsNullOrEmpty(seriesName))
  51. {
  52. var season = TVUtils.GetSeasonNumberFromEpisodeFile(path);
  53. result.ExtractedSeasonNumber = season;
  54. if (season.HasValue)
  55. {
  56. // Passing in true will include a few extra regex's
  57. var episode = TVUtils.GetEpisodeNumberFromFile(path, true);
  58. result.ExtractedEpisodeNumber = episode;
  59. if (episode.HasValue)
  60. {
  61. _logger.Debug("Extracted information from {0}. Series name {1}, Season {2}, Episode {3}", path, seriesName, season, episode);
  62. var endingEpisodeNumber = TVUtils.GetEndingEpisodeNumberFromFile(path);
  63. result.ExtractedEndingEpisodeNumber = endingEpisodeNumber;
  64. OrganizeEpisode(path, seriesName, season.Value, episode.Value, endingEpisodeNumber, options, overwriteExisting, result);
  65. }
  66. else
  67. {
  68. var msg = string.Format("Unable to determine episode number from {0}", path);
  69. result.Status = FileSortingStatus.Failure;
  70. result.StatusMessage = msg;
  71. _logger.Warn(msg);
  72. }
  73. }
  74. else
  75. {
  76. var msg = string.Format("Unable to determine season 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 series name from {0}", path);
  85. result.Status = FileSortingStatus.Failure;
  86. result.StatusMessage = msg;
  87. _logger.Warn(msg);
  88. }
  89. await _organizationService.SaveResult(result, CancellationToken.None).ConfigureAwait(false);
  90. return result;
  91. }
  92. public async Task<FileOrganizationResult> OrganizeWithCorrection(EpisodeFileOrganizationRequest request, TvFileOrganizationOptions options)
  93. {
  94. var result = _organizationService.GetResult(request.ResultId);
  95. var series = (Series)_libraryManager.GetItemById(new Guid(request.SeriesId));
  96. OrganizeEpisode(result.OriginalPath, series, request.SeasonNumber, request.EpisodeNumber, request.EndingEpisodeNumber, _config.Configuration.TvFileOrganizationOptions, true, result);
  97. await _organizationService.SaveResult(result, CancellationToken.None).ConfigureAwait(false);
  98. return result;
  99. }
  100. private void OrganizeEpisode(string sourcePath, string seriesName, int seasonNumber, int episodeNumber, int? endingEpiosdeNumber, TvFileOrganizationOptions options, bool overwriteExisting, FileOrganizationResult result)
  101. {
  102. var series = GetMatchingSeries(seriesName, result);
  103. if (series == null)
  104. {
  105. var msg = string.Format("Unable to find series in library matching name {0}", seriesName);
  106. result.Status = FileSortingStatus.Failure;
  107. result.StatusMessage = msg;
  108. _logger.Warn(msg);
  109. return;
  110. }
  111. OrganizeEpisode(sourcePath, series, seasonNumber, episodeNumber, endingEpiosdeNumber, options, overwriteExisting, result);
  112. }
  113. private void OrganizeEpisode(string sourcePath, Series series, int seasonNumber, int episodeNumber, int? endingEpiosdeNumber, TvFileOrganizationOptions options, bool overwriteExisting, FileOrganizationResult result)
  114. {
  115. _logger.Info("Sorting file {0} into series {1}", sourcePath, series.Path);
  116. // Proceed to sort the file
  117. var newPath = GetNewPath(sourcePath, series, seasonNumber, episodeNumber, endingEpiosdeNumber, options);
  118. if (string.IsNullOrEmpty(newPath))
  119. {
  120. var msg = string.Format("Unable to sort {0} because target path could not be determined.", sourcePath);
  121. result.Status = FileSortingStatus.Failure;
  122. result.StatusMessage = msg;
  123. _logger.Warn(msg);
  124. return;
  125. }
  126. _logger.Info("Sorting file {0} to new path {1}", sourcePath, newPath);
  127. result.TargetPath = newPath;
  128. var existing = GetDuplicatePaths(result.TargetPath, series, seasonNumber, episodeNumber);
  129. if (!overwriteExisting && existing.Count > 0)
  130. {
  131. result.Status = FileSortingStatus.SkippedExisting;
  132. result.StatusMessage = string.Empty;
  133. return;
  134. }
  135. PerformFileSorting(options, result);
  136. }
  137. private List<string> GetDuplicatePaths(string targetPath, Series series, int seasonNumber, int episodeNumber)
  138. {
  139. var list = new List<string>();
  140. if (File.Exists(targetPath))
  141. {
  142. list.Add(targetPath);
  143. }
  144. return list;
  145. }
  146. private void PerformFileSorting(TvFileOrganizationOptions options, FileOrganizationResult result)
  147. {
  148. _directoryWatchers.TemporarilyIgnore(result.TargetPath);
  149. Directory.CreateDirectory(Path.GetDirectoryName(result.TargetPath));
  150. var copy = File.Exists(result.TargetPath);
  151. try
  152. {
  153. if (copy)
  154. {
  155. File.Copy(result.OriginalPath, result.TargetPath, true);
  156. }
  157. else
  158. {
  159. File.Move(result.OriginalPath, result.TargetPath);
  160. }
  161. result.Status = FileSortingStatus.Success;
  162. result.StatusMessage = string.Empty;
  163. }
  164. catch (Exception ex)
  165. {
  166. var errorMsg = string.Format("Failed to move file from {0} to {1}", result.OriginalPath, result.TargetPath);
  167. result.Status = FileSortingStatus.Failure;
  168. result.StatusMessage = errorMsg;
  169. _logger.ErrorException(errorMsg, ex);
  170. return;
  171. }
  172. finally
  173. {
  174. _directoryWatchers.RemoveTempIgnore(result.TargetPath);
  175. }
  176. if (copy)
  177. {
  178. try
  179. {
  180. File.Delete(result.OriginalPath);
  181. }
  182. catch (Exception ex)
  183. {
  184. _logger.ErrorException("Error deleting {0}", ex, result.OriginalPath);
  185. }
  186. }
  187. }
  188. private Series GetMatchingSeries(string seriesName, FileOrganizationResult result)
  189. {
  190. int? yearInName;
  191. var nameWithoutYear = seriesName;
  192. NameParser.ParseName(nameWithoutYear, out nameWithoutYear, out yearInName);
  193. result.ExtractedName = nameWithoutYear;
  194. result.ExtractedYear = yearInName;
  195. return _libraryManager.RootFolder.RecursiveChildren
  196. .OfType<Series>()
  197. .Select(i => NameUtils.GetMatchScore(nameWithoutYear, yearInName, i))
  198. .Where(i => i.Item2 > 0)
  199. .OrderByDescending(i => i.Item2)
  200. .Select(i => i.Item1)
  201. .FirstOrDefault();
  202. }
  203. /// <summary>
  204. /// Gets the new path.
  205. /// </summary>
  206. /// <param name="sourcePath">The source path.</param>
  207. /// <param name="series">The series.</param>
  208. /// <param name="seasonNumber">The season number.</param>
  209. /// <param name="episodeNumber">The episode number.</param>
  210. /// <param name="endingEpisodeNumber">The ending episode number.</param>
  211. /// <param name="options">The options.</param>
  212. /// <returns>System.String.</returns>
  213. private string GetNewPath(string sourcePath, Series series, int seasonNumber, int episodeNumber, int? endingEpisodeNumber, TvFileOrganizationOptions options)
  214. {
  215. // If season and episode numbers match
  216. var currentEpisodes = series.RecursiveChildren.OfType<Episode>()
  217. .Where(i => i.IndexNumber.HasValue &&
  218. i.IndexNumber.Value == episodeNumber &&
  219. i.ParentIndexNumber.HasValue &&
  220. i.ParentIndexNumber.Value == seasonNumber)
  221. .ToList();
  222. if (currentEpisodes.Count == 0)
  223. {
  224. return null;
  225. }
  226. var newPath = GetSeasonFolderPath(series, seasonNumber, options);
  227. var episode = currentEpisodes.First();
  228. var episodeFileName = GetEpisodeFileName(sourcePath, series.Name, seasonNumber, episodeNumber, endingEpisodeNumber, episode.Name, options);
  229. newPath = Path.Combine(newPath, episodeFileName);
  230. return newPath;
  231. }
  232. /// <summary>
  233. /// Gets the season folder path.
  234. /// </summary>
  235. /// <param name="series">The series.</param>
  236. /// <param name="seasonNumber">The season number.</param>
  237. /// <param name="options">The options.</param>
  238. /// <returns>System.String.</returns>
  239. private string GetSeasonFolderPath(Series series, int seasonNumber, TvFileOrganizationOptions options)
  240. {
  241. // If there's already a season folder, use that
  242. var season = series
  243. .RecursiveChildren
  244. .OfType<Season>()
  245. .FirstOrDefault(i => i.LocationType == LocationType.FileSystem && i.IndexNumber.HasValue && i.IndexNumber.Value == seasonNumber);
  246. if (season != null)
  247. {
  248. return season.Path;
  249. }
  250. var path = series.Path;
  251. if (series.ContainsEpisodesWithoutSeasonFolders)
  252. {
  253. return path;
  254. }
  255. if (seasonNumber == 0)
  256. {
  257. return Path.Combine(path, _fileSystem.GetValidFilename(options.SeasonZeroFolderName));
  258. }
  259. var seasonFolderName = options.SeasonFolderPattern
  260. .Replace("%s", seasonNumber.ToString(_usCulture))
  261. .Replace("%0s", seasonNumber.ToString("00", _usCulture))
  262. .Replace("%00s", seasonNumber.ToString("000", _usCulture));
  263. return Path.Combine(path, _fileSystem.GetValidFilename(seasonFolderName));
  264. }
  265. private string GetEpisodeFileName(string sourcePath, string seriesName, int seasonNumber, int episodeNumber, int? endingEpisodeNumber, string episodeTitle, TvFileOrganizationOptions options)
  266. {
  267. seriesName = _fileSystem.GetValidFilename(seriesName);
  268. episodeTitle = _fileSystem.GetValidFilename(episodeTitle);
  269. var sourceExtension = (Path.GetExtension(sourcePath) ?? string.Empty).TrimStart('.');
  270. var pattern = endingEpisodeNumber.HasValue ? options.MultiEpisodeNamePattern : options.EpisodeNamePattern;
  271. var result = pattern.Replace("%sn", seriesName)
  272. .Replace("%s.n", seriesName.Replace(" ", "."))
  273. .Replace("%s_n", seriesName.Replace(" ", "_"))
  274. .Replace("%s", seasonNumber.ToString(_usCulture))
  275. .Replace("%0s", seasonNumber.ToString("00", _usCulture))
  276. .Replace("%00s", seasonNumber.ToString("000", _usCulture))
  277. .Replace("%ext", sourceExtension)
  278. .Replace("%en", episodeTitle)
  279. .Replace("%e.n", episodeTitle.Replace(" ", "."))
  280. .Replace("%e_n", episodeTitle.Replace(" ", "_"));
  281. if (endingEpisodeNumber.HasValue)
  282. {
  283. result = result.Replace("%ed", endingEpisodeNumber.Value.ToString(_usCulture))
  284. .Replace("%0ed", endingEpisodeNumber.Value.ToString("00", _usCulture))
  285. .Replace("%00ed", endingEpisodeNumber.Value.ToString("000", _usCulture));
  286. }
  287. return result.Replace("%e", episodeNumber.ToString(_usCulture))
  288. .Replace("%0e", episodeNumber.ToString("00", _usCulture))
  289. .Replace("%00e", episodeNumber.ToString("000", _usCulture));
  290. }
  291. }
  292. }