Skip to content

Commit

Permalink
Merge pull request #505 from fit-ctu-discord/update/2022.4.6
Browse files Browse the repository at this point in the history
Update 2022.4.6
  • Loading branch information
ostorc authored Jun 30, 2023
2 parents 8f0acd6 + 273b75e commit 8f41411
Show file tree
Hide file tree
Showing 18 changed files with 279 additions and 67 deletions.
2 changes: 0 additions & 2 deletions .github/ISSUE_TEMPLATE/bug_report.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
assignees: ostorc, tenhobi

---

**Describe the bug**
Expand Down
28 changes: 9 additions & 19 deletions .github/workflows/codeql-analysis.yml
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
name: "CodeQL"
name: "CodeQL"

on:
push:
branches: [ master ]
branches: [ main, develop ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ master ]
branches: [ main, develop ]
schedule:
- cron: '42 6 * * 1'
workflow_dispatch:
Expand All @@ -14,6 +14,12 @@ jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
timeout-minutes: 360

permissions:
actions: read
contents: read
security-events: write

strategy:
fail-fast: false
Expand All @@ -29,26 +35,10 @@ jobs:
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main

# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v2

# ℹ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl

# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language

#- run: |
# make bootstrap
# make release

- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
3 changes: 2 additions & 1 deletion .github/workflows/dotnet-core.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ on: [push, pull_request]

jobs:
build:

runs-on: ubuntu-latest
# a push event from the origin repo, or a PR from external repo
if: ${{ github.event_name == 'push' || github.event.pull_request.head.repo.full_name != 'fit-ctu-discord/honza-botner' }}

steps:
- uses: actions/checkout@v3
Expand Down
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project>
<PropertyGroup>
<Version>2022.4.5</Version>
<Version>2022.4.6</Version>
<TargetFramework>net7.0</TargetFramework>
<LangVersion>preview</LangVersion>
<Nullable>enable</Nullable>
Expand Down
22 changes: 11 additions & 11 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,27 @@
<ItemGroup>
<PackageVersion Include="Chronic.Core" Version="0.4.0" />
<PackageVersion Include="Cronos" Version="0.7.1" />
<PackageVersion Include="DSharpPlus" Version="4.4.0-nightly-01353 " />
<PackageVersion Include="DSharpPlus.Interactivity" Version="4.4.0-nightly-01353 " />
<PackageVersion Include="DSharpPlus.SlashCommands" Version="4.4.0-nightly-01353 " />
<PackageVersion Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="7.0.3" />
<PackageVersion Include="Microsoft.EntityFrameworkCore" Version="7.0.3" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.3" />
<PackageVersion Include="DSharpPlus" Version="4.4.2 " />
<PackageVersion Include="DSharpPlus.Interactivity" Version="4.4.2 " />
<PackageVersion Include="DSharpPlus.SlashCommands" Version="4.4.2 " />
<PackageVersion Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="7.0.8" />
<PackageVersion Include="Microsoft.EntityFrameworkCore" Version="7.0.8" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.8" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="7.0.0" />
<PackageVersion Include="Microsoft.Extensions.Hosting" Version="7.0.1" />
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="7.0.0" />
<PackageVersion Include="Microsoft.Extensions.Http" Version="7.0.0" />
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.1" />
<PackageVersion Include="Microsoft.Extensions.Options" Version="7.0.1" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.5.0" />
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.3" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.6.2" />
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.4" />
<PackageVersion Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageVersion Include="System.Collections.Immutable" Version="7.0.0" />
<PackageVersion Include="coverlet.collector" Version="3.2.0" />
<PackageVersion Include="coverlet.collector" Version="6.0.0" />
<PackageVersion Include="xunit" Version="2.4.2" />
<PackageVersion Include="xunit.runner.visualstudio" Version="2.4.5" />
<PackageVersion Include="Shouldly" Version="4.1.0" />
<PackageVersion Include="Shouldly" Version="4.2.1" />
<PackageVersion Include="Html2Markdown" Version="5.1.0.703" />
</ItemGroup>
</Project>
Binary file added docs/_assets/logo_server.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions src/HonzaBotner.Database/Mappers/VerificationMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,6 @@ public void Map(EntityTypeBuilder<Verification> builder)
builder.HasKey(v => v.UserId);
builder.HasIndex(v => v.AuthId)
.IsUnique(); // By default it is "IS UNIQUE IF NOT NULL"
builder.Property(v => v.Username).IsRequired(false);
}
}
2 changes: 2 additions & 0 deletions src/HonzaBotner.Database/Verification.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,7 @@ public class Verification
[Key] public ulong UserId { get; set; }
public string AuthId { get; set; }

public string Username { get; set; }

public override string ToString() => $"Discord: <@!{UserId}>, auth hash: {AuthId}";
}
8 changes: 4 additions & 4 deletions src/HonzaBotner.Discord.Services/Commands/MessageCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ public async Task SendMessageCommandAsync(
.WithContent(messageToSend.Content)
.WithAllowedMentions(mention ? Mentions.All : Mentions.None);

await channel.SendMessageAsync(content);
await ctx.CreateResponseAsync("Message sent");
DiscordMessage snt = await channel.SendMessageAsync(content);
await ctx.CreateResponseAsync("Message sent\n" + snt.JumpLink);
}
catch (Exception e)
{
Expand Down Expand Up @@ -84,8 +84,8 @@ public async Task EditMessageCommandAsync(

try
{
await oldMessage.ModifyAsync(content);
await ctx.CreateResponseAsync("Message successfully edited.");
DiscordMessage edited = await oldMessage.ModifyAsync(content);
await ctx.CreateResponseAsync("Message successfully edited.\n" + edited.JumpLink);
}
catch (Exception e)
{
Expand Down
17 changes: 3 additions & 14 deletions src/HonzaBotner.Discord.Services/Commands/ModerationCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -129,21 +129,10 @@ public async Task ListCommandAsync(

List<(string, string)> embedFields = allWarnings.ConvertAll(warning =>
{
DiscordMember? target = null;
DiscordMember? issuer = null;
try
{
issuer = ctx.Guild.GetMemberAsync(warning.IssuerId).Result;
target = ctx.Guild.GetMemberAsync(warning.UserId).Result;
}
catch (NotFoundException)
{
}

return ($"#{warning.Id}\t" +
$"{target?.DisplayName ?? warning.UserId.ToString()}\t" +
return ($"#{warning.Id}\t",
$"<@{warning.UserId}>\t" +
$"{warning.IssuedAt}\t" +
$"{issuer?.DisplayName ?? warning.IssuerId.ToString()}", warning.Reason);
$"<@{warning.IssuerId}>\n" + warning.Reason);
});

if (!embedFields.Any())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,9 @@ public static IEnumerable<Page> GeneratePages(this InteractivityExtension _,
foreach ((string name, string description) in items)
{
string descriptionValue = description;
if (description.Length > 250)
if (description.Length > 300)
{
descriptionValue = description.Substring(0, 250) + "...";
descriptionValue = description.Substring(0, 300) + "...";
}

embed.AddField(name, descriptionValue);
Expand Down
4 changes: 0 additions & 4 deletions src/HonzaBotner.Discord/DiscordBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@ private async Task Client_ClientError(DiscordClient sender, ClientErrorEventArgs
{
sender.Logger.LogError(e.Exception, "Exception occured");
await ReportException( "Client error", e.Exception);
e.Handled = true;
}

private Task Commands_CommandInvoked(SlashCommandsExtension e, SlashCommandInvokedEventArgs args)
Expand All @@ -100,15 +99,13 @@ private async Task Commands_CommandErrored(SlashCommandsExtension e, SlashComman
{
e.Client.Logger.LogError(args.Exception, "Exception occured while executing {Command}", args.Context.CommandName);
await ReportException($"SlashCommand {args.Context.CommandName}", args.Exception);
args.Handled = true;
await args.Context.Channel.SendMessageAsync("Something failed");
}

private async Task Commands_ContextMenuErrored(SlashCommandsExtension e, ContextMenuErrorEventArgs args)
{
e.Client.Logger.LogError(args.Exception, "Exception occured while executing context menu {ContextMenu}", args.Context.CommandName);
await ReportException($"ContextMenu {args.Context.CommandName}", args.Exception);
args.Handled = true;
await args.Context.Channel.SendMessageAsync("Something failed");
}

Expand All @@ -117,7 +114,6 @@ private async Task Commands_AutocompleteErrored(SlashCommandsExtension e, Autoco
e.Client.Logger.LogError(args.Exception, "Autocomplete failed while looking into option {OptionName}", args.Context.FocusedOption.Name);
await ReportException($"Command Autocomplete for option {args.Context.FocusedOption.Name}",
args.Exception);
args.Handled = true;
}

private Task Client_ComponentInteractionCreated(DiscordClient client, ComponentInteractionCreateEventArgs args)
Expand Down
8 changes: 6 additions & 2 deletions src/HonzaBotner.Discord/DiscordHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public static string GetMessageLink(ulong guild, ulong channel, ulong message)
public static async Task<DiscordMessage?> FindMessageFromLink(DiscordGuild guild, string link)
{
// Match the channel and message IDs.
const string pattern = @"https://discord(?:app)?\.com/channels/(?:\d+)/(\d+)/(\d+)/?";
const string pattern = @"https://(?:ptb\.|canary\.)?discord(?:app)?\.com/channels/(?:\d+)/(\d+)/(\d+)/?";
Regex regex = new Regex(pattern);
Match match = regex.Match(link);

Expand All @@ -45,7 +45,11 @@ public static string GetMessageLink(ulong guild, ulong channel, ulong message)

DiscordChannel? channel = guild.GetChannel(channelId);

if (channel.Type != ChannelType.Text) return null;
if (channel.Type != ChannelType.Text
&& channel.Type != ChannelType.GuildForum
&& channel.Type != ChannelType.NewsThread
&& channel.Type != ChannelType.PrivateThread
&& channel.Type != ChannelType.PublicThread) return null;

bool messageParseSuccess = ulong.TryParse(match.Groups[2].Value, out ulong messageId);
if (!messageParseSuccess) return null;
Expand Down
27 changes: 22 additions & 5 deletions src/HonzaBotner.Services/CvutAuthorizationService.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
Expand Down Expand Up @@ -49,8 +50,16 @@ RolesPool rolesPool
return IAuthorizationService.AuthorizeResult.AuthorizeFirst;

bool discordIdPresent = await IsUserVerified(userId);
UsermapPerson? person;
try
{
person = await _usermapInfoService.GetUserInfoAsync(accessToken, username);
}
catch
{
return IAuthorizationService.AuthorizeResult.Failed;
}

UsermapPerson? person = await _usermapInfoService.GetUserInfoAsync(accessToken, username);
if (person == null)
{
_logger.LogWarning("Couldn't fetch info from UserMap");
Expand All @@ -65,10 +74,10 @@ RolesPool rolesPool
// discord and auth -> update roles
if (discordIdPresent && authPresent)
{
bool verificationExists =
await _dbContext.Verifications.AnyAsync(v => v.UserId == userId && v.AuthId == authId);
Verification? verificationExists =
_dbContext.Verifications.FirstOrDefault(v => v.UserId == userId && v.AuthId == authId);

if (verificationExists)
if (verificationExists is not null)
{
bool revoked = await _roleManager.RevokeRolesPoolAsync(userId, rolesPool);
if (!revoked)
Expand All @@ -79,6 +88,14 @@ RolesPool rolesPool
}

bool granted = await _roleManager.GrantRolesAsync(userId, discordRoles);

if (verificationExists.Username is null)
{
verificationExists.Username = username;
_dbContext.Verifications.Update(verificationExists);
await _dbContext.SaveChangesAsync();
}

return granted
? IAuthorizationService.AuthorizeResult.OK
: IAuthorizationService.AuthorizeResult.Failed;
Expand All @@ -99,7 +116,7 @@ RolesPool rolesPool

if (rolesGranted)
{
Verification verification = new() { AuthId = authId, UserId = userId };
Verification verification = new() { AuthId = authId, UserId = userId, Username = person.Username };

await _dbContext.Verifications.AddAsync(verification);
await _dbContext.SaveChangesAsync();
Expand Down
Loading

0 comments on commit 8f41411

Please sign in to comment.