2019-04-19 18:48:37 +00:00
using System ;
using System.Collections.Generic ;
using System.Linq ;
using System.Threading.Tasks ;
2019-08-14 05:16:48 +00:00
2020-04-17 21:10:01 +00:00
using DSharpPlus ;
using DSharpPlus.Entities ;
using DSharpPlus.EventArgs ;
using DSharpPlus.Exceptions ;
2019-08-14 05:16:48 +00:00
2020-01-24 19:28:48 +00:00
using NodaTime ;
2019-08-14 05:16:48 +00:00
using PluralKit.Core ;
2019-07-18 15:13:42 +00:00
using Serilog ;
2019-04-19 18:48:37 +00:00
2019-04-21 13:33:22 +00:00
namespace PluralKit.Bot
2019-04-19 18:48:37 +00:00
{
class ProxyMatch {
public PKMember Member ;
public PKSystem System ;
2020-01-24 19:28:48 +00:00
public ProxyTag ? ProxyTags ;
2019-04-19 18:48:37 +00:00
public string InnerText ;
}
2020-05-01 23:52:52 +00:00
public class ProxyService {
2020-02-01 14:00:36 +00:00
private DiscordShardedClient _client ;
2019-07-18 15:13:42 +00:00
private LogChannelService _logChannel ;
2019-10-26 17:45:30 +00:00
private IDataStore _data ;
2019-06-21 12:13:56 +00:00
private EmbedService _embeds ;
2019-07-18 15:13:42 +00:00
private ILogger _logger ;
2019-08-12 03:47:55 +00:00
private WebhookExecutorService _webhookExecutor ;
2019-12-22 23:29:04 +00:00
2020-02-01 14:00:36 +00:00
public ProxyService ( DiscordShardedClient client , LogChannelService logChannel , IDataStore data , EmbedService embeds , ILogger logger , WebhookExecutorService webhookExecutor )
2019-04-19 18:48:37 +00:00
{
2019-06-21 12:13:56 +00:00
_client = client ;
2019-07-18 15:13:42 +00:00
_logChannel = logChannel ;
2019-10-26 17:45:30 +00:00
_data = data ;
2019-06-21 12:13:56 +00:00
_embeds = embeds ;
2019-08-12 03:47:55 +00:00
_webhookExecutor = webhookExecutor ;
2019-07-18 15:13:42 +00:00
_logger = logger . ForContext < ProxyService > ( ) ;
2019-04-19 18:48:37 +00:00
}
2020-02-01 13:40:57 +00:00
private ProxyMatch GetProxyTagMatch ( string message , PKSystem system , IEnumerable < PKMember > potentialMembers )
2019-06-27 08:38:45 +00:00
{
// 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]
int matchStartPosition = 0 ;
string leadingMention = null ;
2020-02-12 14:16:19 +00:00
if ( StringUtils . HasMentionPrefix ( message , ref matchStartPosition , out _ ) )
2019-06-27 08:38:45 +00:00
{
leadingMention = message . Substring ( 0 , matchStartPosition ) ;
message = message . Substring ( matchStartPosition ) ;
}
2019-04-19 18:48:37 +00:00
2019-10-28 19:15:27 +00:00
// Flatten and sort by specificity (ProxyString length desc = prefix+suffix length desc = inner message asc = more specific proxy first!)
2020-02-01 13:40:57 +00:00
var ordered = potentialMembers . SelectMany ( m = > m . ProxyTags . Select ( tag = > ( tag , m ) ) ) . OrderByDescending ( p = > p . Item1 . ProxyString . Length ) ;
2019-10-28 19:15:27 +00:00
foreach ( var ( tag , match ) in ordered )
2019-06-21 11:49:58 +00:00
{
2019-10-28 19:15:27 +00:00
if ( tag . Prefix = = null & & tag . Suffix = = null ) continue ;
2019-08-08 05:36:09 +00:00
2019-10-28 19:15:27 +00:00
var prefix = tag . Prefix ? ? "" ;
var suffix = tag . Suffix ? ? "" ;
2019-04-19 18:48:37 +00:00
2019-12-26 18:19:06 +00:00
var isMatch = message . Length > = prefix . Length + suffix . Length
& & message . StartsWith ( prefix ) & & message . EndsWith ( suffix ) ;
// Special case for image-only proxies and proxy tags with spaces
if ( ! isMatch & & message . Trim ( ) = = prefix . TrimEnd ( ) + suffix . TrimStart ( ) )
{
isMatch = true ;
message = prefix + suffix ; // To get around substring errors
}
if ( isMatch ) {
2019-04-19 18:48:37 +00:00
var inner = message . Substring ( prefix . Length , message . Length - prefix . Length - suffix . Length ) ;
2019-06-27 08:38:45 +00:00
if ( leadingMention ! = null ) inner = $"{leadingMention} {inner}" ;
2020-02-01 13:40:57 +00:00
return new ProxyMatch { Member = match , System = system , InnerText = inner , ProxyTags = tag } ;
2019-04-19 18:48:37 +00:00
}
}
2019-08-08 05:36:09 +00:00
2019-04-19 18:48:37 +00:00
return null ;
}
2020-04-17 21:10:01 +00:00
public async Task HandleMessageAsync ( DiscordClient client , GuildConfig guild , CachedAccount account , DiscordMessage message , bool doAutoProxy )
2019-07-11 19:25:23 +00:00
{
2019-07-28 13:38:28 +00:00
// Bail early if this isn't in a guild channel
2020-04-24 21:21:02 +00:00
if ( message . Channel . Guild = = null ) return ;
2019-11-03 18:15:50 +00:00
2019-04-19 18:48:37 +00:00
// Find a member with proxy tags matching the message
2020-02-01 13:40:57 +00:00
var match = GetProxyTagMatch ( message . Content , account . System , account . Members ) ;
// O(n) lookup since n is small (max ~100 in prod) and we're more constrained by memory (for a dictionary) here
2020-04-17 21:10:01 +00:00
var systemSettingsForGuild = account . SettingsForGuild ( message . Channel . GuildId ) ;
2020-01-24 19:28:48 +00:00
// If we didn't get a match by proxy tags, try to get one by autoproxy
2020-02-03 15:10:43 +00:00
// Also try if we *did* get a match, but there's no inner text. This happens if someone sends a message that
// is equal to someone else's tags, and messages like these should be autoproxied if possible
2020-02-12 16:44:24 +00:00
// All of this should only be done if this call allows autoproxy.
// When a normal message is sent, autoproxy is enabled, but if this method is called from a message *edit*
// event, then autoproxy is disabled. This is so AP doesn't "retrigger" when the original message was escaped.
if ( doAutoProxy & & ( match = = null | | ( match . InnerText . Trim ( ) . Length = = 0 & & message . Attachments . Count = = 0 ) ) )
2020-04-17 21:10:01 +00:00
match = await GetAutoproxyMatch ( account , systemSettingsForGuild , message , message . Channel ) ;
2020-01-24 19:28:48 +00:00
// If we still haven't found any, just yeet
2019-04-19 18:48:37 +00:00
if ( match = = null ) return ;
2019-11-03 18:15:50 +00:00
// And make sure the channel's not blacklisted from proxying.
2020-04-17 21:10:01 +00:00
if ( guild . Blacklist . Contains ( message . ChannelId ) ) return ;
2019-12-22 13:15:56 +00:00
// Make sure the system hasn't blacklisted the guild either
2020-02-01 13:40:57 +00:00
if ( ! systemSettingsForGuild . ProxyEnabled ) return ;
2019-12-26 19:39:47 +00:00
2019-07-10 21:16:17 +00:00
// We know message.Channel can only be ITextChannel as PK doesn't work in DMs/groups
// Afterwards we ensure the bot has the right permissions, otherwise bail early
2020-04-17 21:10:01 +00:00
if ( ! await EnsureBotPermissions ( message . Channel ) ) return ;
2019-12-22 13:15:56 +00:00
2019-07-15 19:37:34 +00:00
// Can't proxy a message with no content and no attachment
2019-12-23 12:55:43 +00:00
if ( match . InnerText . Trim ( ) . Length = = 0 & & message . Attachments . Count = = 0 )
2019-07-15 19:37:34 +00:00
return ;
2020-02-01 13:40:57 +00:00
2020-04-17 21:10:01 +00:00
var memberSettingsForGuild = account . SettingsForMemberGuild ( match . Member . Id , message . Channel . GuildId ) ;
2019-08-12 03:47:55 +00:00
// Get variables in order and all
2020-02-01 13:40:57 +00:00
var proxyName = match . Member . ProxyName ( match . System . Tag , memberSettingsForGuild . DisplayName ) ;
2020-02-12 16:42:12 +00:00
var avatarUrl = memberSettingsForGuild . AvatarUrl ? ? match . Member . AvatarUrl ? ? match . System . AvatarUrl ;
2019-08-12 03:47:55 +00:00
2019-08-14 05:16:48 +00:00
// If the name's too long (or short), bail
if ( proxyName . Length < 2 ) throw Errors . ProxyNameTooShort ( proxyName ) ;
if ( proxyName . Length > Limits . MaxProxyNameLength ) throw Errors . ProxyNameTooLong ( proxyName ) ;
2019-10-30 08:26:50 +00:00
// Add the proxy tags into the proxied message if that option is enabled
2020-01-24 19:28:48 +00:00
// Also check if the member has any proxy tags - some cases autoproxy can return a member with no tags
var messageContents = ( match . Member . KeepProxy & & match . ProxyTags . HasValue )
? $"{match.ProxyTags.Value.Prefix}{match.InnerText}{match.ProxyTags.Value.Suffix}"
2019-10-30 08:26:50 +00:00
: match . InnerText ;
2019-08-14 05:16:48 +00:00
2019-07-28 13:38:28 +00:00
// Sanitize @everyone, but only if the original user wouldn't have permission to
2020-04-17 21:10:01 +00:00
messageContents = await SanitizeEveryoneMaybe ( message , messageContents ) ;
2019-08-12 03:47:55 +00:00
// Execute the webhook itself
2020-04-17 21:10:01 +00:00
var hookMessageId = await _webhookExecutor . ExecuteWebhook ( message . Channel , proxyName , avatarUrl ,
2019-08-12 03:47:55 +00:00
messageContents ,
2019-12-21 19:07:51 +00:00
message . Attachments
2019-08-12 03:47:55 +00:00
) ;
2019-04-19 18:48:37 +00:00
// Store the message in the database, and log it in the log channel (if applicable)
2020-04-17 21:10:01 +00:00
await _data . AddMessage ( message . Author . Id , hookMessageId , message . Channel . GuildId , message . Channel . Id , message . Id , match . Member ) ;
await _logChannel . LogMessage ( client , match . System , match . Member , hookMessageId , message . Id , message . Channel , message . Author , match . InnerText , guild ) ;
2019-04-19 18:48:37 +00:00
// Wait a second or so before deleting the original message
await Task . Delay ( 1000 ) ;
2019-07-15 19:36:12 +00:00
try
{
await message . DeleteAsync ( ) ;
2019-08-12 02:42:16 +00:00
}
2020-04-17 21:10:01 +00:00
catch ( NotFoundException )
2019-08-12 02:42:16 +00:00
{
2019-08-12 03:47:55 +00:00
// 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 ) ;
2019-08-12 02:42:16 +00:00
}
}
2020-04-17 21:10:01 +00:00
private async Task < ProxyMatch > GetAutoproxyMatch ( CachedAccount account , SystemGuildSettings guildSettings , DiscordMessage message , DiscordChannel channel )
2020-01-24 19:28:48 +00:00
{
// For now we use a backslash as an "escape character", subject to change later
2020-01-25 16:40:41 +00:00
if ( ( message . Content ? ? "" ) . TrimStart ( ) . StartsWith ( "\\" ) ) return null ;
2020-01-24 19:28:48 +00:00
PKMember member = null ;
// Figure out which member to proxy as
2020-02-01 13:40:57 +00:00
switch ( guildSettings . AutoproxyMode )
2020-01-24 19:28:48 +00:00
{
case AutoproxyMode . Off :
// Autoproxy off, bail
return null ;
case AutoproxyMode . Front :
// Front mode: just use the current first fronter
2020-02-01 13:40:57 +00:00
member = await _data . GetFirstFronter ( account . System ) ;
2020-01-24 19:28:48 +00:00
break ;
case AutoproxyMode . Latch :
// Latch mode: find last proxied message, use *that* member
var msg = await _data . GetLastMessageInGuild ( message . Author . Id , channel . 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.
2020-04-17 21:10:01 +00:00
var timestamp = DiscordUtils . SnowflakeToInstant ( msg . Message . Mid ) ;
2020-01-24 19:28:48 +00:00
var timeSince = SystemClock . Instance . GetCurrentInstant ( ) - timestamp ;
if ( timeSince > Duration . FromHours ( 6 ) ) return null ;
member = msg . Member ;
break ;
case AutoproxyMode . Member :
// Member mode: just use that member
2020-02-01 13:40:57 +00:00
// O(n) lookup since n is small (max 1000 de jure) and we're more constrained by memory (for a dictionary) here
member = account . Members . FirstOrDefault ( m = > m . Id = = guildSettings . AutoproxyMember ) ;
2020-01-24 19:28:48 +00:00
break ;
}
// If we haven't found the member (eg. front mode w/ no fronter), bail again
if ( member = = null ) return null ;
return new ProxyMatch
{
2020-02-01 13:40:57 +00:00
System = account . System ,
2020-01-24 19:28:48 +00:00
Member = member ,
// Autoproxying members with no proxy tags is possible, return the correct result
ProxyTags = member . ProxyTags . Count > 0 ? member . ProxyTags . First ( ) : ( ProxyTag ? ) null ,
InnerText = message . Content
} ;
}
2020-04-17 21:10:01 +00:00
private static async Task < string > SanitizeEveryoneMaybe ( DiscordMessage message ,
string messageContents )
2019-07-28 13:38:28 +00:00
{
2020-05-01 15:03:43 +00:00
var permissions = await message . Channel . PermissionsIn ( message . Author ) ;
return ( permissions & Permissions . MentionEveryone ) = = 0 ? messageContents . SanitizeEveryone ( ) : messageContents ;
2019-07-28 13:38:28 +00:00
}
2020-04-17 21:10:01 +00:00
private async Task < bool > EnsureBotPermissions ( DiscordChannel channel )
2019-07-10 21:16:17 +00:00
{
2020-04-17 21:10:01 +00:00
var permissions = channel . BotPermissions ( ) ;
2019-07-10 21:16:17 +00:00
2020-01-08 11:16:27 +00:00
// If we can't send messages at all, just bail immediately.
2020-04-22 07:27:55 +00:00
// 2020-04-22: Manage Messages does *not* override a lack of Send Messages.
2020-05-01 13:21:55 +00:00
if ( ( permissions & Permissions . SendMessages ) = = 0 ) return false ;
2020-01-08 11:16:27 +00:00
2020-04-17 21:10:01 +00:00
if ( ( permissions & Permissions . ManageWebhooks ) = = 0 )
2019-07-10 21:16:17 +00:00
{
2019-08-14 05:16:48 +00:00
// todo: PKError-ify these
2019-07-10 21:16:17 +00:00
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 ;
}
2019-08-08 05:36:09 +00:00
2020-04-17 21:10:01 +00:00
if ( ( permissions & Permissions . ManageMessages ) = = 0 )
2019-07-10 21:16:17 +00:00
{
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 ;
}
2020-04-17 21:10:01 +00:00
public Task HandleReactionAddedAsync ( MessageReactionAddEventArgs args )
2019-04-19 18:48:37 +00:00
{
2019-06-21 12:13:56 +00:00
// Dispatch on emoji
2020-04-17 21:10:01 +00:00
switch ( args . Emoji . Name )
2019-06-21 12:13:56 +00:00
{
case "\u274C" : // Red X
2020-04-17 21:10:01 +00:00
return HandleMessageDeletionByReaction ( args ) ;
2019-06-21 12:13:56 +00:00
case "\u2753" : // Red question mark
case "\u2754" : // White question mark
2020-04-17 21:10:01 +00:00
return HandleMessageQueryByReaction ( args ) ;
2019-12-22 12:54:18 +00:00
case "\U0001F514" : // Bell
case "\U0001F6CE" : // Bellhop bell
case "\U0001F3D3" : // Ping pong paddle (lol)
case "\u23F0" : // Alarm clock
case "\u2757" : // Exclamation mark
2020-04-17 21:10:01 +00:00
return HandleMessagePingByReaction ( args ) ;
2019-06-21 12:13:56 +00:00
default :
return Task . CompletedTask ;
}
}
2019-04-19 18:48:37 +00:00
2020-04-17 21:10:01 +00:00
private async Task HandleMessagePingByReaction ( MessageReactionAddEventArgs args )
2019-12-22 12:54:18 +00:00
{
2020-05-09 13:51:26 +00:00
// Bail in DMs or if we don't have send permission
2020-04-17 21:10:01 +00:00
if ( args . Channel . Type ! = ChannelType . Text ) return ;
2020-05-09 13:51:26 +00:00
if ( ! args . Channel . BotHasAllPermissions ( Permissions . SendMessages ) ) return ;
2020-03-04 17:39:51 +00:00
2019-12-22 12:54:18 +00:00
// Find the message in the DB
2020-04-17 21:10:01 +00:00
var msg = await _data . GetMessage ( args . Message . Id ) ;
2019-12-22 12:54:18 +00:00
if ( msg = = null ) return ;
2020-03-04 17:39:51 +00:00
// Check if the pinger has permission to ping in this channel
2020-04-17 21:10:01 +00:00
var guildUser = await args . Guild . GetMemberAsync ( args . User . Id ) ;
var permissions = guildUser . PermissionsIn ( args . Channel ) ;
2020-03-04 17:39:51 +00:00
// If they don't have Send Messages permission, bail (since PK shouldn't send anything on their behalf)
2020-04-17 21:10:01 +00:00
var requiredPerms = Permissions . AccessChannels | Permissions . SendMessages ;
if ( ( permissions & requiredPerms ) ! = requiredPerms ) return ;
var embed = new DiscordEmbedBuilder ( ) . WithDescription ( $"[Jump to pinged message]({args.Message.JumpLink})" ) ;
await args . Channel . SendMessageAsync ( $"Psst, **{msg.Member.DisplayName ?? msg.Member.Name}** (<@{msg.Message.Sender}>), you have been pinged by <@{args.User.Id}>." , embed : embed . Build ( ) ) ;
2019-12-22 13:44:14 +00:00
// Finally remove the original reaction (if we can)
2020-05-02 13:29:36 +00:00
if ( args . Channel . BotHasAllPermissions ( Permissions . ManageMessages ) )
2020-04-17 21:10:01 +00:00
await args . Message . DeleteReactionAsync ( args . Emoji , args . User ) ;
2019-12-22 12:54:18 +00:00
}
2020-04-17 21:10:01 +00:00
private async Task HandleMessageQueryByReaction ( MessageReactionAddEventArgs args )
2019-06-21 12:13:56 +00:00
{
2020-04-17 21:10:01 +00:00
// Bail if not in guild
if ( args . Guild = = null ) return ;
2019-07-14 03:23:27 +00:00
// Find the message in the DB
2020-04-17 21:10:01 +00:00
var msg = await _data . GetMessage ( args . Message . Id ) ;
2019-06-21 12:13:56 +00:00
if ( msg = = null ) return ;
2020-04-17 21:10:01 +00:00
// Get guild member so we can DM
var member = await args . Guild . GetMemberAsync ( args . User . Id ) ;
2019-08-08 05:36:09 +00:00
2019-07-14 03:23:27 +00:00
// DM them the message card
2020-02-12 13:22:15 +00:00
try
{
2020-04-17 21:10:01 +00:00
await member . SendMessageAsync ( embed : await _embeds . CreateMemberEmbed ( msg . System , msg . Member , args . Guild , LookupContext . ByNonOwner ) ) ;
await member . SendMessageAsync ( embed : await _embeds . CreateMessageInfoEmbed ( args . Client , msg ) ) ;
2020-02-12 13:22:15 +00:00
}
2020-05-12 19:31:59 +00:00
catch ( UnauthorizedException )
2020-02-12 13:22:15 +00:00
{
// Ignore exception if it means we don't have DM permission to this user
// not much else we can do here :/
}
2019-08-08 05:36:09 +00:00
2019-07-14 03:23:27 +00:00
// And finally remove the original reaction (if we can)
2020-04-17 21:10:01 +00:00
await args . Message . DeleteReactionAsync ( args . Emoji , args . User ) ;
2019-06-21 12:13:56 +00:00
}
2020-04-17 21:10:01 +00:00
public async Task HandleMessageDeletionByReaction ( MessageReactionAddEventArgs args )
2019-06-21 12:13:56 +00:00
{
2020-04-17 21:10:01 +00:00
// Bail if we don't have permission to delete
2020-05-02 13:29:36 +00:00
if ( ! args . Channel . BotHasAllPermissions ( Permissions . ManageMessages ) ) return ;
2020-04-17 21:10:01 +00:00
2019-04-19 18:48:37 +00:00
// Find the message in the database
2020-04-17 21:10:01 +00:00
var storedMessage = await _data . GetMessage ( args . Message . Id ) ;
2019-04-19 18:48:37 +00:00
if ( storedMessage = = null ) return ; // (if we can't, that's ok, no worries)
// Make sure it's the actual sender of that message deleting the message
2020-04-17 21:10:01 +00:00
if ( storedMessage . Message . Sender ! = args . User . Id ) return ;
2019-04-19 18:48:37 +00:00
2020-04-17 21:10:01 +00:00
try
{
await args . Message . DeleteAsync ( ) ;
2019-04-19 18:48:37 +00:00
} catch ( NullReferenceException ) {
// Message was deleted before we got to it... cool, no problem, lmao
}
// Finally, delete it from our database.
2020-04-17 21:10:01 +00:00
await _data . DeleteMessage ( args . Message . Id ) ;
2019-04-19 18:48:37 +00:00
}
2020-04-17 21:10:01 +00:00
public async Task HandleMessageDeletedAsync ( MessageDeleteEventArgs args )
2019-04-19 18:48:37 +00:00
{
2019-08-12 01:51:54 +00:00
// Don't delete messages from the store if they aren't webhooks
// Non-webhook messages will never be stored anyway.
// If we're not sure (eg. message outside of cache), delete just to be sure.
2020-04-17 21:10:01 +00:00
if ( ! args . Message . WebhookMessage ) return ;
await _data . DeleteMessage ( args . Message . Id ) ;
2019-04-19 18:48:37 +00:00
}
2019-07-14 19:27:13 +00:00
2020-04-17 21:10:01 +00:00
public async Task HandleMessageBulkDeleteAsync ( MessageBulkDeleteEventArgs args )
2019-07-21 15:16:04 +00:00
{
2020-04-17 21:10:01 +00:00
_logger . Information ( "Bulk deleting {Count} messages in channel {Channel}" , args . Messages . Count , args . Channel . Id ) ;
await _data . DeleteMessagesBulk ( args . Messages . Select ( m = > m . Id ) . ToList ( ) ) ;
2019-07-21 15:16:04 +00:00
}
2019-04-19 18:48:37 +00:00
}
}