feat: upgrade to .NET 6, refactor everything

This commit is contained in:
spiral
2021-11-26 21:10:56 -05:00
parent d28e99ba43
commit 1918c56937
314 changed files with 27954 additions and 27966 deletions

View File

@@ -1,25 +1,24 @@
#nullable enable
using PluralKit.Core;
namespace PluralKit.Bot
namespace PluralKit.Bot;
public struct ProxyMatch
{
public struct ProxyMatch
public ProxyMember Member;
public string? Content;
public ProxyTag? ProxyTags;
public string? ProxyContent
{
public ProxyMember Member;
public string? Content;
public ProxyTag? ProxyTags;
public string? ProxyContent
get
{
get
{
// Add the proxy tags into the proxied message if that option is enabled
// Also check if the member has any proxy tags - some cases autoproxy can return a member with no tags
if (Member.KeepProxy && Content != null && ProxyTags != null)
return $"{ProxyTags.Value.Prefix}{Content}{ProxyTags.Value.Suffix}";
// Add the proxy tags into the proxied message if that option is enabled
// Also check if the member has any proxy tags - some cases autoproxy can return a member with no tags
if (Member.KeepProxy && Content != null && ProxyTags != null)
return $"{ProxyTags.Value.Prefix}{Content}{ProxyTags.Value.Suffix}";
return Content;
}
return Content;
}
}
}

View File

@@ -1,108 +1,114 @@
using System.Collections.Generic;
using System.Linq;
using NodaTime;
using PluralKit.Core;
namespace PluralKit.Bot
namespace PluralKit.Bot;
public class ProxyMatcher
{
public class ProxyMatcher
private static readonly char AutoproxyEscapeCharacter = '\\';
public static readonly Duration DefaultLatchExpiryTime = Duration.FromHours(6);
private readonly IClock _clock;
private readonly ProxyTagParser _parser;
public ProxyMatcher(ProxyTagParser parser, IClock clock)
{
private static readonly char AutoproxyEscapeCharacter = '\\';
public static readonly Duration DefaultLatchExpiryTime = Duration.FromHours(6);
_parser = parser;
_clock = clock;
}
private readonly IClock _clock;
private readonly ProxyTagParser _parser;
public bool TryMatch(MessageContext ctx, IReadOnlyCollection<ProxyMember> members, out ProxyMatch match,
string messageContent,
bool hasAttachments, bool allowAutoproxy)
{
if (TryMatchTags(members, messageContent, hasAttachments, out match)) return true;
if (allowAutoproxy && TryMatchAutoproxy(ctx, members, messageContent, out match)) return true;
return false;
}
public ProxyMatcher(ProxyTagParser parser, IClock clock)
private bool TryMatchTags(IReadOnlyCollection<ProxyMember> members, string messageContent, bool hasAttachments,
out ProxyMatch match)
{
if (!_parser.TryMatch(members, messageContent, out match)) return false;
// Edge case: If we got a match with blank inner text, we'd normally just send w/ attachments
// However, if there are no attachments, the user probably intended something else, so we "un-match" and proceed to autoproxy
return hasAttachments || match.Content.Trim().Length > 0;
}
private bool TryMatchAutoproxy(MessageContext ctx, IReadOnlyCollection<ProxyMember> members,
string messageContent,
out ProxyMatch match)
{
match = default;
// Skip autoproxy match if we hit the escape character
if (messageContent.StartsWith(AutoproxyEscapeCharacter))
throw new ProxyService.ProxyChecksFailedException(
"This message matches none of your proxy tags, and it was not autoproxied because it starts with a backslash (`\\`).");
// Find the member we should autoproxy (null if none)
var member = ctx.AutoproxyMode switch
{
_parser = parser;
_clock = clock;
AutoproxyMode.Member when ctx.AutoproxyMember != null =>
members.FirstOrDefault(m => m.Id == ctx.AutoproxyMember),
AutoproxyMode.Front when ctx.LastSwitchMembers.Length > 0 =>
members.FirstOrDefault(m => m.Id == ctx.LastSwitchMembers[0]),
AutoproxyMode.Latch when ctx.LastMessageMember != null =>
members.FirstOrDefault(m => m.Id == ctx.LastMessageMember.Value),
_ => null
};
// Throw an error if the member is null, message varies depending on autoproxy mode
if (member == null)
{
if (ctx.AutoproxyMode == AutoproxyMode.Front)
throw new ProxyService.ProxyChecksFailedException(
"You are using autoproxy front, but no members are currently registered as fronting. Please use `pk;switch <member>` to log a new switch.");
if (ctx.AutoproxyMode == AutoproxyMode.Member)
throw new ProxyService.ProxyChecksFailedException(
"You are using member-specific autoproxy with an invalid member. Was this member deleted?");
if (ctx.AutoproxyMode == AutoproxyMode.Latch)
throw new ProxyService.ProxyChecksFailedException(
"You are using autoproxy latch, but have not sent any messages yet in this server. Please send a message using proxy tags first.");
throw new ProxyService.ProxyChecksFailedException(
"This message matches none of your proxy tags and autoproxy is not enabled.");
}
public bool TryMatch(MessageContext ctx, IReadOnlyCollection<ProxyMember> members, out ProxyMatch match, string messageContent,
bool hasAttachments, bool allowAutoproxy)
if (ctx.AutoproxyMode != AutoproxyMode.Member && !member.AllowAutoproxy)
throw new ProxyService.ProxyChecksFailedException(
"This member has autoproxy disabled. To enable it, use `pk;m <member> autoproxy on`.");
// Moved the IsLatchExpired() check to here, so that an expired latch and a latch without any previous messages throw different errors
if (ctx.AutoproxyMode == AutoproxyMode.Latch && IsLatchExpired(ctx))
throw new ProxyService.ProxyChecksFailedException(
"Latch-mode autoproxy has timed out. Please send a new message using proxy tags.");
match = new ProxyMatch
{
if (TryMatchTags(members, messageContent, hasAttachments, out match)) return true;
if (allowAutoproxy && TryMatchAutoproxy(ctx, members, messageContent, out match)) return true;
return false;
}
Content = messageContent,
Member = member,
private bool TryMatchTags(IReadOnlyCollection<ProxyMember> members, string messageContent, bool hasAttachments, out ProxyMatch match)
{
if (!_parser.TryMatch(members, messageContent, out match)) return false;
// We're autoproxying, so not using any proxy tags here
// we just find the first pair of tags (if any), otherwise null
ProxyTags = member.ProxyTags.FirstOrDefault()
};
return true;
}
// Edge case: If we got a match with blank inner text, we'd normally just send w/ attachments
// However, if there are no attachments, the user probably intended something else, so we "un-match" and proceed to autoproxy
return hasAttachments || match.Content.Trim().Length > 0;
}
private bool IsLatchExpired(MessageContext ctx)
{
if (ctx.LastMessage == null) return true;
if (ctx.LatchTimeout == 0) return false;
private bool TryMatchAutoproxy(MessageContext ctx, IReadOnlyCollection<ProxyMember> members, string messageContent,
out ProxyMatch match)
{
match = default;
var timeout = ctx.LatchTimeout.HasValue
? Duration.FromSeconds(ctx.LatchTimeout.Value)
: DefaultLatchExpiryTime;
// Skip autoproxy match if we hit the escape character
if (messageContent.StartsWith(AutoproxyEscapeCharacter))
throw new ProxyService.ProxyChecksFailedException("This message matches none of your proxy tags, and it was not autoproxied because it starts with a backslash (`\\`).");
// Find the member we should autoproxy (null if none)
var member = ctx.AutoproxyMode switch
{
AutoproxyMode.Member when ctx.AutoproxyMember != null =>
members.FirstOrDefault(m => m.Id == ctx.AutoproxyMember),
AutoproxyMode.Front when ctx.LastSwitchMembers.Length > 0 =>
members.FirstOrDefault(m => m.Id == ctx.LastSwitchMembers[0]),
AutoproxyMode.Latch when ctx.LastMessageMember != null =>
members.FirstOrDefault(m => m.Id == ctx.LastMessageMember.Value),
_ => null
};
// Throw an error if the member is null, message varies depending on autoproxy mode
if (member == null)
{
if (ctx.AutoproxyMode == AutoproxyMode.Front)
throw new ProxyService.ProxyChecksFailedException("You are using autoproxy front, but no members are currently registered as fronting. Please use `pk;switch <member>` to log a new switch.");
else if (ctx.AutoproxyMode == AutoproxyMode.Member)
throw new ProxyService.ProxyChecksFailedException("You are using member-specific autoproxy with an invalid member. Was this member deleted?");
else if (ctx.AutoproxyMode == AutoproxyMode.Latch)
throw new ProxyService.ProxyChecksFailedException("You are using autoproxy latch, but have not sent any messages yet in this server. Please send a message using proxy tags first.");
throw new ProxyService.ProxyChecksFailedException("This message matches none of your proxy tags and autoproxy is not enabled.");
}
if (ctx.AutoproxyMode != AutoproxyMode.Member && !member.AllowAutoproxy)
throw new ProxyService.ProxyChecksFailedException("This member has autoproxy disabled. To enable it, use `pk;m <member> autoproxy on`.");
// Moved the IsLatchExpired() check to here, so that an expired latch and a latch without any previous messages throw different errors
if (ctx.AutoproxyMode == AutoproxyMode.Latch && IsLatchExpired(ctx))
throw new ProxyService.ProxyChecksFailedException("Latch-mode autoproxy has timed out. Please send a new message using proxy tags.");
match = new ProxyMatch
{
Content = messageContent,
Member = member,
// We're autoproxying, so not using any proxy tags here
// we just find the first pair of tags (if any), otherwise null
ProxyTags = member.ProxyTags.FirstOrDefault()
};
return true;
}
private bool IsLatchExpired(MessageContext ctx)
{
if (ctx.LastMessage == null) return true;
if (ctx.LatchTimeout == 0) return false;
var timeout = ctx.LatchTimeout.HasValue
? Duration.FromSeconds(ctx.LatchTimeout.Value)
: DefaultLatchExpiryTime;
var timestamp = DiscordUtils.SnowflakeToInstant(ctx.LastMessage.Value);
return _clock.GetCurrentInstant() - timestamp > timeout;
}
var timestamp = DiscordUtils.SnowflakeToInstant(ctx.LastMessage.Value);
return _clock.GetCurrentInstant() - timestamp > timeout;
}
}

View File

@@ -1,9 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using App.Metrics;
@@ -19,364 +15,374 @@ using PluralKit.Core;
using Serilog;
namespace PluralKit.Bot
namespace PluralKit.Bot;
public class ProxyService
{
public class ProxyService
private static readonly TimeSpan MessageDeletionDelay = TimeSpan.FromMilliseconds(1000);
private readonly IDiscordCache _cache;
private readonly IDatabase _db;
private readonly DispatchService _dispatch;
private readonly LastMessageCacheService _lastMessage;
private readonly LogChannelService _logChannel;
private readonly ILogger _logger;
private readonly ProxyMatcher _matcher;
private readonly IMetrics _metrics;
private readonly ModelRepository _repo;
private readonly DiscordApiClient _rest;
private readonly WebhookExecutorService _webhookExecutor;
public ProxyService(LogChannelService logChannel, ILogger logger, WebhookExecutorService webhookExecutor,
DispatchService dispatch, IDatabase db, ProxyMatcher matcher, IMetrics metrics, ModelRepository repo,
IDiscordCache cache, DiscordApiClient rest, LastMessageCacheService lastMessage)
{
private static readonly TimeSpan MessageDeletionDelay = TimeSpan.FromMilliseconds(1000);
_logChannel = logChannel;
_webhookExecutor = webhookExecutor;
_dispatch = dispatch;
_db = db;
_matcher = matcher;
_metrics = metrics;
_repo = repo;
_cache = cache;
_lastMessage = lastMessage;
_rest = rest;
_logger = logger.ForContext<ProxyService>();
}
private readonly LogChannelService _logChannel;
private readonly IDatabase _db;
private readonly ModelRepository _repo;
private readonly ILogger _logger;
private readonly WebhookExecutorService _webhookExecutor;
private readonly DispatchService _dispatch;
private readonly ProxyMatcher _matcher;
private readonly IMetrics _metrics;
private readonly IDiscordCache _cache;
private readonly LastMessageCacheService _lastMessage;
private readonly DiscordApiClient _rest;
public async Task<bool> HandleIncomingMessage(Shard shard, MessageCreateEvent message, MessageContext ctx,
Guild guild, Channel channel, bool allowAutoproxy, PermissionSet botPermissions)
{
if (!ShouldProxy(channel, message, ctx))
return false;
public ProxyService(LogChannelService logChannel, ILogger logger, WebhookExecutorService webhookExecutor, DispatchService dispatch, IDatabase db,
ProxyMatcher matcher, IMetrics metrics, ModelRepository repo, IDiscordCache cache, DiscordApiClient rest, LastMessageCacheService lastMessage)
{
_logChannel = logChannel;
_webhookExecutor = webhookExecutor;
_dispatch = dispatch;
_db = db;
_matcher = matcher;
_metrics = metrics;
_repo = repo;
_cache = cache;
_lastMessage = lastMessage;
_rest = rest;
_logger = logger.ForContext<ProxyService>();
}
var rootChannel = await _cache.GetRootChannel(message.ChannelId);
public async Task<bool> HandleIncomingMessage(Shard shard, MessageCreateEvent message, MessageContext ctx, Guild guild, Channel channel, bool allowAutoproxy, PermissionSet botPermissions)
{
if (!ShouldProxy(channel, message, ctx))
return false;
List<ProxyMember> members;
// Fetch members and try to match to a specific member
using (_metrics.Measure.Timer.Time(BotMetrics.ProxyMembersQueryTime))
members = (await _repo.GetProxyMembers(message.Author.Id, message.GuildId!.Value)).ToList();
var rootChannel = await _cache.GetRootChannel(message.ChannelId);
List<ProxyMember> members;
// Fetch members and try to match to a specific member
using (_metrics.Measure.Timer.Time(BotMetrics.ProxyMembersQueryTime))
members = (await _repo.GetProxyMembers(message.Author.Id, message.GuildId!.Value)).ToList();
if (!_matcher.TryMatch(ctx, members, out var match, message.Content, message.Attachments.Length > 0,
if (!_matcher.TryMatch(ctx, members, out var match, message.Content, message.Attachments.Length > 0,
allowAutoproxy)) return false;
// this is hopefully temporary, so not putting it into a separate method
if (message.Content != null && message.Content.Length > 2000) throw new PKError("PluralKit cannot proxy messages over 2000 characters in length.");
// this is hopefully temporary, so not putting it into a separate method
if (message.Content != null && message.Content.Length > 2000)
throw new PKError("PluralKit cannot proxy messages over 2000 characters in length.");
// Permission check after proxy match so we don't get spammed when not actually proxying
if (!await CheckBotPermissionsOrError(botPermissions, rootChannel.Id))
return false;
// Permission check after proxy match so we don't get spammed when not actually proxying
if (!await CheckBotPermissionsOrError(botPermissions, rootChannel.Id))
return false;
// this method throws, so no need to wrap it in an if statement
CheckProxyNameBoundsOrError(match.Member.ProxyName(ctx));
// this method throws, so no need to wrap it in an if statement
CheckProxyNameBoundsOrError(match.Member.ProxyName(ctx));
// Check if the sender account can mention everyone/here + embed links
// we need to "mirror" these permissions when proxying to prevent exploits
var senderPermissions = PermissionExtensions.PermissionsFor(guild, rootChannel, message);
var allowEveryone = senderPermissions.HasFlag(PermissionSet.MentionEveryone);
var allowEmbeds = senderPermissions.HasFlag(PermissionSet.EmbedLinks);
// Check if the sender account can mention everyone/here + embed links
// we need to "mirror" these permissions when proxying to prevent exploits
var senderPermissions = PermissionExtensions.PermissionsFor(guild, rootChannel, message);
var allowEveryone = senderPermissions.HasFlag(PermissionSet.MentionEveryone);
var allowEmbeds = senderPermissions.HasFlag(PermissionSet.EmbedLinks);
// Everything's in order, we can execute the proxy!
await ExecuteProxy(shard, message, ctx, match, allowEveryone, allowEmbeds);
return true;
}
// Everything's in order, we can execute the proxy!
await ExecuteProxy(shard, message, ctx, match, allowEveryone, allowEmbeds);
return true;
}
public bool ShouldProxy(Channel channel, Message msg, MessageContext ctx)
public bool ShouldProxy(Channel channel, Message msg, MessageContext ctx)
{
// Make sure author has a system
if (ctx.SystemId == null)
throw new ProxyChecksFailedException(Errors.NoSystemError.Message);
// Make sure channel is a guild text channel and this is a normal message
if (!DiscordUtils.IsValidGuildChannel(channel))
throw new ProxyChecksFailedException("This channel is not a text channel.");
if (msg.Type != Message.MessageType.Default && msg.Type != Message.MessageType.Reply)
throw new ProxyChecksFailedException("This message is not a normal message.");
// Make sure author is a normal user
if (msg.Author.System == true || msg.Author.Bot || msg.WebhookId != null)
throw new ProxyChecksFailedException("This message was not sent by a normal user.");
// Make sure proxying is enabled here
if (ctx.InBlacklist)
throw new ProxyChecksFailedException(
"Proxying was disabled in this channel by a server administrator (via the proxy blacklist).");
// Make sure the system has proxying enabled in the server
if (!ctx.ProxyEnabled)
throw new ProxyChecksFailedException(
"Your system has proxying disabled in this server. Type `pk;proxy on` to enable it.");
// Make sure we have either an attachment or message content
var isMessageBlank = msg.Content == null || msg.Content.Trim().Length == 0;
if (isMessageBlank && msg.Attachments.Length == 0)
throw new ProxyChecksFailedException("Message cannot be blank.");
// All good!
return true;
}
private async Task ExecuteProxy(Shard shard, Message trigger, MessageContext ctx,
ProxyMatch match, bool allowEveryone, bool allowEmbeds)
{
// Create reply embed
var embeds = new List<Embed>();
if (trigger.Type == Message.MessageType.Reply && trigger.MessageReference?.ChannelId == trigger.ChannelId)
{
// Make sure author has a system
if (ctx.SystemId == null)
throw new ProxyChecksFailedException(Errors.NoSystemError.Message);
// Make sure channel is a guild text channel and this is a normal message
if (!DiscordUtils.IsValidGuildChannel(channel))
throw new ProxyChecksFailedException("This channel is not a text channel.");
if (msg.Type != Message.MessageType.Default && msg.Type != Message.MessageType.Reply)
throw new ProxyChecksFailedException("This message is not a normal message.");
// Make sure author is a normal user
if (msg.Author.System == true || msg.Author.Bot || msg.WebhookId != null)
throw new ProxyChecksFailedException("This message was not sent by a normal user.");
// Make sure proxying is enabled here
if (ctx.InBlacklist)
throw new ProxyChecksFailedException($"Proxying was disabled in this channel by a server administrator (via the proxy blacklist).");
// Make sure the system has proxying enabled in the server
if (!ctx.ProxyEnabled)
throw new ProxyChecksFailedException("Your system has proxying disabled in this server. Type `pk;proxy on` to enable it.");
// Make sure we have either an attachment or message content
var isMessageBlank = msg.Content == null || msg.Content.Trim().Length == 0;
if (isMessageBlank && msg.Attachments.Length == 0)
throw new ProxyChecksFailedException("Message cannot be blank.");
// All good!
return true;
}
private async Task ExecuteProxy(Shard shard, Message trigger, MessageContext ctx,
ProxyMatch match, bool allowEveryone, bool allowEmbeds)
{
// Create reply embed
var embeds = new List<Embed>();
if (trigger.Type == Message.MessageType.Reply && trigger.MessageReference?.ChannelId == trigger.ChannelId)
var repliedTo = trigger.ReferencedMessage.Value;
if (repliedTo != null)
{
var repliedTo = trigger.ReferencedMessage.Value;
if (repliedTo != null)
{
var (nickname, avatar) = await FetchReferencedMessageAuthorInfo(trigger, repliedTo);
var embed = CreateReplyEmbed(match, trigger, repliedTo, nickname, avatar);
if (embed != null)
embeds.Add(embed);
}
// TODO: have a clean error for when message can't be fetched instead of just being silent
var (nickname, avatar) = await FetchReferencedMessageAuthorInfo(trigger, repliedTo);
var embed = CreateReplyEmbed(match, trigger, repliedTo, nickname, avatar);
if (embed != null)
embeds.Add(embed);
}
// Send the webhook
var content = match.ProxyContent;
if (!allowEmbeds) content = content.BreakLinkEmbeds();
var messageChannel = await _cache.GetChannel(trigger.ChannelId);
var rootChannel = await _cache.GetRootChannel(trigger.ChannelId);
var threadId = messageChannel.IsThread() ? messageChannel.Id : (ulong?)null;
var guild = await _cache.GetGuild(trigger.GuildId.Value);
var proxyMessage = await _webhookExecutor.ExecuteWebhook(new ProxyRequest
{
GuildId = trigger.GuildId!.Value,
ChannelId = rootChannel.Id,
ThreadId = threadId,
Name = await FixSameName(messageChannel.Id, ctx, match.Member),
AvatarUrl = AvatarUtils.TryRewriteCdnUrl(match.Member.ProxyAvatar(ctx)),
Content = content,
Attachments = trigger.Attachments,
FileSizeLimit = guild.FileSizeLimit(),
Embeds = embeds.ToArray(),
AllowEveryone = allowEveryone,
});
await HandleProxyExecutedActions(shard, ctx, trigger, proxyMessage, match);
// TODO: have a clean error for when message can't be fetched instead of just being silent
}
private async Task<(string?, string?)> FetchReferencedMessageAuthorInfo(Message trigger, Message referenced)
{
if (referenced.WebhookId != null)
return (null, null);
// Send the webhook
var content = match.ProxyContent;
if (!allowEmbeds) content = content.BreakLinkEmbeds();
try
{
var member = await _rest.GetGuildMember(trigger.GuildId!.Value, referenced.Author.Id);
return (member?.Nick, member?.Avatar);
}
catch (ForbiddenException)
{
_logger.Warning("Failed to fetch member {UserId} in guild {GuildId} when getting reply nickname, falling back to username",
referenced.Author.Id, trigger.GuildId!.Value);
return (null, null);
}
var messageChannel = await _cache.GetChannel(trigger.ChannelId);
var rootChannel = await _cache.GetRootChannel(trigger.ChannelId);
var threadId = messageChannel.IsThread() ? messageChannel.Id : (ulong?)null;
var guild = await _cache.GetGuild(trigger.GuildId.Value);
var proxyMessage = await _webhookExecutor.ExecuteWebhook(new ProxyRequest
{
GuildId = trigger.GuildId!.Value,
ChannelId = rootChannel.Id,
ThreadId = threadId,
Name = await FixSameName(messageChannel.Id, ctx, match.Member),
AvatarUrl = AvatarUtils.TryRewriteCdnUrl(match.Member.ProxyAvatar(ctx)),
Content = content,
Attachments = trigger.Attachments,
FileSizeLimit = guild.FileSizeLimit(),
Embeds = embeds.ToArray(),
AllowEveryone = allowEveryone
});
await HandleProxyExecutedActions(shard, ctx, trigger, proxyMessage, match);
}
private async Task<(string?, string?)> FetchReferencedMessageAuthorInfo(Message trigger, Message referenced)
{
if (referenced.WebhookId != null)
return (null, null);
try
{
var member = await _rest.GetGuildMember(trigger.GuildId!.Value, referenced.Author.Id);
return (member?.Nick, member?.Avatar);
}
private Embed CreateReplyEmbed(ProxyMatch match, Message trigger, Message repliedTo, string? nickname, string? avatar)
catch (ForbiddenException)
{
// repliedTo doesn't have a GuildId field :/
var jumpLink = $"https://discord.com/channels/{trigger.GuildId}/{repliedTo.ChannelId}/{repliedTo.Id}";
var content = new StringBuilder();
var hasContent = !string.IsNullOrWhiteSpace(repliedTo.Content);
if (hasContent)
{
var msg = repliedTo.Content;
if (msg.Length > 100)
{
msg = repliedTo.Content.Substring(0, 100);
var endsWithOpenMention = Regex.IsMatch(msg, @"<[at]?[@#:][!&]?(\w+:)?(\d+)?(:[tTdDfFR])?$");
if (endsWithOpenMention)
{
var mentionTail = repliedTo.Content.Substring(100).Split(">")[0];
if (repliedTo.Content.Contains(msg + mentionTail + ">"))
msg += mentionTail + ">";
}
var endsWithUrl = Regex.IsMatch(msg,
@"(http|https)(:\/\/)?(www\.)?([-a-zA-Z0-9@:%._\+~#=]{1,256})?\.?([a-zA-Z0-9()]{1,6})?\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$");
if (endsWithUrl)
{
var urlTail = repliedTo.Content.Substring(100).Split(" ")[0];
msg += urlTail + " ";
}
var spoilersInOriginalString = Regex.Matches(repliedTo.Content, @"\|\|").Count;
var spoilersInTruncatedString = Regex.Matches(msg, @"\|\|").Count;
if (spoilersInTruncatedString % 2 == 1 && spoilersInOriginalString % 2 == 0)
msg += "||";
if (msg != repliedTo.Content)
msg += "…";
}
content.Append($"**[Reply to:]({jumpLink})** ");
content.Append(msg);
if (repliedTo.Attachments.Length > 0)
content.Append($" {Emojis.Paperclip}");
}
else
{
content.Append($"*[(click to see attachment)]({jumpLink})*");
}
var username = nickname ?? repliedTo.Author.Username;
var avatarUrl = avatar != null
? $"https://cdn.discordapp.com/guilds/{trigger.GuildId}/users/{repliedTo.Author.Id}/avatars/{avatar}.png"
: $"https://cdn.discordapp.com/avatars/{repliedTo.Author.Id}/{repliedTo.Author.Avatar}.png";
return new Embed
{
// unicodes: [three-per-em space] [left arrow emoji] [force emoji presentation]
Author = new($"{username}\u2004\u21a9\ufe0f", IconUrl: avatarUrl),
Description = content.ToString(),
Color = match.Member.Color?.ToDiscordColor(),
};
}
private async Task<string> FixSameName(ulong channelId, MessageContext ctx, ProxyMember member)
{
var proxyName = member.ProxyName(ctx);
var lastMessage = _lastMessage.GetLastMessage(channelId)?.Previous;
if (lastMessage == null)
// cache is out of date or channel is empty.
return proxyName;
var pkMessage = await _db.Execute(conn => _repo.GetMessage(conn, lastMessage.Id));
if (lastMessage.AuthorUsername == proxyName)
{
// last message wasn't proxied by us, but somehow has the same name
// it's probably from a different webhook (Tupperbox?) but let's fix it anyway!
if (pkMessage == null)
return FixSameNameInner(proxyName);
// last message was proxied by a different member
if (pkMessage.Member.Id != member.Id)
return FixSameNameInner(proxyName);
}
// if we fixed the name last message and it's the same member proxying, we want to fix it again
if (lastMessage.AuthorUsername == FixSameNameInner(proxyName) && pkMessage?.Member.Id == member.Id)
return FixSameNameInner(proxyName);
// No issues found, current proxy name is fine.
return proxyName;
}
private string FixSameNameInner(string name)
=> $"{name}\u17b5";
private async Task HandleProxyExecutedActions(Shard shard, MessageContext ctx,
Message triggerMessage, Message proxyMessage,
ProxyMatch match)
{
var sentMessage = new PKMessage
{
Channel = triggerMessage.ChannelId,
Guild = triggerMessage.GuildId,
Member = match.Member.Id,
Mid = proxyMessage.Id,
OriginalMid = triggerMessage.Id,
Sender = triggerMessage.Author.Id
};
Task SaveMessageInDatabase()
=> _repo.AddMessage(sentMessage);
Task LogMessageToChannel() => _logChannel.LogMessage(ctx, sentMessage, triggerMessage, proxyMessage).AsTask();
Task DispatchWebhook() => _dispatch.Dispatch(ctx.SystemId.Value, sentMessage);
async Task DeleteProxyTriggerMessage()
{
// Wait a second or so before deleting the original message
await Task.Delay(MessageDeletionDelay);
try
{
await _rest.DeleteMessage(triggerMessage.ChannelId, triggerMessage.Id);
}
catch (NotFoundException)
{
_logger.Debug("Trigger message {TriggerMessageId} was already deleted when we attempted to; deleting proxy message {ProxyMessageId} also",
triggerMessage.Id, proxyMessage.Id);
await HandleTriggerAlreadyDeleted(proxyMessage);
// Swallow the exception, we don't need it
}
}
// Run post-proxy actions (simultaneously; order doesn't matter)
await Task.WhenAll(
DeleteProxyTriggerMessage(),
SaveMessageInDatabase(),
LogMessageToChannel(),
DispatchWebhook()
);
}
private async Task HandleTriggerAlreadyDeleted(Message proxyMessage)
{
// If a trigger message is deleted before we get to delete it, we can assume a mod bot or similar got to it
// In this case we should also delete the now-proxied message.
// This is going to hit the message delete event handler also, so that'll do the cleanup for us
try
{
await _rest.DeleteMessage(proxyMessage.ChannelId, proxyMessage.Id);
}
catch (NotFoundException) { }
catch (UnauthorizedException) { }
}
private async Task<bool> CheckBotPermissionsOrError(PermissionSet permissions, ulong responseChannel)
{
// If we can't send messages at all, just bail immediately.
// 2020-04-22: Manage Messages does *not* override a lack of Send Messages.
if (!permissions.HasFlag(PermissionSet.SendMessages))
return false;
if (!permissions.HasFlag(PermissionSet.ManageWebhooks))
{
// todo: PKError-ify these
await _rest.CreateMessage(responseChannel, new MessageRequest
{
Content = $"{Emojis.Error} PluralKit does not have the *Manage Webhooks* permission in this channel, and thus cannot proxy messages. Please contact a server administrator to remedy this."
});
return false;
}
if (!permissions.HasFlag(PermissionSet.ManageMessages))
{
await _rest.CreateMessage(responseChannel, new MessageRequest
{
Content = $"{Emojis.Error} PluralKit does not have the *Manage Messages* permission in this channel, and thus cannot delete the original trigger message. Please contact a server administrator to remedy this."
});
return false;
}
return true;
}
private void CheckProxyNameBoundsOrError(string proxyName)
{
if (proxyName.Length > Limits.MaxProxyNameLength) throw Errors.ProxyNameTooLong(proxyName);
}
public class ProxyChecksFailedException: Exception
{
public ProxyChecksFailedException(string message) : base(message) { }
_logger.Warning(
"Failed to fetch member {UserId} in guild {GuildId} when getting reply nickname, falling back to username",
referenced.Author.Id, trigger.GuildId!.Value);
return (null, null);
}
}
private Embed CreateReplyEmbed(ProxyMatch match, Message trigger, Message repliedTo, string? nickname,
string? avatar)
{
// repliedTo doesn't have a GuildId field :/
var jumpLink = $"https://discord.com/channels/{trigger.GuildId}/{repliedTo.ChannelId}/{repliedTo.Id}";
var content = new StringBuilder();
var hasContent = !string.IsNullOrWhiteSpace(repliedTo.Content);
if (hasContent)
{
var msg = repliedTo.Content;
if (msg.Length > 100)
{
msg = repliedTo.Content.Substring(0, 100);
var endsWithOpenMention = Regex.IsMatch(msg, @"<[at]?[@#:][!&]?(\w+:)?(\d+)?(:[tTdDfFR])?$");
if (endsWithOpenMention)
{
var mentionTail = repliedTo.Content.Substring(100).Split(">")[0];
if (repliedTo.Content.Contains(msg + mentionTail + ">"))
msg += mentionTail + ">";
}
var endsWithUrl = Regex.IsMatch(msg,
@"(http|https)(:\/\/)?(www\.)?([-a-zA-Z0-9@:%._\+~#=]{1,256})?\.?([a-zA-Z0-9()]{1,6})?\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$");
if (endsWithUrl)
{
var urlTail = repliedTo.Content.Substring(100).Split(" ")[0];
msg += urlTail + " ";
}
var spoilersInOriginalString = Regex.Matches(repliedTo.Content, @"\|\|").Count;
var spoilersInTruncatedString = Regex.Matches(msg, @"\|\|").Count;
if (spoilersInTruncatedString % 2 == 1 && spoilersInOriginalString % 2 == 0)
msg += "||";
if (msg != repliedTo.Content)
msg += "…";
}
content.Append($"**[Reply to:]({jumpLink})** ");
content.Append(msg);
if (repliedTo.Attachments.Length > 0)
content.Append($" {Emojis.Paperclip}");
}
else
{
content.Append($"*[(click to see attachment)]({jumpLink})*");
}
var username = nickname ?? repliedTo.Author.Username;
var avatarUrl = avatar != null
? $"https://cdn.discordapp.com/guilds/{trigger.GuildId}/users/{repliedTo.Author.Id}/avatars/{avatar}.png"
: $"https://cdn.discordapp.com/avatars/{repliedTo.Author.Id}/{repliedTo.Author.Avatar}.png";
return new Embed
{
// unicodes: [three-per-em space] [left arrow emoji] [force emoji presentation]
Author = new Embed.EmbedAuthor($"{username}\u2004\u21a9\ufe0f", IconUrl: avatarUrl),
Description = content.ToString(),
Color = match.Member.Color?.ToDiscordColor()
};
}
private async Task<string> FixSameName(ulong channelId, MessageContext ctx, ProxyMember member)
{
var proxyName = member.ProxyName(ctx);
var lastMessage = _lastMessage.GetLastMessage(channelId)?.Previous;
if (lastMessage == null)
// cache is out of date or channel is empty.
return proxyName;
var pkMessage = await _db.Execute(conn => _repo.GetMessage(conn, lastMessage.Id));
if (lastMessage.AuthorUsername == proxyName)
{
// last message wasn't proxied by us, but somehow has the same name
// it's probably from a different webhook (Tupperbox?) but let's fix it anyway!
if (pkMessage == null)
return FixSameNameInner(proxyName);
// last message was proxied by a different member
if (pkMessage.Member.Id != member.Id)
return FixSameNameInner(proxyName);
}
// if we fixed the name last message and it's the same member proxying, we want to fix it again
if (lastMessage.AuthorUsername == FixSameNameInner(proxyName) && pkMessage?.Member.Id == member.Id)
return FixSameNameInner(proxyName);
// No issues found, current proxy name is fine.
return proxyName;
}
private string FixSameNameInner(string name)
=> $"{name}\u17b5";
private async Task HandleProxyExecutedActions(Shard shard, MessageContext ctx,
Message triggerMessage, Message proxyMessage, ProxyMatch match)
{
var sentMessage = new PKMessage
{
Channel = triggerMessage.ChannelId,
Guild = triggerMessage.GuildId,
Member = match.Member.Id,
Mid = proxyMessage.Id,
OriginalMid = triggerMessage.Id,
Sender = triggerMessage.Author.Id
};
Task SaveMessageInDatabase()
=> _repo.AddMessage(sentMessage);
Task LogMessageToChannel() =>
_logChannel.LogMessage(ctx, sentMessage, triggerMessage, proxyMessage).AsTask();
Task DispatchWebhook() => _dispatch.Dispatch(ctx.SystemId.Value, sentMessage);
async Task DeleteProxyTriggerMessage()
{
// Wait a second or so before deleting the original message
await Task.Delay(MessageDeletionDelay);
try
{
await _rest.DeleteMessage(triggerMessage.ChannelId, triggerMessage.Id);
}
catch (NotFoundException)
{
_logger.Debug(
"Trigger message {TriggerMessageId} was already deleted when we attempted to; deleting proxy message {ProxyMessageId} also",
triggerMessage.Id, proxyMessage.Id);
await HandleTriggerAlreadyDeleted(proxyMessage);
// Swallow the exception, we don't need it
}
}
// Run post-proxy actions (simultaneously; order doesn't matter)
await Task.WhenAll(
DeleteProxyTriggerMessage(),
SaveMessageInDatabase(),
LogMessageToChannel(),
DispatchWebhook()
);
}
private async Task HandleTriggerAlreadyDeleted(Message proxyMessage)
{
// If a trigger message is deleted before we get to delete it, we can assume a mod bot or similar got to it
// In this case we should also delete the now-proxied message.
// This is going to hit the message delete event handler also, so that'll do the cleanup for us
try
{
await _rest.DeleteMessage(proxyMessage.ChannelId, proxyMessage.Id);
}
catch (NotFoundException) { }
catch (UnauthorizedException) { }
}
private async Task<bool> CheckBotPermissionsOrError(PermissionSet permissions, ulong responseChannel)
{
// If we can't send messages at all, just bail immediately.
// 2020-04-22: Manage Messages does *not* override a lack of Send Messages.
if (!permissions.HasFlag(PermissionSet.SendMessages))
return false;
if (!permissions.HasFlag(PermissionSet.ManageWebhooks))
{
// todo: PKError-ify these
await _rest.CreateMessage(responseChannel, new MessageRequest
{
Content = $"{Emojis.Error} PluralKit does not have the *Manage Webhooks* permission in this channel, and thus cannot proxy messages."
+ " Please contact a server administrator to remedy this."
});
return false;
}
if (!permissions.HasFlag(PermissionSet.ManageMessages))
{
await _rest.CreateMessage(responseChannel, new MessageRequest
{
Content = $"{Emojis.Error} PluralKit does not have the *Manage Messages* permission in this channel, and thus cannot delete the original trigger message."
+ " Please contact a server administrator to remedy this."
});
return false;
}
return true;
}
private void CheckProxyNameBoundsOrError(string proxyName)
{
if (proxyName.Length > Limits.MaxProxyNameLength) throw Errors.ProxyNameTooLong(proxyName);
}
public class ProxyChecksFailedException: Exception
{
public ProxyChecksFailedException(string message) : base(message) { }
}
}

View File

@@ -1,97 +1,94 @@
#nullable enable
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using PluralKit.Core;
namespace PluralKit.Bot
namespace PluralKit.Bot;
public class ProxyTagParser
{
public class ProxyTagParser
private readonly Regex prefixPattern = new(@"^<(?:@!?|#|@&|a?:[\d\w_]+?:)\d+>");
private readonly Regex suffixPattern = new(@"<(?:@!?|#|@&|a?:[\d\w_]+?:)\d+>$");
public bool TryMatch(IEnumerable<ProxyMember> members, string? input, out ProxyMatch result)
{
private Regex prefixPattern = new Regex(@"^<(?:@!?|#|@&|a?:[\d\w_]+?:)\d+>");
private Regex suffixPattern = new Regex(@"<(?:@!?|#|@&|a?:[\d\w_]+?:)\d+>$");
result = default;
public bool TryMatch(IEnumerable<ProxyMember> members, string? input, out ProxyMatch result)
// Null input is valid and is equivalent to empty string
if (input == null) return false;
// If the message starts with a @mention, and then proceeds to have proxy tags,
// extract the mention and place it inside the inner message
// eg. @Ske [text] => [@Ske text]
var leadingMention = ExtractLeadingMention(ref input);
// "Flatten" list of members to a list of tag-member pairs
// Then order them by "tag specificity"
// (prefix+suffix length desc = inner message asc = more specific proxy first)
var tags = members
.SelectMany(member => member.ProxyTags.Select(tag => (tag, member)))
.OrderByDescending(p => p.tag.ProxyString.Length);
// Iterate now-ordered list of tags and try matching each one
foreach (var (tag, member) in tags)
{
result = default;
result.ProxyTags = tag;
result.Member = member;
// Null input is valid and is equivalent to empty string
if (input == null) return false;
// Skip blank tags (shouldn't ever happen in practice)
if (tag.Prefix == null && tag.Suffix == null) continue;
// If the message starts with a @mention, and then proceeds to have proxy tags,
// extract the mention and place it inside the inner message
// eg. @Ske [text] => [@Ske text]
var leadingMention = ExtractLeadingMention(ref input);
if (tag.Prefix == "<" && prefixPattern.IsMatch(input)) continue;
if (tag.Suffix == ">" && suffixPattern.IsMatch(input)) continue;
// "Flatten" list of members to a list of tag-member pairs
// Then order them by "tag specificity"
// (prefix+suffix length desc = inner message asc = more specific proxy first)
var tags = members
.SelectMany(member => member.ProxyTags.Select(tag => (tag, member)))
.OrderByDescending(p => p.tag.ProxyString.Length);
// Iterate now-ordered list of tags and try matching each one
foreach (var (tag, member) in tags)
// Can we match with these tags?
if (TryMatchTagsInner(input, tag, out result.Content))
{
result.ProxyTags = tag;
result.Member = member;
// Skip blank tags (shouldn't ever happen in practice)
if (tag.Prefix == null && tag.Suffix == null) continue;
if (tag.Prefix == "<" && prefixPattern.IsMatch(input)) continue;
if (tag.Suffix == ">" && suffixPattern.IsMatch(input)) continue;
// Can we match with these tags?
if (TryMatchTagsInner(input, tag, out result.Content))
{
// If we extracted a leading mention before, add that back now
if (leadingMention != null) result.Content = $"{leadingMention} {result.Content}";
return true;
}
// (if not, keep going)
// If we extracted a leading mention before, add that back now
if (leadingMention != null) result.Content = $"{leadingMention} {result.Content}";
return true;
}
// We couldn't match anything :(
return false;
// (if not, keep going)
}
private bool TryMatchTagsInner(string input, ProxyTag tag, out string inner)
{
inner = "";
// We couldn't match anything :(
return false;
}
// Normalize null tags to empty strings
var prefix = tag.Prefix ?? "";
var suffix = tag.Suffix ?? "";
private bool TryMatchTagsInner(string input, ProxyTag tag, out string inner)
{
inner = "";
// Check if our input starts/ends with the tags
var isMatch = input.Length >= prefix.Length + suffix.Length
&& input.StartsWith(prefix) && input.EndsWith(suffix);
// Normalize null tags to empty strings
var prefix = tag.Prefix ?? "";
var suffix = tag.Suffix ?? "";
// Special case: image-only proxies + proxy tags with spaces
// Trim everything, then see if we have a "contentless tag pair" (normally disallowed, but OK if we have an attachment)
// Note `input` is still "", even if there are spaces between
if (!isMatch && input.Trim() == prefix.TrimEnd() + suffix.TrimStart())
return true;
if (!isMatch) return false;
// Check if our input starts/ends with the tags
var isMatch = input.Length >= prefix.Length + suffix.Length
&& input.StartsWith(prefix) && input.EndsWith(suffix);
// We got a match, extract inner text
inner = input.Substring(prefix.Length, input.Length - prefix.Length - suffix.Length);
// Special case: image-only proxies + proxy tags with spaces
// Trim everything, then see if we have a "contentless tag pair" (normally disallowed, but OK if we have an attachment)
// Note `input` is still "", even if there are spaces between
if (!isMatch && input.Trim() == prefix.TrimEnd() + suffix.TrimStart())
return true;
if (!isMatch) return false;
// (see https://github.com/xSke/PluralKit/pull/181)
return inner.Trim() != "\U0000fe0f";
}
// We got a match, extract inner text
inner = input.Substring(prefix.Length, input.Length - prefix.Length - suffix.Length);
private string? ExtractLeadingMention(ref string input)
{
var mentionPos = 0;
if (!DiscordUtils.HasMentionPrefix(input, ref mentionPos, out _)) return null;
// (see https://github.com/xSke/PluralKit/pull/181)
return inner.Trim() != "\U0000fe0f";
}
var leadingMention = input.Substring(0, mentionPos);
input = input.Substring(mentionPos);
return leadingMention;
}
private string? ExtractLeadingMention(ref string input)
{
var mentionPos = 0;
if (!DiscordUtils.HasMentionPrefix(input, ref mentionPos, out _)) return null;
var leadingMention = input.Substring(0, mentionPos);
input = input.Substring(mentionPos);
return leadingMention;
}
}