diff --git a/src/HonzaBotner.Discord.Services/Commands/EmoteCommands.cs b/src/HonzaBotner.Discord.Services/Commands/EmoteCommands.cs index 111a77a9..887965ed 100644 --- a/src/HonzaBotner.Discord.Services/Commands/EmoteCommands.cs +++ b/src/HonzaBotner.Discord.Services/Commands/EmoteCommands.cs @@ -59,20 +59,17 @@ public async Task EmoteStatsCommandAsync( continue; } - if (emoji.IsAnimated && type == DisplayTypes.Still) + switch (emoji.IsAnimated) { - continue; - } - - if (!emoji.IsAnimated && type == DisplayTypes.Animated) - { - continue; + case true when type == DisplayTypes.Still: + case false when type == DisplayTypes.Animated: + continue; } string label = total ? "×" : "×/day"; builder.Append(emoji) - .Append("`") + .Append('`') .Append( (total ? result.Used.ToString() diff --git a/src/HonzaBotner.Discord.Services/Commands/FunCommands.cs b/src/HonzaBotner.Discord.Services/Commands/FunCommands.cs index 06354c49..238a6fcc 100644 --- a/src/HonzaBotner.Discord.Services/Commands/FunCommands.cs +++ b/src/HonzaBotner.Discord.Services/Commands/FunCommands.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -21,7 +20,7 @@ public async Task ChooseCommandAsync( string delimiter = "," ) { - var answers = options.Split(delimiter, StringSplitOptions.TrimEntries & StringSplitOptions.RemoveEmptyEntries) + string[] answers = options.Split(delimiter) .Select(option => option.Trim().RemoveDiscordMentions(ctx.Guild)) .Where(option => option != "").ToArray(); if (answers.Length == 0) @@ -31,13 +30,13 @@ public async Task ChooseCommandAsync( } Random random = new(); var text = new StringBuilder("I picked: "); - var winNumber = random.Next(answers.Length); - var winner = answers[winNumber]; + int winNumber = random.Next(answers.Length); + string winner = answers[winNumber]; text.Append("`" + winner + "`"); if (answers.Length > 1) { text.Append("\nOptions were:\n"); - foreach (var option in answers) + foreach (string option in answers) { text.Append("`" + option+ "`, "); } diff --git a/src/HonzaBotner.Discord.Services/Commands/MemberCommands.cs b/src/HonzaBotner.Discord.Services/Commands/MemberCommands.cs index 4dcb2bc9..37edd206 100644 --- a/src/HonzaBotner.Discord.Services/Commands/MemberCommands.cs +++ b/src/HonzaBotner.Discord.Services/Commands/MemberCommands.cs @@ -1,6 +1,5 @@ using System; using System.Linq; -using System.Text; using System.Threading.Tasks; using DSharpPlus; using DSharpPlus.Entities; diff --git a/src/HonzaBotner.Discord.Services/Commands/ModerationCommands.cs b/src/HonzaBotner.Discord.Services/Commands/ModerationCommands.cs index ae380720..496249fd 100644 --- a/src/HonzaBotner.Discord.Services/Commands/ModerationCommands.cs +++ b/src/HonzaBotner.Discord.Services/Commands/ModerationCommands.cs @@ -33,7 +33,7 @@ public ModerationCommands(IWarningService warningService, ILogger. - AuthorMention = originalPoll.Description.Substring( - originalPoll.Description.LastIndexOf("<", StringComparison.Ordinal) - ); + AuthorMention = originalPoll.Description[startIndex..]; Question = originalPoll.Title; + NewChoices = new List(); } public async Task PostAsync(DiscordClient client, DiscordChannel channel) diff --git a/src/HonzaBotner.Discord.Services/EventHandlers/StaffVerificationEventHandler.cs b/src/HonzaBotner.Discord.Services/EventHandlers/StaffVerificationEventHandler.cs index ac628d9c..64fea284 100644 --- a/src/HonzaBotner.Discord.Services/EventHandlers/StaffVerificationEventHandler.cs +++ b/src/HonzaBotner.Discord.Services/EventHandlers/StaffVerificationEventHandler.cs @@ -52,7 +52,7 @@ public async Task Handle(ComponentInteractionCreateEventArgs DiscordUser user = eventArgs.User; DiscordMember member = await eventArgs.Guild.GetMemberAsync(user.Id); - var builder = new DiscordInteractionResponseBuilder().AsEphemeral(true); + var builder = new DiscordInteractionResponseBuilder().AsEphemeral(); // Check if the button to remove staff roles was pressed. if (eventArgs.Id == _buttonOptions.StaffRemoveRoleId) diff --git a/src/HonzaBotner.Discord.Services/EventHandlers/VerificationEventHandler.cs b/src/HonzaBotner.Discord.Services/EventHandlers/VerificationEventHandler.cs index f06d6d77..deee7883 100644 --- a/src/HonzaBotner.Discord.Services/EventHandlers/VerificationEventHandler.cs +++ b/src/HonzaBotner.Discord.Services/EventHandlers/VerificationEventHandler.cs @@ -41,7 +41,7 @@ public async Task Handle(ComponentInteractionCreateEventArgs _translation.SetLanguage(ITranslation.Language.Czech); } - DiscordInteractionResponseBuilder builder = new DiscordInteractionResponseBuilder().AsEphemeral(true); + DiscordInteractionResponseBuilder builder = new DiscordInteractionResponseBuilder().AsEphemeral(); DiscordUser user = eventArgs.User; DiscordMember member = await eventArgs.Guild.GetMemberAsync(user.Id); string link = _urlProvider.GetAuthLink(user.Id, RolesPool.Auth); diff --git a/src/HonzaBotner.Discord.Services/Extensions/DiscordExtensions.cs b/src/HonzaBotner.Discord.Services/Extensions/DiscordExtensions.cs index 35a4db72..890a88c0 100644 --- a/src/HonzaBotner.Discord.Services/Extensions/DiscordExtensions.cs +++ b/src/HonzaBotner.Discord.Services/Extensions/DiscordExtensions.cs @@ -62,23 +62,25 @@ public static IEnumerable GeneratePages(this InteractivityExtension _, string descriptionValue = description; if (description.Length > 250) { - descriptionValue = description.Substring(0, 250) + "..."; + descriptionValue = description[..250] + "..."; } embed.AddField(name, descriptionValue); item++; - if (item == pageRows || page * pageRows + item == items.Count) + if (item != pageRows && page * pageRows + item != items.Count) { - item = 0; - page++; - result.Add( - new Page("", - new DiscordEmbedBuilder(embed).WithFooter($"Page {page}/{pagesCount}") - ) - ); - embed.ClearFields(); + continue; } + + item = 0; + page++; + result.Add( + new Page("", + new DiscordEmbedBuilder(embed).WithFooter($"Page {page}/{pagesCount}") + ) + ); + embed.ClearFields(); } return result; diff --git a/src/HonzaBotner.Discord.Services/Extensions/StringExtensions.cs b/src/HonzaBotner.Discord.Services/Extensions/StringExtensions.cs index 17591923..58f5e796 100644 --- a/src/HonzaBotner.Discord.Services/Extensions/StringExtensions.cs +++ b/src/HonzaBotner.Discord.Services/Extensions/StringExtensions.cs @@ -1,5 +1,4 @@ -using System; -using System.Text.RegularExpressions; +using System.Text.RegularExpressions; using System.Threading.Tasks; using DSharpPlus.Entities; using DSharpPlus.Exceptions; @@ -36,26 +35,29 @@ public static string RemoveDiscordMentions( private static async Task MentionEvaluateAsync(Match match, DiscordGuild? guild) { // Invalidate ID pings, replacing them with their name (only in guilds) - if (guild is not null && match.Groups.TryGetValue("2", out Group? idMention) && idMention.Value != "") + if (guild is null || !match.Groups.TryGetValue("2", out Group? idMention) || idMention.Value == "") { - ulong snowflakeId = ulong.Parse(idMention.Value); + return match.Value.Replace("@", + "@" + char.ConvertFromUtf32(int.Parse("200b", System.Globalization.NumberStyles.HexNumber))); + } - if (match.Groups.TryGetValue("1", out Group? idType) && idType.Value == "&") - { - DiscordRole mentionedRole = guild.GetRole(snowflakeId); - if (mentionedRole is not null) - return mentionedRole.Name.RemoveDiscordMentions(); - } - else + ulong snowflakeId = ulong.Parse(idMention.Value); + + if (match.Groups.TryGetValue("1", out Group? idType) && idType.Value == "&") + { + DiscordRole mentionedRole = guild.GetRole(snowflakeId); + if (mentionedRole is not null) + return mentionedRole.Name.RemoveDiscordMentions(); + } + else + { + try { - try - { - DiscordMember mentionedMember = await guild.GetMemberAsync(snowflakeId); - return mentionedMember.DisplayName.RemoveDiscordMentions(); - } - catch (NotFoundException) - {} + DiscordMember mentionedMember = await guild.GetMemberAsync(snowflakeId); + return mentionedMember.DisplayName.RemoveDiscordMentions(); } + catch (NotFoundException) + {} } // Invalidate @everyone, @here, or pings which have correct ID format, but no name was found for them diff --git a/src/HonzaBotner.Discord.Services/Helpers/StandUpStats.cs b/src/HonzaBotner.Discord.Services/Helpers/StandUpStats.cs index 47e43af6..60fcd43d 100644 --- a/src/HonzaBotner.Discord.Services/Helpers/StandUpStats.cs +++ b/src/HonzaBotner.Discord.Services/Helpers/StandUpStats.cs @@ -19,7 +19,7 @@ public void Increment(string priority) } } - public int Sum => _normal + _must; + private int Sum => _normal + _must; public override string ToString() { diff --git a/src/HonzaBotner.Discord.Services/Jobs/NewsJobProvider.cs b/src/HonzaBotner.Discord.Services/Jobs/NewsJobProvider.cs index b62164f0..540f67d9 100644 --- a/src/HonzaBotner.Discord.Services/Jobs/NewsJobProvider.cs +++ b/src/HonzaBotner.Discord.Services/Jobs/NewsJobProvider.cs @@ -17,7 +17,7 @@ public class NewsJobProvider : IJob { private const int RunOffset = -3; - public string Name { get; } = "news-publisher"; + public string Name => "news-publisher"; private readonly ILogger _logger; private readonly INewsConfigService _configService; diff --git a/src/HonzaBotner.Discord.Services/Managers/ReminderManager.cs b/src/HonzaBotner.Discord.Services/Managers/ReminderManager.cs index 7e3e3e56..4d6a790d 100644 --- a/src/HonzaBotner.Discord.Services/Managers/ReminderManager.cs +++ b/src/HonzaBotner.Discord.Services/Managers/ReminderManager.cs @@ -4,19 +4,16 @@ using HonzaBotner.Discord.Services.Extensions; using HonzaBotner.Discord.Managers; using HonzaBotner.Services.Contract.Dto; -using Microsoft.Extensions.Logging; namespace HonzaBotner.Discord.Services.Managers; public class ReminderManager : IReminderManager { private readonly IGuildProvider _guildProvider; - private readonly ILogger _logger; - public ReminderManager(IGuildProvider guildProvider, ILogger logger) + public ReminderManager(IGuildProvider guildProvider) { _guildProvider = guildProvider; - _logger = logger; } public async Task CreateDmReminderEmbedAsync(Reminder reminder) diff --git a/src/HonzaBotner.Discord.Services/Managers/VoiceManager.cs b/src/HonzaBotner.Discord.Services/Managers/VoiceManager.cs index 9f8c37de..27d6ec8b 100644 --- a/src/HonzaBotner.Discord.Services/Managers/VoiceManager.cs +++ b/src/HonzaBotner.Discord.Services/Managers/VoiceManager.cs @@ -127,7 +127,7 @@ public async Task DeleteAllUnusedVoiceChannelsAsync() private string? ConvertStringToValidState(string? input, string? defaultValue = null) { input = Regex.Replace(input ?? "", @"\p{C}+", string.Empty); - return input.Trim().Length == 0 ? defaultValue : input.Substring(0, Math.Min(input.Length, 30)); + return input.Trim().Length == 0 ? defaultValue : input[..Math.Min(input.Length, 30)]; } private async Task EditChannelAsync(bool isEdit, DiscordChannel? channel, string? name, long? limit, diff --git a/src/HonzaBotner.Discord.Services/Publisher/DiscordEmvedPublisher.cs b/src/HonzaBotner.Discord.Services/Publisher/DiscordEmvedPublisher.cs index 9ec72ed4..24ab9741 100644 --- a/src/HonzaBotner.Discord.Services/Publisher/DiscordEmvedPublisher.cs +++ b/src/HonzaBotner.Discord.Services/Publisher/DiscordEmvedPublisher.cs @@ -28,7 +28,7 @@ private static string Limit(string str, int limit) return str; } - StringBuilder sb = new(str.Substring(0, limit - 1 - andMore.Length)); + StringBuilder sb = new(str [ ..(limit - 1 - andMore.Length)]); sb.Append(andMore); return sb.ToString(); @@ -42,7 +42,7 @@ public async Task Publish(News news, params ulong[] channels) { // Embed titles are limited to 256 characters Title = Limit(news.Title, 256), - Author = new DiscordEmbedBuilder.EmbedAuthor() + Author = new DiscordEmbedBuilder.EmbedAuthor { // The author name is limited to 256 characters Name = Limit(news.Author, 256) diff --git a/src/HonzaBotner.Discord.Services/Utils/Translation.cs b/src/HonzaBotner.Discord.Services/Utils/Translation.cs index a362945e..78b57728 100644 --- a/src/HonzaBotner.Discord.Services/Utils/Translation.cs +++ b/src/HonzaBotner.Discord.Services/Utils/Translation.cs @@ -69,11 +69,15 @@ public class Translation : ITranslation }, { "RemoveRolesButton", - new() { { ITranslation.Language.Czech, "Odebrat role" }, { ITranslation.Language.English, "Remove roles" } } + new Dictionary + { + { ITranslation.Language.Czech, "Odebrat role" }, + { ITranslation.Language.English, "Remove roles" } + } }, { "VerifyStaff", - new() + new Dictionary { { ITranslation.Language.Czech, "Ahoj, pro ověření rolí zaměstnance klikni na tlačítko." }, { ITranslation.Language.English, "Hi, click the button to verify the staff roles." } @@ -81,7 +85,7 @@ public class Translation : ITranslation }, { "AlreadyVerified", - new() + new Dictionary { { ITranslation.Language.Czech, "Ahoj, už jsi ověřený.\nPro aktualizaci rolí klikni na tlačítko." }, { diff --git a/src/HonzaBotner.Discord/Attributes/ICustomAttribute.cs b/src/HonzaBotner.Discord/Attributes/ICustomAttribute.cs deleted file mode 100644 index 100d66ce..00000000 --- a/src/HonzaBotner.Discord/Attributes/ICustomAttribute.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System.Threading.Tasks; -using DSharpPlus.Entities; - -namespace HonzaBotner.Discord.Attributes; - -public interface ICustomAttribute -{ - public Task BuildFailedCheckDiscordEmbed(); -} diff --git a/src/HonzaBotner.Discord/DiscordHelper.cs b/src/HonzaBotner.Discord/DiscordHelper.cs index 769b5fdd..657dcac9 100644 --- a/src/HonzaBotner.Discord/DiscordHelper.cs +++ b/src/HonzaBotner.Discord/DiscordHelper.cs @@ -7,21 +7,6 @@ namespace HonzaBotner.Discord; public static class DiscordHelper { - public static string GetMention(ulong authorId) - { - return $"<@{authorId}>"; - } - - public static string GetChannel(ulong channelId) - { - return $"<#{channelId}>"; - } - - public static string GetMessageLink(ulong guild, ulong channel, ulong message) - { - return $"https://discordapp.com/channels/{guild}/{channel}/{message}"; - } - /// /// Finds DiscordMessage from Discord link to message. /// @@ -32,7 +17,7 @@ public static string GetMessageLink(ulong guild, ulong channel, ulong message) { // Match the channel and message IDs. const string pattern = @"https://discord(?:app)?\.com/channels/(?:\d+)/(\d+)/(\d+)/?"; - Regex regex = new Regex(pattern); + Regex regex = new(pattern); Match match = regex.Match(link); // Malformed message link. diff --git a/src/HonzaBotner.Discord/Extensions/DiscordExtensions.cs b/src/HonzaBotner.Discord/Extensions/DiscordExtensions.cs index 17fd8c78..7ae0f82b 100644 --- a/src/HonzaBotner.Discord/Extensions/DiscordExtensions.cs +++ b/src/HonzaBotner.Discord/Extensions/DiscordExtensions.cs @@ -11,7 +11,7 @@ public static async Task ReportException(this DiscordChannel channel, string sou static string Truncate(string value, int maxLength) { if (string.IsNullOrEmpty(value)) return value; - return value.Length <= maxLength ? value : value.Substring(0, maxLength) + "..."; + return value.Length <= maxLength ? value : value[..maxLength] + "..."; } await channel.SendMessageAsync( diff --git a/src/HonzaBotner.Scheduler/CronJobWrapper.cs b/src/HonzaBotner.Scheduler/CronJobWrapper.cs index dc11f797..66ae8c4f 100644 --- a/src/HonzaBotner.Scheduler/CronJobWrapper.cs +++ b/src/HonzaBotner.Scheduler/CronJobWrapper.cs @@ -20,8 +20,8 @@ public CronJobWrapper(ICronJob job, string cronExpression, DateTime nextRunTime) public ICronJob Job { get; } private CronExpression Expression { get; } - public DateTime NextRunTime { get; private set; } - public DateTime LastRunTime { get; private set; } + private DateTime NextRunTime { get; set; } + private DateTime LastRunTime { get; set; } public void Next() { diff --git a/src/HonzaBotner.Services.Test/NewsConfigEnumsTest.cs b/src/HonzaBotner.Services.Test/NewsConfigEnumsTest.cs index c9ad54b3..1665ac99 100644 --- a/src/HonzaBotner.Services.Test/NewsConfigEnumsTest.cs +++ b/src/HonzaBotner.Services.Test/NewsConfigEnumsTest.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.Collections.Generic; using HonzaBotner.Services.Contract; using HonzaBotner.Services.Contract.Dto; @@ -27,7 +26,7 @@ public void NewsProviderToTypeTest(NewsProviderType newsProviderType) Type? t = Type.GetType(type); Assert.NotNull(t); - Assert.True(t!.IsAssignableTo(interfaceType)); + Assert.True(t.IsAssignableTo(interfaceType)); } public static IEnumerable GetPublisherEnums() @@ -48,6 +47,6 @@ public void PublisherToTypeTest(PublisherType publisherType) Type? t = Type.GetType(type); Assert.NotNull(t); - Assert.True(t!.IsAssignableTo(interfaceType)); + Assert.True(t.IsAssignableTo(interfaceType)); } -} \ No newline at end of file +} diff --git a/src/HonzaBotner.Services/CoursesNewsService.cs b/src/HonzaBotner.Services/CoursesNewsService.cs index 278829c0..23d1921b 100644 --- a/src/HonzaBotner.Services/CoursesNewsService.cs +++ b/src/HonzaBotner.Services/CoursesNewsService.cs @@ -2,13 +2,13 @@ using System.Collections.Generic; using System.Collections.Specialized; using System.Net.Http; +using System.Net.Http.Headers; using System.Text.Json; using System.Text.Json.Serialization; using HonzaBotner.Services.Contract; using HonzaBotner.Services.Contract.Dto; using Html2Markdown; using Html2Markdown.Scheme; -using Microsoft.Extensions.Logging; namespace HonzaBotner.Services; @@ -53,14 +53,12 @@ internal class Person #nullable enable private const string CoursesScope = "cvut:cpages:common:read"; - private readonly ILogger _logger; private readonly HttpClient _client; private readonly IAuthorizationService _authorizationService; - public CoursesNewsService(ILogger logger, HttpClient client, + public CoursesNewsService(HttpClient client, IAuthorizationService authorizationService) { - _logger = logger; _client = client; _authorizationService = authorizationService; } @@ -74,10 +72,7 @@ public async IAsyncEnumerable FetchDataAsync(string source, DateTime since NameValueCollection queryParams = new() { - //{ "access_token", accessToken }, - // type: { "default", "grouped", "jsonfeed" } { "type", "default" }, - // courses: BI-XY,BI-YZ,... { "courses", source }, { "limit", "50" }, { "since", since.AddDays(-1).ToString("yyyy-MM-dd") } @@ -90,7 +85,7 @@ public async IAsyncEnumerable FetchDataAsync(string source, DateTime since HttpRequestMessage requestMessage = new(HttpMethod.Get, uriBuilder.Uri) { - Headers = { Authorization = new("Bearer", accessToken) } + Headers = { Authorization = new AuthenticationHeaderValue("Bearer", accessToken) } }; HttpResponseMessage responseMessage = await _client.SendAsync(requestMessage); @@ -120,4 +115,4 @@ await JsonSerializer.DeserializeAsync(await responseMessage.Conte yield return new News(item.Url, item.CreatedBy.Name, item.Title, markdown, item.PublishedAt); } } -} \ No newline at end of file +} diff --git a/src/HonzaBotner.Services/CvutAuthorizationService.cs b/src/HonzaBotner.Services/CvutAuthorizationService.cs index d1efdea4..d5855cb1 100644 --- a/src/HonzaBotner.Services/CvutAuthorizationService.cs +++ b/src/HonzaBotner.Services/CvutAuthorizationService.cs @@ -68,23 +68,24 @@ RolesPool rolesPool bool verificationExists = await _dbContext.Verifications.AnyAsync(v => v.UserId == userId && v.AuthId == authId); - if (verificationExists) + if (!verificationExists) { - bool revoked = await _roleManager.RevokeRolesPoolAsync(userId, rolesPool); - if (!revoked) - { - _logger.LogWarning("Revoking roles pool {RolesPool} for {Username} (id {Id}) failed", userId, - username, rolesPool); - return IAuthorizationService.AuthorizeResult.Failed; - } - - bool granted = await _roleManager.GrantRolesAsync(userId, discordRoles); - return granted - ? IAuthorizationService.AuthorizeResult.OK - : IAuthorizationService.AuthorizeResult.Failed; + return IAuthorizationService.AuthorizeResult.DifferentMember; } - return IAuthorizationService.AuthorizeResult.DifferentMember; + bool revoked = await _roleManager.RevokeRolesPoolAsync(userId, rolesPool); + if (!revoked) + { + _logger.LogWarning("Revoking roles pool {RolesPool} for {Username} (id {Id}) failed", userId, + username, rolesPool); + return IAuthorizationService.AuthorizeResult.Failed; + } + + bool granted = await _roleManager.GrantRolesAsync(userId, discordRoles); + return granted + ? IAuthorizationService.AuthorizeResult.OK + : IAuthorizationService.AuthorizeResult.Failed; + } // discord xor auth -> user already verified, error @@ -97,17 +98,18 @@ RolesPool rolesPool { bool rolesGranted = await _roleManager.GrantRolesAsync(userId, discordRoles); - if (rolesGranted) + if (!rolesGranted) { - Verification verification = new() { AuthId = authId, UserId = userId }; - - await _dbContext.Verifications.AddAsync(verification); - await _dbContext.SaveChangesAsync(); - await _roleManager.RevokeHostRolesAsync(userId); - return IAuthorizationService.AuthorizeResult.OK; + return IAuthorizationService.AuthorizeResult.Failed; } - return IAuthorizationService.AuthorizeResult.Failed; + Verification verification = new() { AuthId = authId, UserId = userId }; + + await _dbContext.Verifications.AddAsync(verification); + await _dbContext.SaveChangesAsync(); + await _roleManager.RevokeHostRolesAsync(userId); + return IAuthorizationService.AuthorizeResult.OK; + } } @@ -192,12 +194,12 @@ public async Task GetServiceTokenAsync(string scope) UriBuilder uriBuilder = new(tokenUri); - List> contentValues = new() + List> contentValues = new() { - new("grant_type", "client_credentials"), - new("client_id", _cvutConfig.ServiceId), - new("client_secret", _cvutConfig.ServiceSecret), - new("scope", scope) + new KeyValuePair("grant_type", "client_credentials"), + new KeyValuePair("client_id", _cvutConfig.ServiceId ?? string.Empty), + new KeyValuePair("client_secret", _cvutConfig.ServiceSecret ?? string.Empty), + new KeyValuePair("scope", scope) }; FormUrlEncodedContent content = new(contentValues); diff --git a/src/HonzaBotner.Services/DiscordRoleManager.cs b/src/HonzaBotner.Services/DiscordRoleManager.cs index f0ef3e45..229299fe 100644 --- a/src/HonzaBotner.Services/DiscordRoleManager.cs +++ b/src/HonzaBotner.Services/DiscordRoleManager.cs @@ -126,12 +126,15 @@ public HashSet MapUsermapRoles(IReadOnlyCollection kosRoles { bool containsRole = kosRoles.Any(role => role.StartsWith(rolePrefix)); - if (containsRole) + if (!containsRole) { - foreach (DiscordRole role in roles[rolePrefix].Select(roleId => new DiscordRole(roleId))) - { - discordRoles.Add(role); - } + continue; + } + + + foreach (DiscordRole role in roles[rolePrefix].Select(roleId => new DiscordRole(roleId))) + { + discordRoles.Add(role); } } @@ -160,11 +163,11 @@ public async Task RevokeHostRolesAsync(ulong userId) public async Task IsUserDiscordAuthenticated(ulong userId) { - DiscordGuild _guild = await _guildProvider.GetCurrentGuildAsync(); + DiscordGuild guild = await _guildProvider.GetCurrentGuildAsync(); try { - DiscordMember member = await _guild.GetMemberAsync(userId); + DiscordMember member = await guild.GetMemberAsync(userId); if (_roleConfig.AuthenticatedRoleIds.Any(roleId => member.Roles.Select(role => role.Id).Contains(roleId))) { return true; diff --git a/src/HonzaBotner.Services/EmojiCounterService.cs b/src/HonzaBotner.Services/EmojiCounterService.cs index 92979ce7..cc001f5e 100644 --- a/src/HonzaBotner.Services/EmojiCounterService.cs +++ b/src/HonzaBotner.Services/EmojiCounterService.cs @@ -28,7 +28,7 @@ public async Task IncrementAsync(ulong emojiId) if (emoji == null) { - emoji = new Database.CountedEmoji() { Id = emojiId }; + emoji = new Database.CountedEmoji { Id = emojiId }; await _dbContext.CountedEmojis.AddAsync(emoji); } diff --git a/src/HonzaBotner.Services/Extensions.cs b/src/HonzaBotner.Services/Extensions.cs index e808c605..2181c94d 100644 --- a/src/HonzaBotner.Services/Extensions.cs +++ b/src/HonzaBotner.Services/Extensions.cs @@ -12,7 +12,6 @@ public static string GetQueryString(this NameValueCollection queryCollection) => public static DateTime SetKindUtc(this DateTime dateTime) { - if (dateTime.Kind == DateTimeKind.Utc) { return dateTime; } - return DateTime.SpecifyKind(dateTime, DateTimeKind.Utc); + return dateTime.Kind == DateTimeKind.Utc ? dateTime : DateTime.SpecifyKind(dateTime, DateTimeKind.Utc); } } diff --git a/src/HonzaBotner.Services/NewsConfigService.cs b/src/HonzaBotner.Services/NewsConfigService.cs index 79d26c3d..d6898c9f 100644 --- a/src/HonzaBotner.Services/NewsConfigService.cs +++ b/src/HonzaBotner.Services/NewsConfigService.cs @@ -82,7 +82,7 @@ private static Dto.NewsConfig DomainToDto(NewsConfig config) Dto.PublisherType publisherType = NewsConfigHelper.StringToEnum(config.PublisherType); - return new(config.Id, config.Name, config.Source, config.LastFetched, newsProviderType, + return new Dto.NewsConfig(config.Id, config.Name, config.Source, config.LastFetched, newsProviderType, publisherType, config.Active, config.Channels); } diff --git a/src/HonzaBotner.Services/RemindersService.cs b/src/HonzaBotner.Services/RemindersService.cs index 6ea9c064..89ad3d10 100644 --- a/src/HonzaBotner.Services/RemindersService.cs +++ b/src/HonzaBotner.Services/RemindersService.cs @@ -56,10 +56,7 @@ public async Task DeleteReminderAsync(int id) .Where(reminder => reminder.MessageId == messageId) .FirstOrDefaultAsync(); - if (reminder == null) - return null; - - return GetDto(reminder); + return reminder == null ? null : GetDto(reminder); } public async Task> GetRemindersToExecuteAsync(DateTime? dateTime) diff --git a/src/HonzaBotner.Services/Sha256HashService.cs b/src/HonzaBotner.Services/Sha256HashService.cs index f4a0d81a..2213df2d 100644 --- a/src/HonzaBotner.Services/Sha256HashService.cs +++ b/src/HonzaBotner.Services/Sha256HashService.cs @@ -9,11 +9,11 @@ public class Sha256HashService : IHashService { public string Hash(string input) { - var encLen = (input.Length + 1) * 3; + int encLen = (input.Length + 1) * 3; var enc = encLen <= 1024 ? stackalloc byte[encLen] : new byte[encLen]; Span bytes = stackalloc byte[256 / 8]; - var len = Encoding.UTF8.GetBytes(input, enc); + int len = Encoding.UTF8.GetBytes(input, enc); SHA256.HashData(enc[..len], bytes); return Convert.ToHexString(bytes).ToLower(); diff --git a/src/HonzaBotner.Services/WarningService.cs b/src/HonzaBotner.Services/WarningService.cs index f9f9dc0c..a7fd6904 100644 --- a/src/HonzaBotner.Services/WarningService.cs +++ b/src/HonzaBotner.Services/WarningService.cs @@ -37,10 +37,7 @@ public async Task> GetWarningsAsync(ulong userId) Database.Warning? warning = await _dbContext.Warnings .FirstOrDefaultAsync(w => w.Id == id); - if (warning == null) - return null; - - return GetDto(warning); + return warning == null ? null : GetDto(warning); } public async Task DeleteWarningAsync(int id) diff --git a/src/HonzaBotner/Controllers/AuthController.cs b/src/HonzaBotner/Controllers/AuthController.cs index 270558cf..8d256602 100644 --- a/src/HonzaBotner/Controllers/AuthController.cs +++ b/src/HonzaBotner/Controllers/AuthController.cs @@ -86,7 +86,7 @@ public async Task Callback() } } - private bool GetRolesPool(string? value, out RolesPool rolesPool) + private static bool GetRolesPool(string? value, out RolesPool rolesPool) { switch (value?.ToLowerInvariant()) { diff --git a/src/HonzaBotner/Controllers/BaseController.cs b/src/HonzaBotner/Controllers/BaseController.cs index f768d68d..842444e7 100644 --- a/src/HonzaBotner/Controllers/BaseController.cs +++ b/src/HonzaBotner/Controllers/BaseController.cs @@ -6,9 +6,9 @@ namespace HonzaBotner.Controllers; public abstract class BaseController : Controller { - protected readonly IOptions _options; + private readonly IOptions _options; - public BaseController(IOptions options) + protected BaseController(IOptions options) { _options = options; } @@ -17,7 +17,7 @@ protected ActionResult Page(string message, int code) { Response.StatusCode = code; - bool success = code >= 200 && code < 300; + bool success = code is >= 200 and < 300; string content = string.Format( System.IO.File.ReadAllText("Static/auth.html"), diff --git a/src/HonzaBotner/PsqlConnectionStringParser.cs b/src/HonzaBotner/PsqlConnectionStringParser.cs index 37a6dcb4..5a2ff707 100644 --- a/src/HonzaBotner/PsqlConnectionStringParser.cs +++ b/src/HonzaBotner/PsqlConnectionStringParser.cs @@ -10,7 +10,7 @@ internal static string GetEFConnectionString(string connectionUrl) if (isUrl && url != null) { return - $"host={url.Host};username={url.UserInfo.Split(':')[0]};password={url.UserInfo.Split(':')[1]};database={url.LocalPath.Substring(1)};Pooling=true;SSL Mode=Require;Trust Server Certificate=True;"; + $"host={url.Host};username={url.UserInfo.Split(':')[0]};password={url.UserInfo.Split(':')[1]};database={url.LocalPath[1..]};Pooling=true;SSL Mode=Require;Trust Server Certificate=True;"; } return connectionUrl;