CleanDateTimeParser.cs 2.8 KB

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