2020-02-26 18:47:30 +00:00
|
|
|
using System;
|
2019-12-21 19:07:51 +00:00
|
|
|
using System.Collections.Generic;
|
|
|
|
using System.Linq;
|
2019-08-12 03:47:55 +00:00
|
|
|
using System.Net.Http;
|
|
|
|
using System.Text.RegularExpressions;
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
using App.Metrics;
|
2019-12-21 17:50:28 +00:00
|
|
|
|
|
|
|
using Humanizer;
|
|
|
|
|
2020-12-22 12:15:26 +00:00
|
|
|
using Myriad.Cache;
|
2020-12-22 15:55:13 +00:00
|
|
|
using Myriad.Extensions;
|
2020-12-22 12:15:26 +00:00
|
|
|
using Myriad.Rest;
|
|
|
|
using Myriad.Rest.Types;
|
|
|
|
using Myriad.Rest.Types.Requests;
|
|
|
|
using Myriad.Types;
|
|
|
|
|
2019-12-21 17:50:28 +00:00
|
|
|
using Newtonsoft.Json;
|
|
|
|
|
2019-08-12 03:47:55 +00:00
|
|
|
using Serilog;
|
|
|
|
|
|
|
|
namespace PluralKit.Bot
|
|
|
|
{
|
2021-08-27 15:03:47 +00:00
|
|
|
public class WebhookExecutionErrorOnDiscordsEnd: Exception
|
|
|
|
{
|
2020-02-26 18:47:30 +00:00
|
|
|
}
|
2021-08-27 15:03:47 +00:00
|
|
|
|
|
|
|
public class WebhookRateLimited: WebhookExecutionErrorOnDiscordsEnd
|
|
|
|
{
|
2020-03-26 23:01:42 +00:00
|
|
|
// Exceptions for control flow? don't mind if I do
|
|
|
|
// TODO: rewrite both of these as a normal exceptional return value (0?) in case of error to be discarded by caller
|
|
|
|
}
|
2020-12-22 12:15:26 +00:00
|
|
|
|
|
|
|
public record ProxyRequest
|
|
|
|
{
|
|
|
|
public ulong GuildId { get; init; }
|
|
|
|
public ulong ChannelId { get; init; }
|
2021-07-15 10:41:19 +00:00
|
|
|
public ulong? ThreadId { get; init; }
|
2020-12-22 12:15:26 +00:00
|
|
|
public string Name { get; init; }
|
|
|
|
public string? AvatarUrl { get; init; }
|
|
|
|
public string? Content { get; init; }
|
|
|
|
public Message.Attachment[] Attachments { get; init; }
|
2021-11-04 18:13:43 +00:00
|
|
|
public int FileSizeLimit { get; init; }
|
2020-12-22 12:15:26 +00:00
|
|
|
public Embed[] Embeds { get; init; }
|
|
|
|
public bool AllowEveryone { get; init; }
|
|
|
|
}
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2019-12-22 23:35:42 +00:00
|
|
|
public class WebhookExecutorService
|
2019-08-12 03:47:55 +00:00
|
|
|
{
|
2020-12-22 12:15:26 +00:00
|
|
|
private readonly IDiscordCache _cache;
|
2020-08-29 11:46:27 +00:00
|
|
|
private readonly WebhookCacheService _webhookCache;
|
2020-12-22 12:15:26 +00:00
|
|
|
private readonly DiscordApiClient _rest;
|
2020-08-29 11:46:27 +00:00
|
|
|
private readonly ILogger _logger;
|
|
|
|
private readonly IMetrics _metrics;
|
|
|
|
private readonly HttpClient _client;
|
2019-08-12 03:47:55 +00:00
|
|
|
|
2020-12-22 12:15:26 +00:00
|
|
|
public WebhookExecutorService(IMetrics metrics, WebhookCacheService webhookCache, ILogger logger, HttpClient client, IDiscordCache cache, DiscordApiClient rest)
|
2019-08-12 03:47:55 +00:00
|
|
|
{
|
|
|
|
_metrics = metrics;
|
|
|
|
_webhookCache = webhookCache;
|
2019-12-22 23:29:04 +00:00
|
|
|
_client = client;
|
2020-12-22 12:15:26 +00:00
|
|
|
_cache = cache;
|
|
|
|
_rest = rest;
|
2019-08-12 03:47:55 +00:00
|
|
|
_logger = logger.ForContext<WebhookExecutorService>();
|
|
|
|
}
|
|
|
|
|
2020-12-22 12:15:26 +00:00
|
|
|
public async Task<Message> ExecuteWebhook(ProxyRequest req)
|
2019-08-12 03:47:55 +00:00
|
|
|
{
|
2020-12-22 12:15:26 +00:00
|
|
|
_logger.Verbose("Invoking webhook in channel {Channel}", req.ChannelId);
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2019-08-12 03:47:55 +00:00
|
|
|
// Get a webhook, execute it
|
2020-12-22 12:15:26 +00:00
|
|
|
var webhook = await _webhookCache.GetWebhook(req.ChannelId);
|
|
|
|
var webhookMessage = await ExecuteWebhookInner(webhook, req);
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2019-08-12 03:47:55 +00:00
|
|
|
// Log the relevant metrics
|
|
|
|
_metrics.Measure.Meter.Mark(BotMetrics.MessagesProxied);
|
2021-08-01 16:32:40 +00:00
|
|
|
_logger.Information("Invoked webhook {Webhook} in channel {Channel} (thread {ThreadId})", webhook.Id,
|
2021-07-15 10:41:19 +00:00
|
|
|
req.ChannelId, req.ThreadId);
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2020-11-15 13:34:49 +00:00
|
|
|
return webhookMessage;
|
2019-08-12 03:47:55 +00:00
|
|
|
}
|
|
|
|
|
2021-05-03 10:33:30 +00:00
|
|
|
public async Task<Message> EditWebhookMessage(ulong channelId, ulong messageId, string newContent)
|
|
|
|
{
|
2021-08-27 15:03:47 +00:00
|
|
|
var allowedMentions = newContent.ParseMentions() with
|
|
|
|
{
|
2021-05-03 10:33:30 +00:00
|
|
|
Roles = Array.Empty<ulong>(),
|
|
|
|
Parse = Array.Empty<AllowedMentions.ParseType>()
|
|
|
|
};
|
|
|
|
|
2021-09-24 23:03:40 +00:00
|
|
|
ulong? threadId = null;
|
2021-11-18 01:41:02 +00:00
|
|
|
var root = await _cache.GetRootChannel(channelId);
|
2021-09-24 23:03:40 +00:00
|
|
|
if (root.Id != channelId)
|
|
|
|
threadId = channelId;
|
|
|
|
|
|
|
|
var webhook = await _webhookCache.GetWebhook(root.Id);
|
|
|
|
|
2021-05-03 10:33:30 +00:00
|
|
|
return await _rest.EditWebhookMessage(webhook.Id, webhook.Token, messageId,
|
2021-09-24 23:03:40 +00:00
|
|
|
new WebhookMessageEditRequest { Content = newContent, AllowedMentions = allowedMentions },
|
|
|
|
threadId);
|
2021-05-03 10:33:30 +00:00
|
|
|
}
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2020-12-22 12:15:26 +00:00
|
|
|
private async Task<Message> ExecuteWebhookInner(Webhook webhook, ProxyRequest req, bool hasRetried = false)
|
2019-08-12 03:47:55 +00:00
|
|
|
{
|
2021-11-18 01:41:02 +00:00
|
|
|
var guild = await _cache.GetGuild(req.GuildId);
|
2020-12-22 12:15:26 +00:00
|
|
|
var content = req.Content.Truncate(2000);
|
|
|
|
|
2020-12-22 15:55:13 +00:00
|
|
|
var allowedMentions = content.ParseMentions();
|
|
|
|
if (!req.AllowEveryone)
|
2021-08-27 15:03:47 +00:00
|
|
|
allowedMentions = allowedMentions.RemoveUnmentionableRoles(guild) with
|
|
|
|
{
|
2021-03-18 10:34:35 +00:00
|
|
|
// also clear @everyones
|
|
|
|
Parse = Array.Empty<AllowedMentions.ParseType>()
|
|
|
|
};
|
2020-12-22 15:55:13 +00:00
|
|
|
|
2020-12-22 12:15:26 +00:00
|
|
|
var webhookReq = new ExecuteWebhookRequest
|
|
|
|
{
|
2021-01-31 15:02:34 +00:00
|
|
|
Username = FixProxyName(req.Name).Truncate(80),
|
2020-12-22 12:15:26 +00:00
|
|
|
Content = content,
|
2020-12-22 15:55:13 +00:00
|
|
|
AllowedMentions = allowedMentions,
|
2020-12-22 12:15:26 +00:00
|
|
|
AvatarUrl = !string.IsNullOrWhiteSpace(req.AvatarUrl) ? req.AvatarUrl : null,
|
|
|
|
Embeds = req.Embeds
|
|
|
|
};
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2020-12-22 12:15:26 +00:00
|
|
|
MultipartFile[] files = null;
|
2021-11-04 18:13:43 +00:00
|
|
|
var attachmentChunks = ChunkAttachmentsOrThrow(req.Attachments, req.FileSizeLimit * 1024 * 1024);
|
2019-12-21 19:07:51 +00:00
|
|
|
if (attachmentChunks.Count > 0)
|
2019-12-22 21:56:18 +00:00
|
|
|
{
|
2021-08-27 15:03:47 +00:00
|
|
|
_logger.Information("Invoking webhook with {AttachmentCount} attachments totalling {AttachmentSize} MiB in {AttachmentChunks} chunks",
|
2020-12-22 12:15:26 +00:00
|
|
|
req.Attachments.Length, req.Attachments.Select(a => a.Size).Sum() / 1024 / 1024, attachmentChunks.Count);
|
|
|
|
files = await GetAttachmentFiles(attachmentChunks[0]);
|
2019-12-23 12:55:43 +00:00
|
|
|
}
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2020-12-22 12:15:26 +00:00
|
|
|
Message webhookMessage;
|
2021-08-27 15:03:47 +00:00
|
|
|
using (_metrics.Measure.Timer.Time(BotMetrics.WebhookResponseTime))
|
|
|
|
{
|
2020-06-14 20:19:12 +00:00
|
|
|
try
|
2019-08-12 14:38:34 +00:00
|
|
|
{
|
2021-07-15 10:41:19 +00:00
|
|
|
webhookMessage = await _rest.ExecuteWebhook(webhook.Id, webhook.Token, webhookReq, files, req.ThreadId);
|
2019-08-12 14:38:34 +00:00
|
|
|
}
|
2020-06-14 20:19:12 +00:00
|
|
|
catch (JsonReaderException)
|
|
|
|
{
|
|
|
|
// This happens sometimes when we hit a CloudFlare error (or similar) on Discord's end
|
|
|
|
// Nothing we can do about this - happens sometimes under server load, so just drop the message and give up
|
|
|
|
throw new WebhookExecutionErrorOnDiscordsEnd();
|
|
|
|
}
|
2020-12-22 12:15:26 +00:00
|
|
|
catch (Myriad.Rest.Exceptions.NotFoundException e)
|
2020-06-14 20:19:12 +00:00
|
|
|
{
|
2020-12-22 12:15:26 +00:00
|
|
|
if (e.ErrorCode == 10015 && !hasRetried)
|
2020-06-14 20:19:12 +00:00
|
|
|
{
|
|
|
|
// Error 10015 = "Unknown Webhook" - this likely means the webhook was deleted
|
|
|
|
// but is still in our cache. Invalidate, refresh, try again
|
2021-08-01 16:32:40 +00:00
|
|
|
_logger.Warning("Error invoking webhook {Webhook} in channel {Channel} (thread {ThreadId})",
|
2021-07-15 10:41:19 +00:00
|
|
|
webhook.Id, webhook.ChannelId, req.ThreadId);
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2020-12-22 12:15:26 +00:00
|
|
|
var newWebhook = await _webhookCache.InvalidateAndRefreshWebhook(req.ChannelId, webhook);
|
|
|
|
return await ExecuteWebhookInner(newWebhook, req, hasRetried: true);
|
2020-06-14 20:19:12 +00:00
|
|
|
}
|
2019-12-21 19:07:51 +00:00
|
|
|
|
2020-06-14 20:19:12 +00:00
|
|
|
throw;
|
|
|
|
}
|
2021-08-27 15:03:47 +00:00
|
|
|
}
|
2019-12-21 19:07:51 +00:00
|
|
|
|
2020-04-17 21:10:01 +00:00
|
|
|
// We don't care about whether the sending succeeds, and we don't want to *wait* for it, so we just fork it off
|
2021-07-15 10:41:19 +00:00
|
|
|
var _ = TrySendRemainingAttachments(webhook, req.Name, req.AvatarUrl, attachmentChunks, req.ThreadId);
|
2020-04-17 21:10:01 +00:00
|
|
|
|
2020-11-15 13:34:49 +00:00
|
|
|
return webhookMessage;
|
2020-04-17 21:10:01 +00:00
|
|
|
}
|
|
|
|
|
2021-07-15 10:41:19 +00:00
|
|
|
private async Task TrySendRemainingAttachments(Webhook webhook, string name, string avatarUrl, IReadOnlyList<IReadOnlyCollection<Message.Attachment>> attachmentChunks, ulong? threadId)
|
2020-04-17 21:10:01 +00:00
|
|
|
{
|
|
|
|
if (attachmentChunks.Count <= 1) return;
|
|
|
|
|
|
|
|
for (var i = 1; i < attachmentChunks.Count; i++)
|
|
|
|
{
|
2020-12-22 12:15:26 +00:00
|
|
|
var files = await GetAttachmentFiles(attachmentChunks[i]);
|
2021-08-27 15:03:47 +00:00
|
|
|
var req = new ExecuteWebhookRequest { Username = name, AvatarUrl = avatarUrl };
|
2021-07-15 10:41:19 +00:00
|
|
|
await _rest.ExecuteWebhook(webhook.Id, webhook.Token!, req, files, threadId);
|
2019-12-21 17:50:28 +00:00
|
|
|
}
|
2020-04-17 21:10:01 +00:00
|
|
|
}
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2020-12-22 12:15:26 +00:00
|
|
|
private async Task<MultipartFile[]> GetAttachmentFiles(IReadOnlyCollection<Message.Attachment> attachments)
|
2020-04-17 21:10:01 +00:00
|
|
|
{
|
2020-12-22 12:15:26 +00:00
|
|
|
async Task<MultipartFile> GetStream(Message.Attachment attachment)
|
2019-12-21 19:07:51 +00:00
|
|
|
{
|
2020-04-17 21:10:01 +00:00
|
|
|
var attachmentResponse = await _client.GetAsync(attachment.Url, HttpCompletionOption.ResponseHeadersRead);
|
2020-12-22 12:15:26 +00:00
|
|
|
return new(attachment.Filename, await attachmentResponse.Content.ReadAsStreamAsync());
|
2019-12-23 12:55:43 +00:00
|
|
|
}
|
2020-12-22 12:15:26 +00:00
|
|
|
|
|
|
|
return await Task.WhenAll(attachments.Select(GetStream));
|
2019-08-12 03:47:55 +00:00
|
|
|
}
|
2020-04-17 21:10:01 +00:00
|
|
|
|
2020-12-22 12:15:26 +00:00
|
|
|
private IReadOnlyList<IReadOnlyCollection<Message.Attachment>> ChunkAttachmentsOrThrow(
|
|
|
|
IReadOnlyList<Message.Attachment> attachments, int sizeThreshold)
|
2019-12-21 19:07:51 +00:00
|
|
|
{
|
|
|
|
// Splits a list of attachments into "chunks" of at most 8MB each
|
|
|
|
// If any individual attachment is larger than 8MB, will throw an error
|
2020-12-22 12:15:26 +00:00
|
|
|
var chunks = new List<List<Message.Attachment>>();
|
|
|
|
var list = new List<Message.Attachment>();
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2019-12-21 19:07:51 +00:00
|
|
|
foreach (var attachment in attachments)
|
|
|
|
{
|
2020-12-22 12:15:26 +00:00
|
|
|
if (attachment.Size >= sizeThreshold) throw Errors.AttachmentTooLarge;
|
2019-12-21 19:07:51 +00:00
|
|
|
|
2020-12-22 12:15:26 +00:00
|
|
|
if (list.Sum(a => a.Size) + attachment.Size >= sizeThreshold)
|
2019-12-21 19:07:51 +00:00
|
|
|
{
|
|
|
|
chunks.Add(list);
|
2020-12-22 12:15:26 +00:00
|
|
|
list = new List<Message.Attachment>();
|
2019-12-21 19:07:51 +00:00
|
|
|
}
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2019-12-21 19:07:51 +00:00
|
|
|
list.Add(attachment);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (list.Count > 0) chunks.Add(list);
|
|
|
|
return chunks;
|
|
|
|
}
|
|
|
|
|
2021-01-31 15:02:34 +00:00
|
|
|
private string FixProxyName(string name) => FixSingleCharacterName(FixClyde(name));
|
|
|
|
|
2019-08-12 03:47:55 +00:00
|
|
|
private string FixClyde(string name)
|
|
|
|
{
|
2020-11-15 12:12:30 +00:00
|
|
|
static string Replacement(Match m) => m.Groups[1].Value + "\u200A" + m.Groups[2].Value;
|
2019-08-12 03:47:55 +00:00
|
|
|
|
2020-11-15 12:12:30 +00:00
|
|
|
// Adds a Unicode hair space (\u200A) between the "c" and the "lyde" to avoid Discord matching it
|
2019-08-12 03:47:55 +00:00
|
|
|
// since Discord blocks webhooks containing the word "Clyde"... for some reason. /shrug
|
2020-11-15 12:12:30 +00:00
|
|
|
return Regex.Replace(name, "(c)(lyde)", Replacement, RegexOptions.IgnoreCase);
|
2019-08-12 03:47:55 +00:00
|
|
|
}
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2021-01-31 15:02:34 +00:00
|
|
|
private string FixSingleCharacterName(string proxyName)
|
|
|
|
{
|
|
|
|
if (proxyName.Length == 1)
|
|
|
|
return proxyName + "\u17b5";
|
|
|
|
return proxyName;
|
|
|
|
}
|
2019-08-12 03:47:55 +00:00
|
|
|
}
|
|
|
|
}
|