Refactor proxy handling code

- Move reaction handlers to the ReactionAdded event instead of
  ProxyService
- Split tag matching off into ProxyTagParser
- Split autoproxy matching off into Autoproxier
- General cleanup and simplification
This commit is contained in:
Ske
2020-06-11 23:20:46 +02:00
parent 4a4d980349
commit 49acc4d9e2
13 changed files with 492 additions and 395 deletions

View File

@@ -0,0 +1,93 @@
#nullable enable
using System;
using System.Linq;
using System.Threading.Tasks;
using NodaTime;
using PluralKit.Core;
namespace PluralKit.Bot
{
public class Autoproxier
{
public static readonly string EscapeString = @"\";
public static readonly Duration AutoproxyExpiryTime = Duration.FromHours(6);
private IClock _clock;
private IDataStore _data;
public Autoproxier(IDataStore data, IClock clock)
{
_data = data;
_clock = clock;
}
public async ValueTask<ProxyMatch?> TryAutoproxy(AutoproxyContext ctx)
{
if (IsEscaped(ctx.Content))
return null;
var member = await FindAutoproxyMember(ctx);
if (member == null) return null;
return new ProxyMatch
{
Content = ctx.Content,
Member = member,
ProxyTags = ProxyTagsFor(member)
};
}
private async ValueTask<PKMember?> FindAutoproxyMember(AutoproxyContext ctx)
{
switch (ctx.Mode)
{
case AutoproxyMode.Off:
return null;
case AutoproxyMode.Front:
return await _data.GetFirstFronter(ctx.Account.System);
case AutoproxyMode.Latch:
// Latch mode: find last proxied message, use *that* member
var msg = await _data.GetLastMessageInGuild(ctx.SenderId, ctx.GuildId);
if (msg == null) return null; // No message found
// If the message is older than 6 hours, ignore it and force the sender to "refresh" a proxy
// This can be revised in the future, it's a preliminary value.
var timestamp = DiscordUtils.SnowflakeToInstant(msg.Message.Mid);
if (_clock.GetCurrentInstant() - timestamp > AutoproxyExpiryTime) return null;
return msg.Member;
case AutoproxyMode.Member:
// We already have the member list cached, so:
// O(n) lookup since n is small (max 1500 de jure) and we're more constrained by memory (for a dictionary) here
return ctx.Account.Members.FirstOrDefault(m => m.Id == ctx.AutoproxyMember);
default:
throw new ArgumentOutOfRangeException($"Unknown autoproxy mode {ctx.Mode}");
}
}
private ProxyTag? ProxyTagsFor(PKMember member)
{
if (member.ProxyTags.Count == 0) return null;
return member.ProxyTags.First();
}
private bool IsEscaped(string message) => message.TrimStart().StartsWith(EscapeString);
public struct AutoproxyContext
{
public CachedAccount Account;
public string Content;
public AutoproxyMode Mode;
public int? AutoproxyMember;
public ulong SenderId;
public ulong GuildId;
}
}
}

View File

@@ -0,0 +1,25 @@
#nullable enable
using PluralKit.Core;
namespace PluralKit.Bot
{
public struct ProxyMatch
{
public PKMember Member;
public string? Content;
public ProxyTag? ProxyTags;
public string? ProxyContent
{
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}";
return Content;
}
}
}
}

View File

@@ -0,0 +1,145 @@
using System;
using System.Threading.Tasks;
using DSharpPlus;
using DSharpPlus.Entities;
using DSharpPlus.Exceptions;
using PluralKit.Core;
using Serilog;
namespace PluralKit.Bot
{
public class ProxyService {
public static readonly TimeSpan MessageDeletionDelay = TimeSpan.FromMilliseconds(1000);
private LogChannelService _logChannel;
private IDataStore _data;
private ILogger _logger;
private WebhookExecutorService _webhookExecutor;
private ProxyTagParser _parser;
private Autoproxier _autoproxier;
public ProxyService(LogChannelService logChannel, IDataStore data, ILogger logger, WebhookExecutorService webhookExecutor, ProxyTagParser parser, Autoproxier autoproxier)
{
_logChannel = logChannel;
_data = data;
_webhookExecutor = webhookExecutor;
_parser = parser;
_autoproxier = autoproxier;
_logger = logger.ForContext<ProxyService>();
}
public async Task<ProxyMatch?> TryGetMatch(DiscordMessage message, SystemGuildSettings systemGuildSettings, CachedAccount account, bool allowAutoproxy)
{
// First, try parsing by tags
if (_parser.TryParse(message.Content, account.Members, out var tagMatch))
{
// If the content is blank (and we don't have any attachments), someone just sent a message that happens
// to be equal to someone else's tags. This doesn't count! Proceed to autoproxy in that case.
var isEdgeCase = tagMatch.Content.Trim().Length == 0 && message.Attachments.Count == 0;
if (!isEdgeCase) return tagMatch;
}
// Then, if AP is enabled, try finding an autoproxy match
if (allowAutoproxy)
return await _autoproxier.TryAutoproxy(new Autoproxier.AutoproxyContext
{
Account = account,
AutoproxyMember = systemGuildSettings.AutoproxyMember,
Content = message.Content,
GuildId = message.Channel.GuildId,
Mode = systemGuildSettings.AutoproxyMode,
SenderId = message.Author.Id
});
// Didn't find anything :(
return null;
}
public async Task HandleMessageAsync(DiscordClient client, GuildConfig guild, CachedAccount account, DiscordMessage message, bool allowAutoproxy)
{
// Early checks
if (message.Channel.Guild == null) return;
if (guild.Blacklist.Contains(message.ChannelId)) return;
var systemSettingsForGuild = account.SettingsForGuild(message.Channel.GuildId);
if (!systemSettingsForGuild.ProxyEnabled) return;
if (!await EnsureBotPermissions(message.Channel)) return;
// Find a proxy match (either with tags or autoproxy), bail if we couldn't find any
if (!(await TryGetMatch(message, systemSettingsForGuild, account, allowAutoproxy) is { } match))
return;
// Can't proxy a message with no content and no attachment
if (match.Content.Trim().Length == 0 && message.Attachments.Count == 0)
return;
var memberSettingsForGuild = account.SettingsForMemberGuild(match.Member.Id, message.Channel.GuildId);
// Find and check proxied name
var proxyName = match.Member.ProxyName(account.System.Tag, memberSettingsForGuild.DisplayName);
if (proxyName.Length < 2) throw Errors.ProxyNameTooShort(proxyName);
if (proxyName.Length > Limits.MaxProxyNameLength) throw Errors.ProxyNameTooLong(proxyName);
// Find proxy avatar (server avatar -> member avatar -> system avatar)
var proxyAvatar = memberSettingsForGuild.AvatarUrl ?? match.Member.AvatarUrl ?? account.System.AvatarUrl;
// Execute the webhook!
var hookMessage = await _webhookExecutor.ExecuteWebhook(message.Channel, proxyName, proxyAvatar,
await SanitizeEveryoneMaybe(message, match.ProxyContent),
message.Attachments
);
// Store the message in the database, and log it in the log channel (if applicable)
await _data.AddMessage(message.Author.Id, hookMessage, message.Channel.GuildId, message.Channel.Id, message.Id, match.Member);
await _logChannel.LogMessage(client, account.System, match.Member, hookMessage, message.Id, message.Channel, message.Author, match.Content, guild);
// Wait a second or so before deleting the original message
await Task.Delay(MessageDeletionDelay);
try
{
await message.DeleteAsync();
}
catch (NotFoundException)
{
// If it's already deleted, we just log and swallow the exception
_logger.Warning("Attempted to delete already deleted proxy trigger message {Message}", message.Id);
}
}
private static async Task<string> SanitizeEveryoneMaybe(DiscordMessage message,
string messageContents)
{
var permissions = await message.Channel.PermissionsIn(message.Author);
return (permissions & Permissions.MentionEveryone) == 0 ? messageContents.SanitizeEveryone() : messageContents;
}
private async Task<bool> EnsureBotPermissions(DiscordChannel channel)
{
var permissions = channel.BotPermissions();
// 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 & Permissions.SendMessages) == 0) return false;
if ((permissions & Permissions.ManageWebhooks) == 0)
{
// todo: PKError-ify these
await channel.SendMessageAsync(
$"{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 & Permissions.ManageMessages) == 0)
{
await channel.SendMessageAsync(
$"{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;
}
}
}

View File

@@ -0,0 +1,94 @@
#nullable enable
using System.Collections.Generic;
using System.Linq;
using PluralKit.Core;
namespace PluralKit.Bot
{
public class ProxyTagParser
{
public bool TryParse(string input, IEnumerable<PKMember> members, out ProxyMatch result)
{
result = default;
// 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"
// (ProxyString length desc = 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.ProxyTags = tag;
result.Member = member;
// Skip blank tags (shouldn't ever happen in practice)
if (tag.Prefix == null && tag.Suffix == null) continue;
// Can we match with these tags?
if (TryMatchTags(input, tag, out result.Content))
{
// (see https://github.com/xSke/PluralKit/pull/181)
if (result.Content == "\U0000fe0f") return false;
// If we extracted a leading mention before, add that back now
if (leadingMention != null) result.Content = $"{leadingMention} {result.Content}";
// We're done!
return true;
}
// (if not, keep going)
}
// We couldn't match anything :(
return false;
}
private bool TryMatchTags(string input, ProxyTag tag, out string content)
{
// Normalize null tags to empty strings
var prefix = tag.Prefix ?? "";
var suffix = tag.Suffix ?? "";
// Check if our input starts/ends with the tags
var isMatch = input.Length >= prefix.Length + suffix.Length
&& input.StartsWith(prefix) && input.EndsWith(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)
if (!isMatch && input.Trim() == prefix.TrimEnd() + suffix.TrimStart())
{
content = "";
return true;
}
if (isMatch)
{
content = input.Substring(prefix.Length, input.Length - prefix.Length - suffix.Length);
return true;
}
content = "";
return false;
}
private string? ExtractLeadingMention(ref string input)
{
var mentionPos = 0;
if (!StringUtils.HasMentionPrefix(input, ref mentionPos, out _)) return null;
var leadingMention = input.Substring(0, mentionPos);
input = input.Substring(mentionPos);
return leadingMention;
}
}
}