CleanDateTimeParser.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #pragma warning disable CS1591
  2. #pragma warning disable SA1600
  3. using System;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text.RegularExpressions;
  8. using Emby.Naming.Common;
  9. namespace Emby.Naming.Video
  10. {
  11. /// <summary>
  12. /// <see href="http://kodi.wiki/view/Advancedsettings.xml#video" />.
  13. /// </summary>
  14. public class CleanDateTimeParser
  15. {
  16. private readonly NamingOptions _options;
  17. public CleanDateTimeParser(NamingOptions options)
  18. {
  19. _options = options;
  20. }
  21. public CleanDateTimeResult Clean(string name)
  22. {
  23. var originalName = name;
  24. try
  25. {
  26. var extension = Path.GetExtension(name) ?? string.Empty;
  27. // Check supported extensions
  28. if (!_options.VideoFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase)
  29. && !_options.AudioFileExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
  30. {
  31. // Dummy up a file extension because the expressions will fail without one
  32. // This is tricky because we can't just check Path.GetExtension for empty
  33. // If the input is "St. Vincent (2014)", it will produce ". Vincent (2014)" as the extension
  34. name += ".mkv";
  35. }
  36. }
  37. catch (ArgumentException)
  38. {
  39. }
  40. var result = _options.CleanDateTimeRegexes.Select(i => Clean(name, i))
  41. .FirstOrDefault(i => i.HasChanged) ??
  42. new CleanDateTimeResult { Name = originalName };
  43. if (result.HasChanged)
  44. {
  45. return result;
  46. }
  47. // Make a second pass, running clean string first
  48. var cleanStringResult = new CleanStringParser().Clean(name, _options.CleanStringRegexes);
  49. if (!cleanStringResult.HasChanged)
  50. {
  51. return result;
  52. }
  53. return _options.CleanDateTimeRegexes.Select(i => Clean(cleanStringResult.Name, i))
  54. .FirstOrDefault(i => i.HasChanged) ??
  55. result;
  56. }
  57. private static CleanDateTimeResult Clean(string name, Regex expression)
  58. {
  59. var result = new CleanDateTimeResult();
  60. var match = expression.Match(name);
  61. if (match.Success
  62. && match.Groups.Count == 4
  63. && match.Groups[1].Success
  64. && match.Groups[2].Success
  65. && int.TryParse(match.Groups[2].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var year))
  66. {
  67. name = match.Groups[1].Value;
  68. result.Year = year;
  69. result.HasChanged = true;
  70. }
  71. result.Name = name;
  72. return result;
  73. }
  74. }
  75. }