jellyfin/Emby.Naming/AudioBook/AudioBookFilePathParser.cs

68 lines
2.5 KiB
C#
Raw Normal View History

using System.Globalization;
2018-09-12 13:26:21 -04:00
using System.IO;
using System.Text.RegularExpressions;
using Emby.Naming.Common;
namespace Emby.Naming.AudioBook
{
2020-11-10 11:11:48 -05:00
/// <summary>
/// Parser class to extract part and/or chapter number from audiobook filename.
/// </summary>
2018-09-12 13:26:21 -04:00
public class AudioBookFilePathParser
{
private readonly NamingOptions _options;
2020-11-10 11:11:48 -05:00
/// <summary>
/// Initializes a new instance of the <see cref="AudioBookFilePathParser"/> class.
/// </summary>
/// <param name="options">Naming options containing AudioBookPartsExpressions.</param>
2018-09-12 13:26:21 -04:00
public AudioBookFilePathParser(NamingOptions options)
{
_options = options;
}
2020-11-10 11:11:48 -05:00
/// <summary>
/// Based on regex determines if filename includes part/chapter number.
/// </summary>
/// <param name="path">Path to audiobook file.</param>
/// <returns>Returns <see cref="AudioBookFilePathParser"/> object.</returns>
2019-05-10 14:37:42 -04:00
public AudioBookFilePathParserResult Parse(string path)
2018-09-12 13:26:21 -04:00
{
2020-09-20 08:02:41 -04:00
AudioBookFilePathParserResult result = default;
2018-09-12 13:26:21 -04:00
var fileName = Path.GetFileNameWithoutExtension(path);
foreach (var expression in _options.AudioBookPartsExpressions)
{
2023-02-20 10:07:51 -05:00
var match = Regex.Match(fileName, expression, RegexOptions.IgnoreCase);
2018-09-12 13:26:21 -04:00
if (match.Success)
{
if (!result.ChapterNumber.HasValue)
{
var value = match.Groups["chapter"];
if (value.Success)
{
2023-02-17 09:00:06 -05:00
if (int.TryParse(value.ValueSpan, NumberStyles.Integer, CultureInfo.InvariantCulture, out var intValue))
2018-09-12 13:26:21 -04:00
{
result.ChapterNumber = intValue;
}
}
}
2019-05-10 14:37:42 -04:00
2018-09-12 13:26:21 -04:00
if (!result.PartNumber.HasValue)
{
var value = match.Groups["part"];
if (value.Success)
{
2023-02-17 09:00:06 -05:00
if (int.TryParse(value.ValueSpan, NumberStyles.Integer, CultureInfo.InvariantCulture, out var intValue))
2018-09-12 13:26:21 -04:00
{
result.PartNumber = intValue;
2018-09-12 13:26:21 -04:00
}
}
}
}
}
return result;
}
}
}