jellyfin/Emby.Naming/Subtitles/SubtitleParser.cs

72 lines
2.4 KiB
C#
Raw Normal View History

using System;
2018-09-12 13:26:21 -04:00
using System.IO;
using System.Linq;
2019-01-13 14:17:29 -05:00
using Emby.Naming.Common;
2021-12-20 07:31:07 -05:00
using Jellyfin.Extensions;
2018-09-12 13:26:21 -04:00
namespace Emby.Naming.Subtitles
{
2020-11-10 13:23:10 -05:00
/// <summary>
/// Subtitle Parser class.
/// </summary>
2018-09-12 13:26:21 -04:00
public class SubtitleParser
{
private readonly NamingOptions _options;
2020-11-10 13:23:10 -05:00
/// <summary>
/// Initializes a new instance of the <see cref="SubtitleParser"/> class.
/// </summary>
/// <param name="options"><see cref="NamingOptions"/> object containing SubtitleFileExtensions, SubtitleDefaultFlags, SubtitleForcedFlags and SubtitleFlagDelimiters.</param>
2018-09-12 13:26:21 -04:00
public SubtitleParser(NamingOptions options)
{
_options = options;
}
2020-11-10 13:23:10 -05:00
/// <summary>
/// Parse file to determine if is subtitle and <see cref="SubtitleInfo"/>.
/// </summary>
/// <param name="path">Path to file.</param>
/// <returns>Returns null or <see cref="SubtitleInfo"/> object if parsing is successful.</returns>
2020-04-19 05:57:03 -04:00
public SubtitleInfo? ParseFile(string path)
2018-09-12 13:26:21 -04:00
{
2020-04-19 05:57:03 -04:00
if (path.Length == 0)
2018-09-12 13:26:21 -04:00
{
2020-11-10 13:23:10 -05:00
return null;
2018-09-12 13:26:21 -04:00
}
var extension = Path.GetExtension(path);
2021-12-20 07:31:07 -05:00
if (!_options.SubtitleFileExtensions.Contains(extension, StringComparison.OrdinalIgnoreCase))
2018-09-12 13:26:21 -04:00
{
return null;
}
var flags = GetFlags(path);
2020-11-01 04:47:31 -05:00
var info = new SubtitleInfo(
path,
2021-12-20 07:31:07 -05:00
_options.SubtitleDefaultFlags.Any(i => flags.Contains(i, StringComparison.OrdinalIgnoreCase)),
_options.SubtitleForcedFlags.Any(i => flags.Contains(i, StringComparison.OrdinalIgnoreCase)));
2018-09-12 13:26:21 -04:00
2021-12-20 07:31:07 -05:00
var parts = flags.Where(i => !_options.SubtitleDefaultFlags.Contains(i, StringComparison.OrdinalIgnoreCase)
&& !_options.SubtitleForcedFlags.Contains(i, StringComparison.OrdinalIgnoreCase))
2018-09-12 13:26:21 -04:00
.ToList();
// Should have a name, language and file extension
if (parts.Count >= 3)
{
2020-01-18 10:18:55 -05:00
info.Language = parts[^2];
2018-09-12 13:26:21 -04:00
}
return info;
}
private string[] GetFlags(string path)
{
2020-11-18 08:23:45 -05:00
// Note: the tags need be surrounded be either a space ( ), hyphen -, dot . or underscore _.
2018-09-12 13:26:21 -04:00
var file = Path.GetFileName(path);
return file.Split(_options.SubtitleFlagDelimiters, StringSplitOptions.RemoveEmptyEntries);
}
}
}