2020-02-26 18:47:30 +00:00
|
|
|
using System;
|
2019-12-21 19:07:51 +00:00
|
|
|
using System.Collections.Generic;
|
|
|
|
using System.IO;
|
|
|
|
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
|
|
|
|
2020-04-17 21:10:01 +00:00
|
|
|
using DSharpPlus.Entities;
|
|
|
|
using DSharpPlus.Exceptions;
|
2019-12-21 17:50:28 +00:00
|
|
|
|
|
|
|
using Humanizer;
|
|
|
|
|
|
|
|
using Newtonsoft.Json;
|
2020-06-14 20:19:12 +00:00
|
|
|
using Newtonsoft.Json.Serialization;
|
2019-12-21 17:50:28 +00:00
|
|
|
|
2019-08-12 03:47:55 +00:00
|
|
|
using Serilog;
|
|
|
|
|
|
|
|
namespace PluralKit.Bot
|
|
|
|
{
|
2020-02-26 18:47:30 +00:00
|
|
|
public class WebhookExecutionErrorOnDiscordsEnd: Exception {
|
|
|
|
}
|
|
|
|
|
2020-03-26 23:01:42 +00:00
|
|
|
public class WebhookRateLimited: WebhookExecutionErrorOnDiscordsEnd {
|
|
|
|
// 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
|
|
|
|
}
|
|
|
|
|
2019-12-22 23:35:42 +00:00
|
|
|
public class WebhookExecutorService
|
2019-08-12 03:47:55 +00:00
|
|
|
{
|
|
|
|
private WebhookCacheService _webhookCache;
|
|
|
|
private ILogger _logger;
|
|
|
|
private IMetrics _metrics;
|
|
|
|
private HttpClient _client;
|
|
|
|
|
2020-04-30 22:00:33 +00:00
|
|
|
public WebhookExecutorService(IMetrics metrics, WebhookCacheService webhookCache, ILogger logger, HttpClient client)
|
2019-08-12 03:47:55 +00:00
|
|
|
{
|
|
|
|
_metrics = metrics;
|
|
|
|
_webhookCache = webhookCache;
|
2019-12-22 23:29:04 +00:00
|
|
|
_client = client;
|
2019-08-12 03:47:55 +00:00
|
|
|
_logger = logger.ForContext<WebhookExecutorService>();
|
|
|
|
}
|
|
|
|
|
2020-04-17 21:10:01 +00:00
|
|
|
public async Task<ulong> ExecuteWebhook(DiscordChannel channel, string name, string avatarUrl, string content, IReadOnlyList<DiscordAttachment> attachments)
|
2019-08-12 03:47:55 +00:00
|
|
|
{
|
2019-10-28 16:03:16 +00:00
|
|
|
_logger.Verbose("Invoking webhook in channel {Channel}", channel.Id);
|
2019-08-12 03:47:55 +00:00
|
|
|
|
|
|
|
// Get a webhook, execute it
|
|
|
|
var webhook = await _webhookCache.GetWebhook(channel);
|
2020-04-17 21:10:01 +00:00
|
|
|
var id = await ExecuteWebhookInner(channel, webhook, name, avatarUrl, content, attachments);
|
2019-08-12 03:47:55 +00:00
|
|
|
|
|
|
|
// Log the relevant metrics
|
|
|
|
_metrics.Measure.Meter.Mark(BotMetrics.MessagesProxied);
|
|
|
|
_logger.Information("Invoked webhook {Webhook} in channel {Channel}", webhook.Id,
|
|
|
|
channel.Id);
|
|
|
|
|
|
|
|
return id;
|
|
|
|
}
|
|
|
|
|
2020-04-17 21:10:01 +00:00
|
|
|
private async Task<ulong> ExecuteWebhookInner(DiscordChannel channel, DiscordWebhook webhook, string name, string avatarUrl, string content,
|
|
|
|
IReadOnlyList<DiscordAttachment> attachments, bool hasRetried = false)
|
2019-08-12 03:47:55 +00:00
|
|
|
{
|
2020-04-17 21:10:01 +00:00
|
|
|
var dwb = new DiscordWebhookBuilder();
|
|
|
|
dwb.WithUsername(FixClyde(name).Truncate(80));
|
|
|
|
dwb.WithContent(content.Truncate(2000));
|
|
|
|
if (avatarUrl != null) dwb.WithAvatarUrl(avatarUrl);
|
|
|
|
|
2019-12-23 12:55:43 +00:00
|
|
|
var attachmentChunks = ChunkAttachmentsOrThrow(attachments, 8 * 1024 * 1024);
|
2019-12-21 19:07:51 +00:00
|
|
|
if (attachmentChunks.Count > 0)
|
2019-12-22 21:56:18 +00:00
|
|
|
{
|
2020-04-17 21:10:01 +00:00
|
|
|
_logger.Information("Invoking webhook with {AttachmentCount} attachments totalling {AttachmentSize} MiB in {AttachmentChunks} chunks", attachments.Count, attachments.Select(a => a.FileSize).Sum() / 1024 / 1024, attachmentChunks.Count);
|
|
|
|
await AddAttachmentsToBuilder(dwb, attachmentChunks[0]);
|
2019-12-23 12:55:43 +00:00
|
|
|
}
|
2020-03-26 23:01:42 +00:00
|
|
|
|
2020-04-17 21:10:01 +00:00
|
|
|
DiscordMessage response;
|
2020-06-14 20:19:12 +00:00
|
|
|
using (_metrics.Measure.Timer.Time(BotMetrics.WebhookResponseTime)) {
|
|
|
|
try
|
2019-08-12 14:38:34 +00:00
|
|
|
{
|
2020-06-14 20:19:12 +00:00
|
|
|
response = await webhook.ExecuteAsync(dwb);
|
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();
|
|
|
|
}
|
|
|
|
catch (NotFoundException e)
|
|
|
|
{
|
|
|
|
var errorText = e.WebResponse?.Response;
|
|
|
|
if (errorText != null && errorText.Contains("10015") && !hasRetried)
|
|
|
|
{
|
|
|
|
// Error 10015 = "Unknown Webhook" - this likely means the webhook was deleted
|
|
|
|
// but is still in our cache. Invalidate, refresh, try again
|
|
|
|
_logger.Warning("Error invoking webhook {Webhook} in channel {Channel}", webhook.Id, webhook.ChannelId);
|
|
|
|
|
|
|
|
var newWebhook = await _webhookCache.InvalidateAndRefreshWebhook(channel, webhook);
|
|
|
|
return await ExecuteWebhookInner(channel, newWebhook, name, avatarUrl, content, attachments, hasRetried: true);
|
|
|
|
}
|
2019-12-21 19:07:51 +00:00
|
|
|
|
2020-06-14 20:19:12 +00:00
|
|
|
throw;
|
|
|
|
}
|
|
|
|
}
|
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
|
|
|
|
var _ = TrySendRemainingAttachments(webhook, name, avatarUrl, attachmentChunks);
|
|
|
|
|
|
|
|
return response.Id;
|
|
|
|
}
|
|
|
|
|
|
|
|
private async Task TrySendRemainingAttachments(DiscordWebhook webhook, string name, string avatarUrl, IReadOnlyList<IReadOnlyCollection<DiscordAttachment>> attachmentChunks)
|
|
|
|
{
|
|
|
|
if (attachmentChunks.Count <= 1) return;
|
|
|
|
|
|
|
|
for (var i = 1; i < attachmentChunks.Count; i++)
|
|
|
|
{
|
|
|
|
var dwb = new DiscordWebhookBuilder();
|
|
|
|
if (avatarUrl != null) dwb.WithAvatarUrl(avatarUrl);
|
|
|
|
dwb.WithUsername(name);
|
|
|
|
await AddAttachmentsToBuilder(dwb, attachmentChunks[i]);
|
|
|
|
await webhook.ExecuteAsync(dwb);
|
2019-12-21 17:50:28 +00:00
|
|
|
}
|
2020-04-17 21:10:01 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
private async Task AddAttachmentsToBuilder(DiscordWebhookBuilder dwb, IReadOnlyCollection<DiscordAttachment> attachments)
|
|
|
|
{
|
|
|
|
async Task<(DiscordAttachment, Stream)> GetStream(DiscordAttachment 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);
|
|
|
|
return (attachment, await attachmentResponse.Content.ReadAsStreamAsync());
|
2019-12-23 12:55:43 +00:00
|
|
|
}
|
2019-12-21 19:07:51 +00:00
|
|
|
|
2020-04-17 21:10:01 +00:00
|
|
|
foreach (var (attachment, attachmentStream) in await Task.WhenAll(attachments.Select(GetStream)))
|
|
|
|
dwb.AddFile(attachment.FileName, attachmentStream);
|
2019-08-12 03:47:55 +00:00
|
|
|
}
|
2020-04-17 21:10:01 +00:00
|
|
|
|
|
|
|
private IReadOnlyList<IReadOnlyCollection<DiscordAttachment>> ChunkAttachmentsOrThrow(
|
|
|
|
IReadOnlyList<DiscordAttachment> 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-04-17 21:10:01 +00:00
|
|
|
var chunks = new List<List<DiscordAttachment>>();
|
|
|
|
var list = new List<DiscordAttachment>();
|
2019-12-21 19:07:51 +00:00
|
|
|
|
|
|
|
foreach (var attachment in attachments)
|
|
|
|
{
|
2020-04-17 21:10:01 +00:00
|
|
|
if (attachment.FileSize >= sizeThreshold) throw Errors.AttachmentTooLarge;
|
2019-12-21 19:07:51 +00:00
|
|
|
|
2020-04-17 21:10:01 +00:00
|
|
|
if (list.Sum(a => a.FileSize) + attachment.FileSize >= sizeThreshold)
|
2019-12-21 19:07:51 +00:00
|
|
|
{
|
|
|
|
chunks.Add(list);
|
2020-04-17 21:10:01 +00:00
|
|
|
list = new List<DiscordAttachment>();
|
2019-12-21 19:07:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
list.Add(attachment);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (list.Count > 0) chunks.Add(list);
|
|
|
|
return chunks;
|
|
|
|
}
|
|
|
|
|
2019-08-12 03:47:55 +00:00
|
|
|
private string FixClyde(string name)
|
|
|
|
{
|
|
|
|
// Check if the name contains "Clyde" - if not, do nothing
|
|
|
|
var match = Regex.Match(name, "clyde", RegexOptions.IgnoreCase);
|
|
|
|
if (!match.Success) return name;
|
|
|
|
|
|
|
|
// 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);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|