AudioBookFilePathParser.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System.Globalization;
  2. using System.IO;
  3. using System.Text.RegularExpressions;
  4. using Emby.Naming.Common;
  5. namespace Emby.Naming.AudioBook
  6. {
  7. /// <summary>
  8. /// Parser class to extract part and/or chapter number from audiobook filename.
  9. /// </summary>
  10. public class AudioBookFilePathParser
  11. {
  12. private readonly NamingOptions _options;
  13. /// <summary>
  14. /// Initializes a new instance of the <see cref="AudioBookFilePathParser"/> class.
  15. /// </summary>
  16. /// <param name="options">Naming options containing AudioBookPartsExpressions.</param>
  17. public AudioBookFilePathParser(NamingOptions options)
  18. {
  19. _options = options;
  20. }
  21. /// <summary>
  22. /// Based on regex determines if filename includes part/chapter number.
  23. /// </summary>
  24. /// <param name="path">Path to audiobook file.</param>
  25. /// <returns>Returns <see cref="AudioBookFilePathParser"/> object.</returns>
  26. public AudioBookFilePathParserResult Parse(string path)
  27. {
  28. AudioBookFilePathParserResult result = default;
  29. var fileName = Path.GetFileNameWithoutExtension(path);
  30. foreach (var expression in _options.AudioBookPartsExpressions)
  31. {
  32. var match = Regex.Match(fileName, expression, RegexOptions.IgnoreCase);
  33. if (match.Success)
  34. {
  35. if (!result.ChapterNumber.HasValue)
  36. {
  37. var value = match.Groups["chapter"];
  38. if (value.Success)
  39. {
  40. if (int.TryParse(value.ValueSpan, NumberStyles.Integer, CultureInfo.InvariantCulture, out var intValue))
  41. {
  42. result.ChapterNumber = intValue;
  43. }
  44. }
  45. }
  46. if (!result.PartNumber.HasValue)
  47. {
  48. var value = match.Groups["part"];
  49. if (value.Success)
  50. {
  51. if (int.TryParse(value.ValueSpan, NumberStyles.Integer, CultureInfo.InvariantCulture, out var intValue))
  52. {
  53. result.PartNumber = intValue;
  54. }
  55. }
  56. }
  57. }
  58. }
  59. return result;
  60. }
  61. }
  62. }