2020-01-11 15:16:36 -05:00
|
|
|
using System;
|
2019-01-06 15:50:43 -05:00
|
|
|
using System.Collections.Generic;
|
2021-03-08 19:28:21 -05:00
|
|
|
using System.Diagnostics.CodeAnalysis;
|
2018-09-12 13:26:21 -04:00
|
|
|
using System.Text.RegularExpressions;
|
|
|
|
|
|
|
|
namespace Emby.Naming.Video
|
|
|
|
{
|
|
|
|
/// <summary>
|
2019-12-06 14:40:06 -05:00
|
|
|
/// <see href="http://kodi.wiki/view/Advancedsettings.xml#video" />.
|
2018-09-12 13:26:21 -04:00
|
|
|
/// </summary>
|
2020-01-11 14:25:06 -05:00
|
|
|
public static class CleanStringParser
|
2018-09-12 13:26:21 -04:00
|
|
|
{
|
2020-11-10 11:11:48 -05:00
|
|
|
/// <summary>
|
|
|
|
/// Attempts to extract clean name with regular expressions.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="name">Name of file.</param>
|
|
|
|
/// <param name="expressions">List of regex to parse name and year from.</param>
|
|
|
|
/// <param name="newName">Parsing result string.</param>
|
|
|
|
/// <returns>True if parsing was successful.</returns>
|
2021-03-08 19:28:21 -05:00
|
|
|
public static bool TryClean([NotNullWhen(true)] string? name, IReadOnlyList<Regex> expressions, out ReadOnlySpan<char> newName)
|
2018-09-12 13:26:21 -04:00
|
|
|
{
|
2021-03-08 19:28:21 -05:00
|
|
|
if (string.IsNullOrEmpty(name))
|
|
|
|
{
|
|
|
|
newName = ReadOnlySpan<char>.Empty;
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2021-08-05 02:25:54 -04:00
|
|
|
// Iteratively apply the regexps to clean the string.
|
|
|
|
bool cleaned = false;
|
|
|
|
for (int i = 0; i < expressions.Count; i++)
|
2018-09-12 13:26:21 -04:00
|
|
|
{
|
2021-08-05 02:25:54 -04:00
|
|
|
if (TryClean(name, expressions[i], out newName))
|
2018-09-12 13:26:21 -04:00
|
|
|
{
|
2021-08-05 02:25:54 -04:00
|
|
|
cleaned = true;
|
|
|
|
name = newName.ToString();
|
2018-09-12 13:26:21 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-05 02:25:54 -04:00
|
|
|
newName = cleaned ? name.AsSpan() : ReadOnlySpan<char>.Empty;
|
2021-08-05 16:09:42 -04:00
|
|
|
return cleaned;
|
2018-09-12 13:26:21 -04:00
|
|
|
}
|
|
|
|
|
2021-03-07 16:59:08 -05:00
|
|
|
private static bool TryClean(string name, Regex expression, out ReadOnlySpan<char> newName)
|
2018-09-12 13:26:21 -04:00
|
|
|
{
|
|
|
|
var match = expression.Match(name);
|
2020-01-11 15:16:36 -05:00
|
|
|
int index = match.Index;
|
2021-08-03 16:46:56 -04:00
|
|
|
if (match.Success)
|
2018-09-12 13:26:21 -04:00
|
|
|
{
|
2021-08-03 16:46:56 -04:00
|
|
|
var found = match.Groups.TryGetValue("cleaned", out var cleaned);
|
|
|
|
if (!found || cleaned == null)
|
|
|
|
{
|
|
|
|
newName = ReadOnlySpan<char>.Empty;
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
newName = name.AsSpan().Slice(cleaned.Index, cleaned.Length);
|
2020-01-11 15:16:36 -05:00
|
|
|
return true;
|
2018-09-12 13:26:21 -04:00
|
|
|
}
|
|
|
|
|
2021-03-07 16:59:08 -05:00
|
|
|
newName = ReadOnlySpan<char>.Empty;
|
2020-01-11 15:16:36 -05:00
|
|
|
return false;
|
2018-09-12 13:26:21 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|