From 46dd72e0cd94630343420074e9826c6cd2537e6c Mon Sep 17 00:00:00 2001 From: Mark McDowall Date: Fri, 20 Nov 2020 14:43:04 -0800 Subject: [PATCH] New: Validate that naming formats don't contain illegal characters (cherry picked from commit 145c644c9d8f1636027da8a782a7e74f3182c678) Closes #5382 --- .../Organizer/FileNameValidation.cs | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/NzbDrone.Core/Organizer/FileNameValidation.cs b/src/NzbDrone.Core/Organizer/FileNameValidation.cs index 0352e7ba7..b7682407b 100644 --- a/src/NzbDrone.Core/Organizer/FileNameValidation.cs +++ b/src/NzbDrone.Core/Organizer/FileNameValidation.cs @@ -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 ValidMovieFolderFormat(this IRuleBuilder 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 ValidMovieFormat(this IRuleBuilder 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; + } + } }