EpisodeFileOrganizer.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  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.Extensions;
  9. using MediaBrowser.Model.FileOrganization;
  10. using MediaBrowser.Model.Logging;
  11. using MediaBrowser.Server.Implementations.Library;
  12. using MediaBrowser.Server.Implementations.Logging;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.Globalization;
  16. using System.IO;
  17. using System.Linq;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. using CommonIO;
  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 Task<FileOrganizationResult> OrganizeEpisodeFile(string path, CancellationToken cancellationToken)
  44. {
  45. var options = _config.GetAutoOrganizeOptions();
  46. return OrganizeEpisodeFile(path, options, false, cancellationToken);
  47. }
  48. public async Task<FileOrganizationResult> OrganizeEpisodeFile(string path, AutoOrganizeOptions options, bool overwriteExisting, CancellationToken cancellationToken)
  49. {
  50. _logger.Info("Sorting file {0}", path);
  51. var result = new FileOrganizationResult
  52. {
  53. Date = DateTime.UtcNow,
  54. OriginalPath = path,
  55. OriginalFileName = Path.GetFileName(path),
  56. Type = FileOrganizerType.Episode,
  57. FileSize = new FileInfo(path).Length
  58. };
  59. var namingOptions = ((LibraryManager)_libraryManager).GetNamingOptions();
  60. var resolver = new Naming.TV.EpisodeResolver(namingOptions, new PatternsLogger());
  61. var episodeInfo = resolver.Resolve(path, false) ??
  62. new Naming.TV.EpisodeInfo();
  63. var seriesName = episodeInfo.SeriesName;
  64. if (!string.IsNullOrEmpty(seriesName))
  65. {
  66. var seasonNumber = episodeInfo.SeasonNumber;
  67. result.ExtractedSeasonNumber = seasonNumber;
  68. // Passing in true will include a few extra regex's
  69. var episodeNumber = episodeInfo.EpisodeNumber;
  70. result.ExtractedEpisodeNumber = episodeNumber;
  71. var premiereDate = episodeInfo.IsByDate ?
  72. new DateTime(episodeInfo.Year.Value, episodeInfo.Month.Value, episodeInfo.Day.Value) :
  73. (DateTime?)null;
  74. if (episodeInfo.IsByDate || (seasonNumber.HasValue && episodeNumber.HasValue))
  75. {
  76. if (episodeInfo.IsByDate)
  77. {
  78. _logger.Debug("Extracted information from {0}. Series name {1}, Date {2}", path, seriesName, premiereDate.Value);
  79. }
  80. else
  81. {
  82. _logger.Debug("Extracted information from {0}. Series name {1}, Season {2}, Episode {3}", path, seriesName, seasonNumber, episodeNumber);
  83. }
  84. var endingEpisodeNumber = episodeInfo.EndingEpsiodeNumber;
  85. result.ExtractedEndingEpisodeNumber = endingEpisodeNumber;
  86. await OrganizeEpisode(path,
  87. seriesName,
  88. seasonNumber,
  89. episodeNumber,
  90. endingEpisodeNumber,
  91. premiereDate,
  92. options,
  93. overwriteExisting,
  94. false,
  95. result,
  96. cancellationToken).ConfigureAwait(false);
  97. }
  98. else
  99. {
  100. var msg = string.Format("Unable to determine episode number from {0}", path);
  101. result.Status = FileSortingStatus.Failure;
  102. result.StatusMessage = msg;
  103. _logger.Warn(msg);
  104. }
  105. }
  106. else
  107. {
  108. var msg = string.Format("Unable to determine series name from {0}", path);
  109. result.Status = FileSortingStatus.Failure;
  110. result.StatusMessage = msg;
  111. _logger.Warn(msg);
  112. }
  113. var previousResult = _organizationService.GetResultBySourcePath(path);
  114. if (previousResult != null)
  115. {
  116. // Don't keep saving the same result over and over if nothing has changed
  117. if (previousResult.Status == result.Status && previousResult.StatusMessage == result.StatusMessage && result.Status != FileSortingStatus.Success)
  118. {
  119. return previousResult;
  120. }
  121. }
  122. await _organizationService.SaveResult(result, CancellationToken.None).ConfigureAwait(false);
  123. return result;
  124. }
  125. public async Task<FileOrganizationResult> OrganizeWithCorrection(EpisodeFileOrganizationRequest request, AutoOrganizeOptions options, CancellationToken cancellationToken)
  126. {
  127. var result = _organizationService.GetResult(request.ResultId);
  128. var series = (Series)_libraryManager.GetItemById(new Guid(request.SeriesId));
  129. await OrganizeEpisode(result.OriginalPath,
  130. series,
  131. request.SeasonNumber,
  132. request.EpisodeNumber,
  133. request.EndingEpisodeNumber,
  134. null,
  135. options,
  136. true,
  137. request.RememberCorrection,
  138. result,
  139. cancellationToken).ConfigureAwait(false);
  140. await _organizationService.SaveResult(result, CancellationToken.None).ConfigureAwait(false);
  141. return result;
  142. }
  143. private Task OrganizeEpisode(string sourcePath,
  144. string seriesName,
  145. int? seasonNumber,
  146. int? episodeNumber,
  147. int? endingEpiosdeNumber,
  148. DateTime? premiereDate,
  149. AutoOrganizeOptions options,
  150. bool overwriteExisting,
  151. bool rememberCorrection,
  152. FileOrganizationResult result,
  153. CancellationToken cancellationToken)
  154. {
  155. var series = GetMatchingSeries(seriesName, result, options);
  156. if (series == null)
  157. {
  158. var msg = string.Format("Unable to find series in library matching name {0}", seriesName);
  159. result.Status = FileSortingStatus.Failure;
  160. result.StatusMessage = msg;
  161. _logger.Warn(msg);
  162. return Task.FromResult(true);
  163. }
  164. return OrganizeEpisode(sourcePath,
  165. series,
  166. seasonNumber,
  167. episodeNumber,
  168. endingEpiosdeNumber,
  169. premiereDate,
  170. options,
  171. overwriteExisting,
  172. rememberCorrection,
  173. result,
  174. cancellationToken);
  175. }
  176. private async Task OrganizeEpisode(string sourcePath,
  177. Series series,
  178. int? seasonNumber,
  179. int? episodeNumber,
  180. int? endingEpiosdeNumber,
  181. DateTime? premiereDate,
  182. AutoOrganizeOptions options,
  183. bool overwriteExisting,
  184. bool rememberCorrection,
  185. FileOrganizationResult result,
  186. CancellationToken cancellationToken)
  187. {
  188. _logger.Info("Sorting file {0} into series {1}", sourcePath, series.Path);
  189. var originalExtractedSeriesString = result.ExtractedName;
  190. // Proceed to sort the file
  191. var newPath = await GetNewPath(sourcePath, series, seasonNumber, episodeNumber, endingEpiosdeNumber, premiereDate, options.TvOptions, cancellationToken).ConfigureAwait(false);
  192. if (string.IsNullOrEmpty(newPath))
  193. {
  194. var msg = string.Format("Unable to sort {0} because target path could not be determined.", sourcePath);
  195. result.Status = FileSortingStatus.Failure;
  196. result.StatusMessage = msg;
  197. _logger.Warn(msg);
  198. return;
  199. }
  200. _logger.Info("Sorting file {0} to new path {1}", sourcePath, newPath);
  201. result.TargetPath = newPath;
  202. var fileExists = _fileSystem.FileExists(result.TargetPath);
  203. var otherDuplicatePaths = GetOtherDuplicatePaths(result.TargetPath, series, seasonNumber, episodeNumber, endingEpiosdeNumber);
  204. if (!overwriteExisting)
  205. {
  206. if (options.TvOptions.CopyOriginalFile && fileExists && IsSameEpisode(sourcePath, newPath))
  207. {
  208. _logger.Info("File {0} already copied to new path {1}, stopping organization", sourcePath, newPath);
  209. result.Status = FileSortingStatus.SkippedExisting;
  210. result.StatusMessage = string.Empty;
  211. return;
  212. }
  213. if (fileExists || otherDuplicatePaths.Count > 0)
  214. {
  215. result.Status = FileSortingStatus.SkippedExisting;
  216. result.StatusMessage = string.Empty;
  217. result.DuplicatePaths = otherDuplicatePaths;
  218. return;
  219. }
  220. }
  221. PerformFileSorting(options.TvOptions, result);
  222. if (overwriteExisting)
  223. {
  224. var hasRenamedFiles = false;
  225. foreach (var path in otherDuplicatePaths)
  226. {
  227. _logger.Debug("Removing duplicate episode {0}", path);
  228. _libraryMonitor.ReportFileSystemChangeBeginning(path);
  229. var renameRelatedFiles = !hasRenamedFiles &&
  230. string.Equals(Path.GetDirectoryName(path), Path.GetDirectoryName(result.TargetPath), StringComparison.OrdinalIgnoreCase);
  231. if (renameRelatedFiles)
  232. {
  233. hasRenamedFiles = true;
  234. }
  235. try
  236. {
  237. DeleteLibraryFile(path, renameRelatedFiles, result.TargetPath);
  238. }
  239. catch (IOException ex)
  240. {
  241. _logger.ErrorException("Error removing duplicate episode", ex, path);
  242. }
  243. finally
  244. {
  245. _libraryMonitor.ReportFileSystemChangeComplete(path, true);
  246. }
  247. }
  248. }
  249. if (rememberCorrection)
  250. {
  251. SaveSmartMatchString(originalExtractedSeriesString, series, options);
  252. }
  253. }
  254. private void SaveSmartMatchString(string matchString, Series series, AutoOrganizeOptions options)
  255. {
  256. SmartMatchInfo info = options.SmartMatchInfos.FirstOrDefault(i => string.Equals(i.ItemName, series.Name, StringComparison.OrdinalIgnoreCase));
  257. if (info == null)
  258. {
  259. info = new SmartMatchInfo();
  260. info.ItemName = series.Name;
  261. info.OrganizerType = FileOrganizerType.Episode;
  262. info.DisplayName = series.Name;
  263. var list = options.SmartMatchInfos.ToList();
  264. list.Add(info);
  265. options.SmartMatchInfos = list.ToArray();
  266. }
  267. if (!info.MatchStrings.Contains(matchString, StringComparer.OrdinalIgnoreCase))
  268. {
  269. var list = info.MatchStrings.ToList();
  270. list.Add(matchString);
  271. info.MatchStrings = list.ToArray();
  272. _config.SaveAutoOrganizeOptions(options);
  273. }
  274. }
  275. private void DeleteLibraryFile(string path, bool renameRelatedFiles, string targetPath)
  276. {
  277. _fileSystem.DeleteFile(path);
  278. if (!renameRelatedFiles)
  279. {
  280. return;
  281. }
  282. // Now find other files
  283. var originalFilenameWithoutExtension = Path.GetFileNameWithoutExtension(path);
  284. var directory = Path.GetDirectoryName(path);
  285. if (!string.IsNullOrWhiteSpace(originalFilenameWithoutExtension) && !string.IsNullOrWhiteSpace(directory))
  286. {
  287. // Get all related files, e.g. metadata, images, etc
  288. var files = _fileSystem.GetFilePaths(directory)
  289. .Where(i => (Path.GetFileNameWithoutExtension(i) ?? string.Empty).StartsWith(originalFilenameWithoutExtension, StringComparison.OrdinalIgnoreCase))
  290. .ToList();
  291. var targetFilenameWithoutExtension = Path.GetFileNameWithoutExtension(targetPath);
  292. foreach (var file in files)
  293. {
  294. directory = Path.GetDirectoryName(file);
  295. var filename = Path.GetFileName(file);
  296. filename = filename.Replace(originalFilenameWithoutExtension, targetFilenameWithoutExtension,
  297. StringComparison.OrdinalIgnoreCase);
  298. var destination = Path.Combine(directory, filename);
  299. _fileSystem.MoveFile(file, destination);
  300. }
  301. }
  302. }
  303. private List<string> GetOtherDuplicatePaths(string targetPath,
  304. Series series,
  305. int? seasonNumber,
  306. int? episodeNumber,
  307. int? endingEpisodeNumber)
  308. {
  309. // TODO: Support date-naming?
  310. if (!seasonNumber.HasValue || !episodeNumber.HasValue)
  311. {
  312. return new List<string>();
  313. }
  314. var episodePaths = series.GetRecursiveChildren()
  315. .OfType<Episode>()
  316. .Where(i =>
  317. {
  318. var locationType = i.LocationType;
  319. // Must be file system based and match exactly
  320. if (locationType != LocationType.Remote &&
  321. locationType != LocationType.Virtual &&
  322. i.ParentIndexNumber.HasValue &&
  323. i.ParentIndexNumber.Value == seasonNumber &&
  324. i.IndexNumber.HasValue &&
  325. i.IndexNumber.Value == episodeNumber)
  326. {
  327. if (endingEpisodeNumber.HasValue || i.IndexNumberEnd.HasValue)
  328. {
  329. return endingEpisodeNumber.HasValue && i.IndexNumberEnd.HasValue &&
  330. endingEpisodeNumber.Value == i.IndexNumberEnd.Value;
  331. }
  332. return true;
  333. }
  334. return false;
  335. })
  336. .Select(i => i.Path)
  337. .ToList();
  338. var folder = Path.GetDirectoryName(targetPath);
  339. var targetFileNameWithoutExtension = _fileSystem.GetFileNameWithoutExtension(targetPath);
  340. try
  341. {
  342. var filesOfOtherExtensions = _fileSystem.GetFilePaths(folder)
  343. .Where(i => _libraryManager.IsVideoFile(i) && string.Equals(_fileSystem.GetFileNameWithoutExtension(i), targetFileNameWithoutExtension, StringComparison.OrdinalIgnoreCase));
  344. episodePaths.AddRange(filesOfOtherExtensions);
  345. }
  346. catch (DirectoryNotFoundException)
  347. {
  348. // No big deal. Maybe the season folder doesn't already exist.
  349. }
  350. return episodePaths.Where(i => !string.Equals(i, targetPath, StringComparison.OrdinalIgnoreCase))
  351. .Distinct(StringComparer.OrdinalIgnoreCase)
  352. .ToList();
  353. }
  354. private void PerformFileSorting(TvFileOrganizationOptions options, FileOrganizationResult result)
  355. {
  356. _libraryMonitor.ReportFileSystemChangeBeginning(result.TargetPath);
  357. _fileSystem.CreateDirectory(Path.GetDirectoryName(result.TargetPath));
  358. var targetAlreadyExists = _fileSystem.FileExists(result.TargetPath);
  359. try
  360. {
  361. if (targetAlreadyExists || options.CopyOriginalFile)
  362. {
  363. _fileSystem.CopyFile(result.OriginalPath, result.TargetPath, true);
  364. }
  365. else
  366. {
  367. _fileSystem.MoveFile(result.OriginalPath, result.TargetPath);
  368. }
  369. result.Status = FileSortingStatus.Success;
  370. result.StatusMessage = string.Empty;
  371. }
  372. catch (Exception ex)
  373. {
  374. var errorMsg = string.Format("Failed to move file from {0} to {1}", result.OriginalPath, result.TargetPath);
  375. result.Status = FileSortingStatus.Failure;
  376. result.StatusMessage = errorMsg;
  377. _logger.ErrorException(errorMsg, ex);
  378. return;
  379. }
  380. finally
  381. {
  382. _libraryMonitor.ReportFileSystemChangeComplete(result.TargetPath, true);
  383. }
  384. if (targetAlreadyExists && !options.CopyOriginalFile)
  385. {
  386. try
  387. {
  388. _fileSystem.DeleteFile(result.OriginalPath);
  389. }
  390. catch (Exception ex)
  391. {
  392. _logger.ErrorException("Error deleting {0}", ex, result.OriginalPath);
  393. }
  394. }
  395. }
  396. private Series GetMatchingSeries(string seriesName, FileOrganizationResult result, AutoOrganizeOptions options)
  397. {
  398. var parsedName = _libraryManager.ParseName(seriesName);
  399. var yearInName = parsedName.Year;
  400. var nameWithoutYear = parsedName.Name;
  401. result.ExtractedName = nameWithoutYear;
  402. result.ExtractedYear = yearInName;
  403. var series = _libraryManager.RootFolder.GetRecursiveChildren(i => i is Series)
  404. .Cast<Series>()
  405. .Select(i => NameUtils.GetMatchScore(nameWithoutYear, yearInName, i))
  406. .Where(i => i.Item2 > 0)
  407. .OrderByDescending(i => i.Item2)
  408. .Select(i => i.Item1)
  409. .FirstOrDefault();
  410. if (series == null)
  411. {
  412. SmartMatchInfo info = options.SmartMatchInfos.FirstOrDefault(e => e.MatchStrings.Contains(seriesName, StringComparer.OrdinalIgnoreCase));
  413. if (info != null)
  414. {
  415. series = _libraryManager.RootFolder
  416. .GetRecursiveChildren(i => i is Series)
  417. .Cast<Series>()
  418. .FirstOrDefault(i => string.Equals(i.Name, info.ItemName, StringComparison.OrdinalIgnoreCase));
  419. }
  420. }
  421. return series;
  422. }
  423. /// <summary>
  424. /// Gets the new path.
  425. /// </summary>
  426. /// <param name="sourcePath">The source path.</param>
  427. /// <param name="series">The series.</param>
  428. /// <param name="seasonNumber">The season number.</param>
  429. /// <param name="episodeNumber">The episode number.</param>
  430. /// <param name="endingEpisodeNumber">The ending episode number.</param>
  431. /// <param name="premiereDate">The premiere date.</param>
  432. /// <param name="options">The options.</param>
  433. /// <param name="cancellationToken">The cancellation token.</param>
  434. /// <returns>System.String.</returns>
  435. private async Task<string> GetNewPath(string sourcePath,
  436. Series series,
  437. int? seasonNumber,
  438. int? episodeNumber,
  439. int? endingEpisodeNumber,
  440. DateTime? premiereDate,
  441. TvFileOrganizationOptions options,
  442. CancellationToken cancellationToken)
  443. {
  444. var episodeInfo = new EpisodeInfo
  445. {
  446. IndexNumber = episodeNumber,
  447. IndexNumberEnd = endingEpisodeNumber,
  448. MetadataCountryCode = series.GetPreferredMetadataCountryCode(),
  449. MetadataLanguage = series.GetPreferredMetadataLanguage(),
  450. ParentIndexNumber = seasonNumber,
  451. SeriesProviderIds = series.ProviderIds,
  452. PremiereDate = premiereDate
  453. };
  454. var searchResults = await _providerManager.GetRemoteSearchResults<Episode, EpisodeInfo>(new RemoteSearchQuery<EpisodeInfo>
  455. {
  456. SearchInfo = episodeInfo
  457. }, cancellationToken).ConfigureAwait(false);
  458. var episode = searchResults.FirstOrDefault();
  459. if (episode == null)
  460. {
  461. var msg = string.Format("No provider metadata found for {0} season {1} episode {2}", series.Name, seasonNumber, episodeNumber);
  462. _logger.Warn(msg);
  463. return null;
  464. }
  465. var episodeName = episode.Name;
  466. //if (string.IsNullOrWhiteSpace(episodeName))
  467. //{
  468. // var msg = string.Format("No provider metadata found for {0} season {1} episode {2}", series.Name, seasonNumber, episodeNumber);
  469. // _logger.Warn(msg);
  470. // return null;
  471. //}
  472. seasonNumber = seasonNumber ?? episode.ParentIndexNumber;
  473. episodeNumber = episodeNumber ?? episode.IndexNumber;
  474. var newPath = GetSeasonFolderPath(series, seasonNumber.Value, options);
  475. // MAX_PATH - trailing <NULL> charachter - drive component: 260 - 1 - 3 = 256
  476. // Usually newPath would include the drive component, but use 256 to be sure
  477. var maxFilenameLength = 256 - newPath.Length;
  478. if (!newPath.EndsWith(@"\"))
  479. {
  480. // Remove 1 for missing backslash combining path and filename
  481. maxFilenameLength--;
  482. }
  483. // Remove additional 4 chars to prevent PathTooLongException for downloaded subtitles (eg. filename.ext.eng.srt)
  484. maxFilenameLength -= 4;
  485. var episodeFileName = GetEpisodeFileName(sourcePath, series.Name, seasonNumber.Value, episodeNumber.Value, endingEpisodeNumber, episodeName, options, maxFilenameLength);
  486. if (string.IsNullOrEmpty(episodeFileName))
  487. {
  488. // cause failure
  489. return string.Empty;
  490. }
  491. newPath = Path.Combine(newPath, episodeFileName);
  492. return newPath;
  493. }
  494. /// <summary>
  495. /// Gets the season folder path.
  496. /// </summary>
  497. /// <param name="series">The series.</param>
  498. /// <param name="seasonNumber">The season number.</param>
  499. /// <param name="options">The options.</param>
  500. /// <returns>System.String.</returns>
  501. private string GetSeasonFolderPath(Series series, int seasonNumber, TvFileOrganizationOptions options)
  502. {
  503. // If there's already a season folder, use that
  504. var season = series
  505. .GetRecursiveChildren(i => i is Season && i.LocationType == LocationType.FileSystem && i.IndexNumber.HasValue && i.IndexNumber.Value == seasonNumber)
  506. .FirstOrDefault();
  507. if (season != null)
  508. {
  509. return season.Path;
  510. }
  511. var path = series.Path;
  512. if (series.ContainsEpisodesWithoutSeasonFolders)
  513. {
  514. return path;
  515. }
  516. if (seasonNumber == 0)
  517. {
  518. return Path.Combine(path, _fileSystem.GetValidFilename(options.SeasonZeroFolderName));
  519. }
  520. var seasonFolderName = options.SeasonFolderPattern
  521. .Replace("%s", seasonNumber.ToString(_usCulture))
  522. .Replace("%0s", seasonNumber.ToString("00", _usCulture))
  523. .Replace("%00s", seasonNumber.ToString("000", _usCulture));
  524. return Path.Combine(path, _fileSystem.GetValidFilename(seasonFolderName));
  525. }
  526. private string GetEpisodeFileName(string sourcePath, string seriesName, int seasonNumber, int episodeNumber, int? endingEpisodeNumber, string episodeTitle, TvFileOrganizationOptions options, int? maxLength)
  527. {
  528. seriesName = _fileSystem.GetValidFilename(seriesName).Trim();
  529. if (string.IsNullOrWhiteSpace(episodeTitle))
  530. {
  531. episodeTitle = string.Empty;
  532. }
  533. else
  534. {
  535. episodeTitle = _fileSystem.GetValidFilename(episodeTitle).Trim();
  536. }
  537. var sourceExtension = (Path.GetExtension(sourcePath) ?? string.Empty).TrimStart('.');
  538. var pattern = endingEpisodeNumber.HasValue ? options.MultiEpisodeNamePattern : options.EpisodeNamePattern;
  539. var result = pattern.Replace("%sn", seriesName)
  540. .Replace("%s.n", seriesName.Replace(" ", "."))
  541. .Replace("%s_n", seriesName.Replace(" ", "_"))
  542. .Replace("%s", seasonNumber.ToString(_usCulture))
  543. .Replace("%0s", seasonNumber.ToString("00", _usCulture))
  544. .Replace("%00s", seasonNumber.ToString("000", _usCulture))
  545. .Replace("%ext", sourceExtension)
  546. .Replace("%en", "%#1")
  547. .Replace("%e.n", "%#2")
  548. .Replace("%e_n", "%#3");
  549. if (endingEpisodeNumber.HasValue)
  550. {
  551. result = result.Replace("%ed", endingEpisodeNumber.Value.ToString(_usCulture))
  552. .Replace("%0ed", endingEpisodeNumber.Value.ToString("00", _usCulture))
  553. .Replace("%00ed", endingEpisodeNumber.Value.ToString("000", _usCulture));
  554. }
  555. result = result.Replace("%e", episodeNumber.ToString(_usCulture))
  556. .Replace("%0e", episodeNumber.ToString("00", _usCulture))
  557. .Replace("%00e", episodeNumber.ToString("000", _usCulture));
  558. if (maxLength.HasValue && result.Contains("%#"))
  559. {
  560. // Substract 3 for the temp token length (%#1, %#2 or %#3)
  561. int maxRemainingTitleLength = maxLength.Value - result.Length + 3;
  562. string shortenedEpisodeTitle = string.Empty;
  563. if (maxRemainingTitleLength > 5)
  564. {
  565. // A title with fewer than 5 letters wouldn't be of much value
  566. shortenedEpisodeTitle = episodeTitle.Substring(0, Math.Min(maxRemainingTitleLength, episodeTitle.Length));
  567. }
  568. result = result.Replace("%#1", shortenedEpisodeTitle)
  569. .Replace("%#2", shortenedEpisodeTitle.Replace(" ", "."))
  570. .Replace("%#3", shortenedEpisodeTitle.Replace(" ", "_"));
  571. }
  572. if (maxLength.HasValue && result.Length > maxLength.Value)
  573. {
  574. // There may be cases where reducing the title length may still not be sufficient to
  575. // stay below maxLength
  576. var msg = string.Format("Unable to generate an episode file name shorter than {0} characters to constrain to the max path limit", maxLength);
  577. _logger.Warn(msg);
  578. return string.Empty;
  579. }
  580. return result;
  581. }
  582. private bool IsSameEpisode(string sourcePath, string newPath)
  583. {
  584. try
  585. {
  586. var sourceFileInfo = new FileInfo(sourcePath);
  587. var destinationFileInfo = new FileInfo(newPath);
  588. if (sourceFileInfo.Length == destinationFileInfo.Length)
  589. {
  590. return true;
  591. }
  592. }
  593. catch (FileNotFoundException)
  594. {
  595. return false;
  596. }
  597. catch (DirectoryNotFoundException)
  598. {
  599. return false;
  600. }
  601. return false;
  602. }
  603. }
  604. }