New: Validate that naming formats don't contain illegal characters

(cherry picked from commit 145c644c9d8f1636027da8a782a7e74f3182c678)

Closes #5382
This commit is contained in:
Mark McDowall 2020-11-20 14:43:04 -08:00 committed by Bogdan
parent 4e3535f1fe
commit 46dd72e0cd
1 changed files with 32 additions and 0 deletions

View File

@ -1,5 +1,8 @@
using System.IO;
using System.Linq;
using FluentValidation;
using FluentValidation.Validators;
using NzbDrone.Common.Extensions;
namespace NzbDrone.Core.Organizer
{
@ -8,13 +11,42 @@ namespace NzbDrone.Core.Organizer
public static IRuleBuilderOptions<T, string> ValidMovieFolderFormat<T>(this IRuleBuilder<T, string> ruleBuilder)
{
ruleBuilder.SetValidator(new NotEmptyValidator(null));
ruleBuilder.SetValidator(new IllegalCharactersValidator());
return ruleBuilder.SetValidator(new RegularExpressionValidator(FileNameBuilder.MovieTitleRegex)).WithMessage("Must contain movie title");
}
public static IRuleBuilderOptions<T, string> ValidMovieFormat<T>(this IRuleBuilder<T, string> ruleBuilder)
{
ruleBuilder.SetValidator(new NotEmptyValidator(null));
ruleBuilder.SetValidator(new IllegalCharactersValidator());
return ruleBuilder.SetValidator(new RegularExpressionValidator(FileNameBuilder.MovieTitleRegex)).WithMessage("Must contain movie title");
}
}
public class IllegalCharactersValidator : PropertyValidator
{
private static readonly char[] InvalidPathChars = Path.GetInvalidPathChars();
protected override string GetDefaultMessageTemplate() => "Contains illegal characters: {InvalidCharacters}";
protected override bool IsValid(PropertyValidatorContext context)
{
var value = context.PropertyValue as string;
if (value.IsNullOrWhiteSpace())
{
return true;
}
var invalidCharacters = InvalidPathChars.Where(i => value!.IndexOf(i) >= 0).ToList();
if (invalidCharacters.Any())
{
context.MessageFormatter.AppendArgument("InvalidCharacters", string.Join("", invalidCharacters));
return false;
}
return true;
}
}
}