From 8fd2b9225a6f9b5143507518d9a235818abef1ae Mon Sep 17 00:00:00 2001 From: Dion Date: Wed, 24 Apr 2024 15:54:44 +0200 Subject: [PATCH] #1537 add regex timeout --- .../Helpers/ExtensionRolesHelper.cs | 34 ++++++++++--------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/starsky/starsky.foundation.platform/Helpers/ExtensionRolesHelper.cs b/starsky/starsky.foundation.platform/Helpers/ExtensionRolesHelper.cs index e65a253f58..8df8f18f3a 100644 --- a/starsky/starsky.foundation.platform/Helpers/ExtensionRolesHelper.cs +++ b/starsky/starsky.foundation.platform/Helpers/ExtensionRolesHelper.cs @@ -8,7 +8,7 @@ namespace starsky.foundation.platform.Helpers { - public static class ExtensionRolesHelper + public static partial class ExtensionRolesHelper { /// /// Xmp sidecar file @@ -88,12 +88,8 @@ private static readonly Dictionary> public static ImageFormat MapFileTypesToExtension(string filename) { if ( string.IsNullOrEmpty(filename) ) return ImageFormat.unknown; - - // without escaped values: - // \.([0-9a-z]+)(?=[?#])|(\.)(?:[\w]+)$ - var matchCollection = new Regex("\\.([0-9a-z]+)(?=[?#])|(\\.)(?:[\\w]+)$", - RegexOptions.None, TimeSpan.FromMilliseconds(100) - ).Matches(filename); + + var matchCollection = FileExtensionRegex().Matches(filename); if ( matchCollection.Count == 0 ) { return ImageFormat.unknown; @@ -280,11 +276,8 @@ public static bool IsExtensionSidecar(string? filename) private static bool IsExtensionForce(string? filename, List checkThisList) { if ( string.IsNullOrEmpty(filename) ) return false; - - // without escaped values: - // \.([0-9a-z]+)(?=[?#])|(\.)(?:[\w]+)$ - var matchCollection = new Regex("\\.([0-9a-z]+)(?=[?#])|(\\.)(?:[\\w]+)$", - RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(200)).Matches(filename); + + var matchCollection = FileExtensionRegex().Matches(filename); if ( matchCollection.Count == 0 ) return false; foreach ( var matchValue in matchCollection.Select(p => p.Value) ) @@ -316,10 +309,7 @@ public static string ReplaceExtensionWithXmp(string? filename) return string.Empty; } - // without escaped values: - // \.([0-9a-z]+)(?=[?#])|(\.)(?:[\w]+)$ - var matchCollection = new Regex("\\.([0-9a-z]+)(?=[?#])|(\\.)(?:[\\w]+)$", - RegexOptions.None, TimeSpan.FromMilliseconds(100)).Matches(filename); + var matchCollection = FileExtensionRegex().Matches(filename); if ( matchCollection.Count == 0 ) return string.Empty; foreach ( Match match in matchCollection ) @@ -339,6 +329,18 @@ public static string ReplaceExtensionWithXmp(string? filename) return string.Empty; } + + /// + /// Check for file extensions + /// without escaped values: + /// \.([0-9a-z]+)(?=[?#])|(\.)(?:[\w]+)$ + /// + /// Regex object + [GeneratedRegex( + @"\.([0-9a-z]+)(?=[?#])|(\.)(?:[\w]+)$", + RegexOptions.CultureInvariant | RegexOptions.IgnoreCase, + matchTimeoutMilliseconds: 500)] + private static partial Regex FileExtensionRegex(); /// /// ImageFormat based on first bytes