From 7ebf6b28ef20bbbc7604074609c5c961a51d3136 Mon Sep 17 00:00:00 2001 From: Yuuki Wesp Date: Wed, 12 Jun 2024 20:53:04 +0300 Subject: [PATCH] refactoring --- src/controllers/PackageContentController.cs | 5 +- src/controllers/StateController.cs | 12 +-- src/logic/DependencyInjectionExtensions.cs | 2 +- src/logic/services/ImageDomainValidator.cs | 8 +- src/logic/services/MarkdownService.cs | 6 +- src/logic/services/NullPackageService.cs | 4 +- src/logic/services/PackageValidator.cs | 8 +- src/logic/services/ServiceIndexService.cs | 2 +- .../searchs/FirestoreSearchService.cs | 4 +- .../searchs/models/AutocompleteContext.cs | 6 +- .../services/searchs/models/SearchContext.cs | 2 +- src/profanity/Profanity.cs | 82 ++++++------------- 12 files changed, 55 insertions(+), 86 deletions(-) diff --git a/src/controllers/PackageContentController.cs b/src/controllers/PackageContentController.cs index 3e76bdd..1e5e254 100644 --- a/src/controllers/PackageContentController.cs +++ b/src/controllers/PackageContentController.cs @@ -78,13 +78,14 @@ public async Task DownloadReadmeAsync(string id, string version, not null => NuGetVersion.Parse(version) }; - var readmeStream = await _content.GetPackageReadmeStreamOrNullAsync(id, ver, cancellationToken); + var readmeStream = await _content.GetPackageReadmeStreamOrNullAsync(id, ver, cancellationToken); + if (readmeStream == null) return NotFound(); using var reader = new StreamReader(readmeStream); - var result = await reader.ReadToEndAsync(); + var result = await reader.ReadToEndAsync(cancellationToken); _cache.Set($"@/packages/{id}/{version}/readme", result, ver.HasMetadata ? TimeSpan.FromMinutes(15) : TimeSpan.FromHours(6)); diff --git a/src/controllers/StateController.cs b/src/controllers/StateController.cs index 08da9cf..a5f2b9b 100644 --- a/src/controllers/StateController.cs +++ b/src/controllers/StateController.cs @@ -30,11 +30,11 @@ public async Task GetState() var result = new PackagesState() { latest_packages = latest, - packages_state = new List() - { - { new("Package downloads", downloads) }, - { new("Package total", count) }, - }, + packages_state = + [ + new("Package downloads", downloads), + new("Package total", count) + ], popular_packages = popular }; @@ -49,5 +49,5 @@ public class PackagesState { public IReadOnlyCollection popular_packages { get; set; } public IReadOnlyCollection latest_packages { get; set; } - public List packages_state { get; set; } = new (); + public List packages_state { get; set; } = []; } diff --git a/src/logic/DependencyInjectionExtensions.cs b/src/logic/DependencyInjectionExtensions.cs index aade58b..4ceb007 100644 --- a/src/logic/DependencyInjectionExtensions.cs +++ b/src/logic/DependencyInjectionExtensions.cs @@ -56,7 +56,7 @@ private static void AddRegistryServices(this IServiceCollection services) a.ProjectId = configuration.GetDatabaseConnectionString(); return a.Build(); }); - services.AddSingleton(x => GetServiceFromProviders(x)); + services.AddSingleton(GetServiceFromProviders); services.TryAddSingleton(); services.TryAddSingleton(); diff --git a/src/logic/services/ImageDomainValidator.cs b/src/logic/services/ImageDomainValidator.cs index 37afe36..df51a3c 100644 --- a/src/logic/services/ImageDomainValidator.cs +++ b/src/logic/services/ImageDomainValidator.cs @@ -6,7 +6,7 @@ namespace core.services; public class ImageDomainValidator { private static readonly TimeSpan RegexTimeout = TimeSpan.FromMinutes(1); - private static readonly Regex GithubBadgeUrlRegEx = new Regex("^(https|http):\\/\\/github\\.com\\/[^/]+\\/[^/]+(\\/actions)?\\/workflows\\/.*badge\\.svg", RegexOptions.IgnoreCase, RegexTimeout); + private static readonly Regex GithubBadgeUrlRegEx = new("^(https|http):\\/\\/github\\.com\\/[^/]+\\/[^/]+(\\/actions)?\\/workflows\\/.*badge\\.svg", RegexOptions.IgnoreCase, RegexTimeout); public bool TryPrepareImageUrlForRendering(string uriString, out string readyUriString) { @@ -40,8 +40,8 @@ private bool IsTrustedImageDomain(Uri uri) => IsGitHubBadge(uri); - private static List TrustedImageDomains = new List() - { + private static List TrustedImageDomains = + [ "api.bintray.com", "api.codacy.com", "app.codacy.com", @@ -75,7 +75,7 @@ private bool IsTrustedImageDomain(Uri uri) => "raw.githubusercontent.com", "user-images.githubusercontent.com", "camo.githubusercontent.com" - }; + ]; private bool IsGitHubBadge(Uri uri) { diff --git a/src/logic/services/MarkdownService.cs b/src/logic/services/MarkdownService.cs index 9864b1c..2a7e8e0 100644 --- a/src/logic/services/MarkdownService.cs +++ b/src/logic/services/MarkdownService.cs @@ -23,9 +23,9 @@ public class MarkdownService { private readonly ImageDomainValidator _imageDomainValidator; private static readonly TimeSpan RegexTimeout = TimeSpan.FromMinutes(1); - private static readonly Regex EncodedBlockQuotePattern = new Regex("^ {0,3}>", RegexOptions.Multiline, RegexTimeout); - private static readonly Regex LinkPattern = new Regex("", RegexOptions.Singleline, RegexTimeout); + private static readonly Regex EncodedBlockQuotePattern = new("^ {0,3}>", RegexOptions.Multiline, RegexTimeout); + private static readonly Regex LinkPattern = new("", RegexOptions.Singleline, RegexTimeout); public bool IsMarkdigMdRenderingEnabled { get; set; } = true; diff --git a/src/logic/services/NullPackageService.cs b/src/logic/services/NullPackageService.cs index 06bb85e..0c47285 100644 --- a/src/logic/services/NullPackageService.cs +++ b/src/logic/services/NullPackageService.cs @@ -18,8 +18,8 @@ public Task AddAsync(Package package, UserRecord owner, Cancel public async Task> FindAsync(string id, bool includeUnlisted, CancellationToken cancellationToken) => new List().AsReadOnly(); - public async Task> GetLatestPackagesByUserAsync(UserRecord user, CancellationToken token = default) - => new List(); + public async Task> GetLatestPackagesByUserAsync(UserRecord user, CancellationToken token = default) => + []; public Task ExistsAsync(string id, CancellationToken cancellationToken) => Task.FromResult(default(bool)); diff --git a/src/logic/services/PackageValidator.cs b/src/logic/services/PackageValidator.cs index 279aa60..a01fd3e 100644 --- a/src/logic/services/PackageValidator.cs +++ b/src/logic/services/PackageValidator.cs @@ -9,17 +9,17 @@ public class PackageValidator private const long MaxAllowedContentForUploading = 1024 * 1024 * 300; // 300 MB private static Profanity _censor = new ("./content"); - private static readonly List Reserved = new() - { + private static readonly List Reserved = + [ "com0", "com1", "com2", "com3", "com4", "com5", - "com6","com7", "com8", "com9", + "com6", "com7", "com8", "com9", "builtins", "collections", "debug", "std", "test", "bump", "nul", "null", "prn", "aux", "vin", "http", "grpc", "logger", "core", "kernel", "live", "docker" - }; + ]; public static async Task ValidateExistAsync(Shard shard) { diff --git a/src/logic/services/ServiceIndexService.cs b/src/logic/services/ServiceIndexService.cs index bc453e3..6053787 100644 --- a/src/logic/services/ServiceIndexService.cs +++ b/src/logic/services/ServiceIndexService.cs @@ -23,7 +23,7 @@ public RegistryServiceIndex(IUrlGenerator url) => _url = url ?? throw new ArgumentNullException(nameof(url)); private ServiceIndexItem BuildResource(string name, string url) => - new ServiceIndexItem + new() { ResourceUrl = url, Type = name, diff --git a/src/logic/services/searchs/FirestoreSearchService.cs b/src/logic/services/searchs/FirestoreSearchService.cs index dfb6db6..a781241 100644 --- a/src/logic/services/searchs/FirestoreSearchService.cs +++ b/src/logic/services/searchs/FirestoreSearchService.cs @@ -316,7 +316,7 @@ private async Task>> SearchInternalAsync( .ToList(); if (packages.Count == 0) - return new List>(); + return []; var segment = await packages.ToAsyncEnumerable() .Select(x => x.Collection("v")) @@ -332,7 +332,7 @@ private async Task>> SearchInternalAsync( if (lastPartitionKey != pkgID) { - results.Add(new List()); + results.Add([]); lastPartitionKey = pkgID; } diff --git a/src/logic/services/searchs/models/AutocompleteContext.cs b/src/logic/services/searchs/models/AutocompleteContext.cs index 4be4217..3bce63e 100644 --- a/src/logic/services/searchs/models/AutocompleteContext.cs +++ b/src/logic/services/searchs/models/AutocompleteContext.cs @@ -1,14 +1,14 @@ -namespace core.services.searchs.models; +namespace core.services.searchs.models; using Newtonsoft.Json; public class AutocompleteContext { - public static readonly AutocompleteContext Default = new AutocompleteContext + public static readonly AutocompleteContext Default = new() { Vocab = "http://schema.registry.vein-lang.org/schema#" }; [JsonProperty("@vocab")] public string Vocab { get; set; } -} \ No newline at end of file +} diff --git a/src/logic/services/searchs/models/SearchContext.cs b/src/logic/services/searchs/models/SearchContext.cs index e818787..3572929 100644 --- a/src/logic/services/searchs/models/SearchContext.cs +++ b/src/logic/services/searchs/models/SearchContext.cs @@ -4,7 +4,7 @@ namespace core.services.searchs.models; public class SearchContext { - public static SearchContext Default(string registrationBaseUrl) => new SearchContext + public static SearchContext Default(string registrationBaseUrl) => new() { Vocab = "http://schema.registry.vein-lang.org/schema#", Base = registrationBaseUrl diff --git a/src/profanity/Profanity.cs b/src/profanity/Profanity.cs index 25b7b49..6770ee3 100644 --- a/src/profanity/Profanity.cs +++ b/src/profanity/Profanity.cs @@ -19,26 +19,26 @@ public class Profanity // Characters for creating variants private readonly Dictionary> _charsMapping = - new Dictionary>() + new() { - { 'a', new List() { 'a', '@', '*', '4' } }, - { 'i', new List() { 'i', '*', 'l', '1' } }, - { 'o', new List() { 'o', '*', '0', '@' } }, - { 'u', new List() { 'u', '*', 'v' } }, - { 'v', new List() { 'v', '*', 'u' } }, - { 'l', new List() { 'l', '1' } }, - { 'e', new List() { 'e', '*', '3' } }, - { 's', new List() { 's', '$', '5' } } + { 'a', ['a', '@', '*', '4'] }, + { 'i', ['i', '*', 'l', '1'] }, + { 'o', ['o', '*', '0', '@'] }, + { 'u', ['u', '*', 'v'] }, + { 'v', ['v', '*', 'u'] }, + { 'l', ['l', '1'] }, + { 'e', ['e', '*', '3'] }, + { 's', ['s', '$', '5'] } }; // Data directory, in case the user wants to override the data path - private string dataDir = null; + private readonly string? dataDir = null; /// /// The profanity filter /// /// Optional directory to search for alphabetic_unicode.json and profanity_wordlist.txt in - public Profanity(string dataDir = null) + public Profanity(string? dataDir = null) { this.dataDir = dataDir; Utils.LoadUnicodeSymbols(dataDir); @@ -55,25 +55,10 @@ public Profanity(string dataDir = null) /// Sets the original behavior mode flag /// /// originalBehaviorMode value - public void SetOriginalBehaviorMode(bool value) - { - originalBehaviorMode = value; - } + public void SetOriginalBehaviorMode(bool value) => originalBehaviorMode = value; - private int CountNonAllowedCharacters(string word) - { - var count = 0; - - foreach (var c in word) - { - if (!Utils.AllowedCharacters.Contains(c.ToString())) - { - count++; - } - } - - return count; - } + private int CountNonAllowedCharacters(string word) + => word.Count(c => !Utils.AllowedCharacters.Contains(c.ToString())); /// /// Adds words to the censored word set. @@ -81,10 +66,7 @@ private int CountNonAllowedCharacters(string word) /// An IEnumerable of words to add public void AddCensorWords(IEnumerable newWords) { - foreach (var word in newWords) - { - CensorWordSet.Add(word); - } + foreach (var word in newWords) CensorWordSet.Add(word); } /// @@ -129,28 +111,16 @@ private List ReadWordList() .ToList(); } - private List GeneratePatternsFromWord(string word) + private IEnumerable GeneratePatternsFromWord(string word) { - var combos = new List>(); - foreach (var c in word) - { - combos.Add(!_charsMapping.ContainsKey(c) ? new List() { c } : _charsMapping[c]); - } - + var combos = word.Select(c => !_charsMapping.ContainsKey(c) ? [c] : _charsMapping[c]).ToList(); var product = combos.CartesianProduct(); return product.Select(combo => string.Join("", combo)).ToList(); } - private string GetReplacementForSwearWord(char censorChar, int count = 4) - { + private string GetReplacementForSwearWord(char censorChar, int count = 4) => // 4 is hardcoded for original behavior mode - if (originalBehaviorMode) - { - return new string(censorChar, 4); - } - - return new string(censorChar, count); - } + originalBehaviorMode ? new string(censorChar, 4) : new string(censorChar, count); /// /// Return true if the input text has any swear words. @@ -170,9 +140,7 @@ private string GetReplacementForSwearWord(char censorChar, int count = 4) { // Python: not set() = true if (wordsIndices == null || wordsIndices.Count < 1) - { wordsIndices = Utils.GetNextWords(text, startIndex, maxNumberCombinations); - } else { wordsIndices.RemoveRange(0, 2); @@ -300,7 +268,7 @@ public string Censor(string s, char censorChar = '*') public static class Utils { - public static readonly HashSet AllowedCharacters = new HashSet(); + public static readonly HashSet AllowedCharacters = []; /// /// Add ascii_letters, digits, and @$*"' to the allowed character list (AllowedCharacters). @@ -442,11 +410,11 @@ public static (bool, int) AnyNextWordsFormSwearWord(string curWord, string text, // Return an empty string if there are no other words if (nextWordStartIndex >= s.Length - 1) { - return new List<(string, int)>() - { - ("", nextWordStartIndex), - ("", nextWordStartIndex) - }; + return + [ + ("", nextWordStartIndex), + ("", nextWordStartIndex) + ]; } // Combine the words into a list