2019-04-19 18:48:37 +00:00
using System ;
using System.Collections.Generic ;
using System.Linq ;
2019-07-10 10:52:02 +00:00
using System.Net.Http ;
2019-07-14 19:27:13 +00:00
using System.Text.RegularExpressions ;
2019-04-19 18:48:37 +00:00
using System.Threading.Tasks ;
2019-07-16 19:59:06 +00:00
using App.Metrics ;
2019-04-19 18:48:37 +00:00
using Dapper ;
using Discord ;
2019-07-15 19:36:12 +00:00
using Discord.Net ;
2019-04-19 18:48:37 +00:00
using Discord.Webhook ;
using Discord.WebSocket ;
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 ProxyDatabaseResult
{
public PKSystem System ;
public PKMember Member ;
}
class ProxyMatch {
public PKMember Member ;
public PKSystem System ;
public string InnerText ;
}
2019-07-21 02:27:04 +00:00
class ProxyService : IDisposable {
2019-04-19 18:48:37 +00:00
private IDiscordClient _client ;
2019-07-11 19:25:23 +00:00
private DbConnectionFactory _conn ;
2019-07-18 15:13:42 +00:00
private LogChannelService _logChannel ;
2019-05-16 23:23:09 +00:00
private WebhookCacheService _webhookCache ;
2019-04-19 18:48:37 +00:00
private MessageStore _messageStorage ;
2019-06-21 12:13:56 +00:00
private EmbedService _embeds ;
2019-07-16 19:59:06 +00:00
private IMetrics _metrics ;
2019-07-18 15:13:42 +00:00
private ILogger _logger ;
2019-07-21 02:27:04 +00:00
private HttpClient _httpClient ;
2019-08-08 05:36:09 +00:00
2019-07-18 15:13:42 +00:00
public ProxyService ( IDiscordClient client , WebhookCacheService webhookCache , DbConnectionFactory conn , LogChannelService logChannel , MessageStore messageStorage , EmbedService embeds , IMetrics metrics , ILogger logger )
2019-04-19 18:48:37 +00:00
{
2019-06-21 12:13:56 +00:00
_client = client ;
_webhookCache = webhookCache ;
2019-07-11 19:25:23 +00:00
_conn = conn ;
2019-07-18 15:13:42 +00:00
_logChannel = logChannel ;
2019-06-21 12:13:56 +00:00
_messageStorage = messageStorage ;
_embeds = embeds ;
2019-07-16 19:59:06 +00:00
_metrics = metrics ;
2019-07-18 15:13:42 +00:00
_logger = logger . ForContext < ProxyService > ( ) ;
2019-08-08 05:36:09 +00:00
2019-07-21 02:27:04 +00:00
_httpClient = new HttpClient ( ) ;
2019-04-19 18:48:37 +00:00
}
2019-06-27 08:38:45 +00:00
private ProxyMatch GetProxyTagMatch ( string message , IEnumerable < ProxyDatabaseResult > potentials )
{
// 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 ;
if ( Utils . HasMentionPrefix ( message , ref matchStartPosition ) )
{
leadingMention = message . Substring ( 0 , matchStartPosition ) ;
message = message . Substring ( matchStartPosition ) ;
}
2019-04-19 18:48:37 +00:00
2019-05-13 21:12:58 +00:00
// Sort by specificity (ProxyString length desc = prefix+suffix length desc = inner message asc = more specific proxy first!)
var ordered = potentials . OrderByDescending ( p = > p . Member . ProxyString . Length ) ;
2019-06-21 11:49:58 +00:00
foreach ( var potential in ordered )
{
2019-06-21 11:53:19 +00:00
if ( potential . Member . Prefix = = null & & potential . Member . Suffix = = null ) continue ;
2019-08-08 05:36:09 +00:00
2019-04-19 18:48:37 +00:00
var prefix = potential . Member . Prefix ? ? "" ;
var suffix = potential . Member . Suffix ? ? "" ;
2019-07-19 00:14:46 +00:00
if ( message . Length > = prefix . Length + suffix . Length & & message . StartsWith ( prefix ) & & message . EndsWith ( suffix ) ) {
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}" ;
2019-04-19 18:48:37 +00:00
return new ProxyMatch { Member = potential . Member , System = potential . System , InnerText = inner } ;
}
}
2019-08-08 05:36:09 +00:00
2019-04-19 18:48:37 +00:00
return null ;
}
2019-07-11 19:25:23 +00:00
public async Task HandleMessageAsync ( IMessage message )
{
2019-07-28 13:38:28 +00:00
// Bail early if this isn't in a guild channel
if ( ! ( message . Channel is IGuildChannel ) ) return ;
2019-08-08 05:36:09 +00:00
2019-07-11 19:25:23 +00:00
IEnumerable < ProxyDatabaseResult > results ;
2019-07-14 03:23:27 +00:00
using ( var conn = await _conn . Obtain ( ) )
2019-07-11 19:25:23 +00:00
{
results = await conn . QueryAsync < PKMember , PKSystem , ProxyDatabaseResult > (
"select members.*, systems.* from members, systems, accounts where members.system = systems.id and accounts.system = systems.id and accounts.uid = @Uid" ,
( member , system ) = >
new ProxyDatabaseResult { Member = member , System = system } , new { Uid = message . Author . Id } ) ;
}
2019-04-19 18:48:37 +00:00
// Find a member with proxy tags matching the message
var match = GetProxyTagMatch ( message . Content , results ) ;
if ( match = = null ) return ;
2019-08-08 05:36:09 +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
if ( ! await EnsureBotPermissions ( message . Channel as ITextChannel ) ) return ;
2019-08-08 05:36:09 +00:00
2019-07-15 19:37:34 +00:00
// Can't proxy a message with no content and no attachment
if ( match . InnerText . Trim ( ) . Length = = 0 & & message . Attachments . Count = = 0 )
return ;
2019-07-28 13:38:28 +00:00
// Sanitize @everyone, but only if the original user wouldn't have permission to
var messageContents = SanitizeEveryoneMaybe ( message , match . InnerText ) ;
2019-04-19 18:48:37 +00:00
// Fetch a webhook for this channel, and send the proxied message
2019-05-16 23:23:09 +00:00
var webhook = await _webhookCache . GetWebhook ( message . Channel as ITextChannel ) ;
2019-07-26 09:08:06 +00:00
var avatarUrl = match . Member . AvatarUrl ? ? match . System . AvatarUrl ;
2019-08-09 08:12:38 +00:00
var proxyName = match . Member . ProxyName ( match . System . Tag ) ;
2019-08-11 22:57:23 +00:00
ulong hookMessageId ;
using ( _metrics . Measure . Timer . Time ( BotMetrics . WebhookResponseTime ) )
hookMessageId = await ExecuteWebhook ( webhook , messageContents , proxyName , avatarUrl , message . Attachments . FirstOrDefault ( ) ) ;
2019-04-19 18:48:37 +00:00
// Store the message in the database, and log it in the log channel (if applicable)
2019-07-24 11:38:54 +00:00
await _messageStorage . Store ( message . Author . Id , hookMessageId , message . Channel . Id , message . Id , match . Member ) ;
2019-08-08 05:36:09 +00:00
await _logChannel . LogMessage ( match . System , match . Member , hookMessageId , message . Id , message . Channel as IGuildChannel , message . Author , match . InnerText ) ;
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 ( ) ;
} catch ( HttpException ) { } // If it's already deleted, we just swallow the exception
2019-04-19 18:48:37 +00:00
}
2019-07-28 13:38:28 +00:00
private static string SanitizeEveryoneMaybe ( IMessage message , string messageContents )
{
var senderPermissions = ( ( IGuildUser ) message . Author ) . GetPermissions ( message . Channel as IGuildChannel ) ;
if ( ! senderPermissions . MentionEveryone ) return messageContents . SanitizeEveryone ( ) ;
return messageContents ;
}
2019-07-10 21:16:17 +00:00
private async Task < bool > EnsureBotPermissions ( ITextChannel channel )
{
var guildUser = await channel . Guild . GetCurrentUserAsync ( ) ;
var permissions = guildUser . GetPermissions ( channel ) ;
if ( ! permissions . ManageWebhooks )
{
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
2019-07-10 21:16:17 +00:00
if ( ! permissions . ManageMessages )
{
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 ;
}
2019-07-15 15:53:01 +00:00
private async Task < ulong > ExecuteWebhook ( IWebhook webhook , string text , string username , string avatarUrl , IAttachment attachment )
2019-07-14 19:27:13 +00:00
{
username = FixClyde ( username ) ;
2019-08-08 05:36:09 +00:00
2019-07-10 21:16:17 +00:00
// TODO: DiscordWebhookClient's ctor does a call to GetWebhook that may be unnecessary, see if there's a way to do this The Hard Way :tm:
// TODO: this will probably crash if there are multiple consecutive failures, perhaps have a loop instead?
DiscordWebhookClient client ;
try
{
client = new DiscordWebhookClient ( webhook ) ;
}
catch ( InvalidOperationException )
{
2019-07-21 02:27:04 +00:00
// TODO: does this leak internal stuff in the (now-invalid) client?
2019-08-08 05:36:09 +00:00
2019-07-10 21:16:17 +00:00
// webhook was deleted or invalid
webhook = await _webhookCache . InvalidateAndRefreshWebhook ( webhook ) ;
client = new DiscordWebhookClient ( webhook ) ;
}
2019-04-19 18:48:37 +00:00
2019-07-21 02:27:04 +00:00
// TODO: clean this entire block up
using ( client )
2019-07-16 19:59:06 +00:00
{
2019-07-21 02:27:04 +00:00
ulong messageId ;
try
2019-07-16 19:59:06 +00:00
{
2019-07-21 02:27:04 +00:00
if ( attachment ! = null )
{
using ( var stream = await _httpClient . GetStreamAsync ( attachment . Url ) )
{
messageId = await client . SendFileAsync ( stream , filename : attachment . Filename , text : text ,
username : username , avatarUrl : avatarUrl ) ;
}
}
else
2019-07-16 19:59:06 +00:00
{
2019-07-21 02:27:04 +00:00
messageId = await client . SendMessageAsync ( text , username : username , avatarUrl : avatarUrl ) ;
2019-07-16 19:59:06 +00:00
}
2019-07-21 02:27:04 +00:00
_logger . Information ( "Invoked webhook {Webhook} in channel {Channel}" , webhook . Id ,
webhook . ChannelId ) ;
// Log it in the metrics
_metrics . Measure . Meter . Mark ( BotMetrics . MessagesProxied , "success" ) ;
2019-04-19 18:48:37 +00:00
}
2019-07-21 02:27:04 +00:00
catch ( HttpException e )
2019-07-16 19:59:06 +00:00
{
2019-07-21 02:27:04 +00:00
_logger . Warning ( e , "Error invoking webhook {Webhook} in channel {Channel}" , webhook . Id ,
webhook . ChannelId ) ;
2019-07-18 15:13:42 +00:00
2019-07-21 02:27:04 +00:00
// Log failure in metrics and rethrow (we still need to cancel everything else)
_metrics . Measure . Meter . Mark ( BotMetrics . MessagesProxied , "failure" ) ;
throw ;
}
2019-08-08 05:36:09 +00:00
2019-07-21 02:27:04 +00:00
// TODO: figure out a way to return the full message object (without doing a GetMessageAsync call, which
// doesn't work if there's no permission to)
return messageId ;
2019-07-16 19:59:06 +00:00
}
2019-04-19 18:48:37 +00:00
}
2019-06-21 12:13:56 +00:00
public Task HandleReactionAddedAsync ( Cacheable < IUserMessage , ulong > message , ISocketMessageChannel channel , SocketReaction reaction )
2019-04-19 18:48:37 +00:00
{
2019-06-21 12:13:56 +00:00
// Dispatch on emoji
switch ( reaction . Emote . Name )
{
case "\u274C" : // Red X
return HandleMessageDeletionByReaction ( message , reaction . UserId ) ;
case "\u2753" : // Red question mark
case "\u2754" : // White question mark
2019-07-14 03:23:27 +00:00
return HandleMessageQueryByReaction ( message , reaction . UserId , reaction . Emote ) ;
2019-06-21 12:13:56 +00:00
default :
return Task . CompletedTask ;
}
}
2019-04-19 18:48:37 +00:00
2019-07-14 03:23:27 +00:00
private async Task HandleMessageQueryByReaction ( Cacheable < IUserMessage , ulong > message , ulong userWhoReacted , IEmote reactedEmote )
2019-06-21 12:13:56 +00:00
{
2019-07-14 03:23:27 +00:00
// Find the user who sent the reaction, so we can DM them
2019-06-21 12:13:56 +00:00
var user = await _client . GetUserAsync ( userWhoReacted ) ;
if ( user = = null ) return ;
2019-07-14 03:23:27 +00:00
// Find the message in the DB
2019-06-21 12:13:56 +00:00
var msg = await _messageStorage . Get ( message . Id ) ;
if ( msg = = null ) return ;
2019-08-08 05:36:09 +00:00
2019-07-14 03:23:27 +00:00
// DM them the message card
2019-06-21 12:13:56 +00:00
await user . SendMessageAsync ( embed : await _embeds . CreateMessageInfoEmbed ( msg ) ) ;
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)
var msgObj = await message . GetOrDownloadAsync ( ) ;
if ( await msgObj . Channel . HasPermission ( ChannelPermission . ManageMessages ) )
await msgObj . RemoveReactionAsync ( reactedEmote , user ) ;
2019-06-21 12:13:56 +00:00
}
public async Task HandleMessageDeletionByReaction ( Cacheable < IUserMessage , ulong > message , ulong userWhoReacted )
{
2019-04-19 18:48:37 +00:00
// Find the message in the database
var storedMessage = await _messageStorage . Get ( message . Id ) ;
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
2019-06-21 12:13:56 +00:00
if ( storedMessage . Message . Sender ! = userWhoReacted ) return ;
2019-04-19 18:48:37 +00:00
try {
// Then, fetch the Discord message and delete that
// TODO: this could be faster if we didn't bother fetching it and just deleted it directly
// somehow through REST?
await ( await message . GetOrDownloadAsync ( ) ) . DeleteAsync ( ) ;
} catch ( NullReferenceException ) {
// Message was deleted before we got to it... cool, no problem, lmao
}
// Finally, delete it from our database.
await _messageStorage . Delete ( message . Id ) ;
}
public async Task HandleMessageDeletedAsync ( Cacheable < IMessage , ulong > message , ISocketMessageChannel channel )
{
await _messageStorage . Delete ( message . Id ) ;
}
2019-07-14 19:27:13 +00:00
2019-07-21 15:16:04 +00:00
public async Task HandleMessageBulkDeleteAsync ( IReadOnlyCollection < Cacheable < IMessage , ulong > > messages , IMessageChannel channel )
{
_logger . Information ( "Bulk deleting {Count} messages in channel {Channel}" , messages . Count , channel . Id ) ;
await _messageStorage . BulkDelete ( messages . Select ( m = > m . Id ) . ToList ( ) ) ;
}
2019-07-14 19:27:13 +00:00
private string FixClyde ( string name )
{
var match = Regex . Match ( name , "clyde" , RegexOptions . IgnoreCase ) ;
if ( ! match . Success ) return name ;
2019-08-08 05:36:09 +00:00
2019-07-14 19:27:13 +00:00
// Put a hair space (\u200A) between the "c" and the "lyde" in the match to avoid Discord matching it
// since Discord blocks webhooks containing the word "Clyde"... for some reason. /shrug
return name . Substring ( 0 , match . Index + 1 ) + ' \ u200A ' + name . Substring ( match . Index + 1 ) ;
}
2019-07-21 02:27:04 +00:00
public void Dispose ( )
{
_httpClient . Dispose ( ) ;
}
2019-04-19 18:48:37 +00:00
}
}