Add member avatar edit command
This also refactors a large portion of the DI toolchain, since I discovered that you shouldn't be reusing IDbConnection objects. Instead, most services and stores are now declared transient, and the webhook cache has been moved to a database-independent storage singleton by itself.
This commit is contained in:
parent
1824bfd6bb
commit
08afa2543b
@ -64,21 +64,23 @@ namespace PluralKit.Bot
|
||||
}
|
||||
|
||||
public ServiceProvider BuildServiceProvider() => new ServiceCollection()
|
||||
.AddSingleton(_config.GetSection("PluralKit").Get<CoreConfig>() ?? new CoreConfig())
|
||||
.AddSingleton(_config.GetSection("PluralKit").GetSection("Bot").Get<BotConfig>() ?? new BotConfig())
|
||||
.AddTransient(_ => _config.GetSection("PluralKit").Get<CoreConfig>() ?? new CoreConfig())
|
||||
.AddTransient(_ => _config.GetSection("PluralKit").GetSection("Bot").Get<BotConfig>() ?? new BotConfig())
|
||||
|
||||
.AddScoped<IDbConnection>(svc => new NpgsqlConnection(svc.GetRequiredService<CoreConfig>().Database))
|
||||
|
||||
.AddSingleton<IDiscordClient, DiscordSocketClient>()
|
||||
.AddSingleton<IDbConnection, NpgsqlConnection>()
|
||||
.AddSingleton<Bot>()
|
||||
|
||||
.AddSingleton<CommandService>()
|
||||
.AddSingleton<EmbedService>()
|
||||
.AddSingleton<LogChannelService>()
|
||||
.AddSingleton<ProxyService>()
|
||||
.AddTransient<CommandService>()
|
||||
.AddTransient<EmbedService>()
|
||||
.AddTransient<ProxyService>()
|
||||
.AddTransient<LogChannelService>()
|
||||
.AddSingleton<WebhookCacheService>()
|
||||
|
||||
.AddSingleton<SystemStore>()
|
||||
.AddSingleton<MemberStore>()
|
||||
.AddSingleton<MessageStore>()
|
||||
.AddTransient<SystemStore>()
|
||||
.AddTransient<MemberStore>()
|
||||
.AddTransient<MessageStore>()
|
||||
.BuildServiceProvider();
|
||||
}
|
||||
class Bot
|
||||
@ -154,6 +156,8 @@ namespace PluralKit.Bot
|
||||
|
||||
private async Task MessageReceived(SocketMessage _arg)
|
||||
{
|
||||
var serviceScope = _services.CreateScope();
|
||||
|
||||
// Ignore system messages (member joined, message pinned, etc)
|
||||
var arg = _arg as SocketUserMessage;
|
||||
if (arg == null) return;
|
||||
@ -169,7 +173,7 @@ namespace PluralKit.Bot
|
||||
// and start command execution
|
||||
// Note system may be null if user has no system, hence `OrDefault`
|
||||
var system = await _connection.QueryFirstOrDefaultAsync<PKSystem>("select systems.* from systems, accounts where accounts.uid = @Id and systems.id = accounts.system", new { Id = arg.Author.Id });
|
||||
await _commands.ExecuteAsync(new PKCommandContext(_client, arg as SocketUserMessage, _connection, system), argPos, _services);
|
||||
await _commands.ExecuteAsync(new PKCommandContext(_client, arg, _connection, system), argPos, serviceScope.ServiceProvider);
|
||||
}
|
||||
else
|
||||
{
|
||||
|
@ -1,8 +1,12 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
using Discord;
|
||||
using Discord.Commands;
|
||||
using NodaTime;
|
||||
using Image = SixLabors.ImageSharp.Image;
|
||||
|
||||
namespace PluralKit.Bot.Commands
|
||||
{
|
||||
@ -179,6 +183,22 @@ namespace PluralKit.Bot.Commands
|
||||
await Context.Channel.SendMessageAsync($"{Emojis.Success} Member deleted.");
|
||||
}
|
||||
|
||||
[Command("avatar")]
|
||||
[Alias("profile", "picture", "icon", "image", "pic", "pfp")]
|
||||
[Remarks("member <member> avatar <avatar url>")]
|
||||
[MustPassOwnMember]
|
||||
public async Task MemberAvatar([Remainder] string avatarUrl = null)
|
||||
{
|
||||
string url = avatarUrl ?? Context.Message.Attachments.FirstOrDefault()?.ProxyUrl;
|
||||
if (url != null) await Context.BusyIndicator(() => Utils.VerifyAvatarOrThrow(url));
|
||||
|
||||
ContextEntity.AvatarUrl = url;
|
||||
await Members.Save(ContextEntity);
|
||||
|
||||
var embed = url != null ? new EmbedBuilder().WithImageUrl(url).Build() : null;
|
||||
await Context.Channel.SendMessageAsync($"{Emojis.Success} Member avatar {(url == null ? "cleared" : "changed")}.", embed: embed);
|
||||
}
|
||||
|
||||
[Command]
|
||||
[Alias("view", "show", "info")]
|
||||
[Remarks("member")]
|
||||
@ -187,6 +207,7 @@ namespace PluralKit.Bot.Commands
|
||||
var system = await Systems.GetById(member.System);
|
||||
await Context.Channel.SendMessageAsync(embed: await Embeds.CreateMemberEmbed(system, member));
|
||||
}
|
||||
|
||||
public override async Task<PKMember> ReadContextParameterAsync(string value)
|
||||
{
|
||||
var res = await new PKMemberTypeReader().ReadAsync(Context, value, _services);
|
||||
|
@ -103,5 +103,29 @@ namespace PluralKit.Bot {
|
||||
}
|
||||
|
||||
public static async Task<bool> HasPermission(this ICommandContext ctx, ChannelPermission permission) => (await Permissions(ctx)).Has(permission);
|
||||
|
||||
public static async Task BusyIndicator(this ICommandContext ctx, Func<Task> f, string emoji = "\u23f3" /* hourglass */)
|
||||
{
|
||||
await ctx.BusyIndicator<object>(async () =>
|
||||
{
|
||||
await f();
|
||||
return null;
|
||||
}, emoji);
|
||||
}
|
||||
|
||||
public static async Task<T> BusyIndicator<T>(this ICommandContext ctx, Func<Task<T>> f, string emoji = "\u23f3" /* hourglass */)
|
||||
{
|
||||
var task = f();
|
||||
|
||||
try
|
||||
{
|
||||
await Task.WhenAll(ctx.Message.AddReactionAsync(new Emoji(emoji)), task);
|
||||
return await task;
|
||||
}
|
||||
finally
|
||||
{
|
||||
ctx.Message.RemoveReactionAsync(new Emoji(emoji), ctx.Client.CurrentUser);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,3 +1,6 @@
|
||||
using System.Net;
|
||||
using Humanizer;
|
||||
|
||||
namespace PluralKit.Bot {
|
||||
public static class Errors {
|
||||
// TODO: is returning constructed errors and throwing them at call site a good idea, or should these be methods that insta-throw instead?
|
||||
@ -20,5 +23,10 @@ namespace PluralKit.Bot {
|
||||
public static PKError ProxyMultipleText => new PKSyntaxError("Example proxy message must contain the string 'text' exactly once.");
|
||||
|
||||
public static PKError MemberDeleteCancelled => new PKError($"Member deletion cancelled. Stay safe! {Emojis.ThumbsUp}");
|
||||
public static PKError AvatarServerError(HttpStatusCode statusCode) => new PKError($"Server responded with status code {(int) statusCode}, are you sure your link is working?");
|
||||
public static PKError AvatarFileSizeLimit(long size) => new PKError($"File size too large ({size.Bytes().ToString("#.#")} > {Limits.AvatarFileSizeLimit.Bytes().ToString("#.#")}), try shrinking or compressing the image.");
|
||||
public static PKError AvatarNotAnImage(string mimeType) => new PKError($"The given link does not point to an image{(mimeType != null ? $" ({mimeType})" : "")}. Make sure you're using a direct link (ending in .jpg, .png, .gif).");
|
||||
public static PKError AvatarDimensionsTooLarge(int width, int height) => new PKError($"Image too large ({width}x{height} > {Limits.AvatarDimensionLimit}x{Limits.AvatarDimensionLimit}), try resizing the image.");
|
||||
public static PKError InvalidUrl(string url) => new PKError($"The given URL is invalid.");
|
||||
}
|
||||
}
|
@ -5,5 +5,8 @@ namespace PluralKit.Bot {
|
||||
public static readonly int MaxDescriptionLength = 1000;
|
||||
public static readonly int MaxMemberNameLength = 50;
|
||||
public static readonly int MaxPronounsLength = 100;
|
||||
|
||||
public static readonly long AvatarFileSizeLimit = 1024 * 1024;
|
||||
public static readonly int AvatarDimensionLimit = 1000;
|
||||
}
|
||||
}
|
@ -13,6 +13,8 @@
|
||||
<PackageReference Include="Discord.Net.Commands" Version="2.0.1" />
|
||||
<PackageReference Include="Discord.Net.Webhook" Version="2.0.1" />
|
||||
<PackageReference Include="Discord.Net.WebSocket" Version="2.0.1" />
|
||||
<PackageReference Include="Humanizer.Core" Version="2.6.2" />
|
||||
<PackageReference Include="SixLabors.ImageSharp" Version="1.0.0-beta0006" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
@ -31,18 +31,17 @@ namespace PluralKit.Bot
|
||||
private IDiscordClient _client;
|
||||
private IDbConnection _connection;
|
||||
private LogChannelService _logger;
|
||||
private WebhookCacheService _webhookCache;
|
||||
private MessageStore _messageStorage;
|
||||
|
||||
private ConcurrentDictionary<ulong, Lazy<Task<IWebhook>>> _webhooks;
|
||||
|
||||
public ProxyService(IDiscordClient client, IDbConnection connection, LogChannelService logger, MessageStore messageStorage)
|
||||
public ProxyService(IDiscordClient client, WebhookCacheService webhookCache, IDbConnection connection, LogChannelService logger, MessageStore messageStorage)
|
||||
{
|
||||
this._client = client;
|
||||
this._webhookCache = webhookCache;
|
||||
this._connection = connection;
|
||||
this._logger = logger;
|
||||
this._messageStorage = messageStorage;
|
||||
|
||||
_webhooks = new ConcurrentDictionary<ulong, Lazy<Task<IWebhook>>>();
|
||||
}
|
||||
|
||||
private ProxyMatch GetProxyTagMatch(string message, IEnumerable<ProxyDatabaseResult> potentials) {
|
||||
@ -70,7 +69,7 @@ namespace PluralKit.Bot
|
||||
if (match == null) return;
|
||||
|
||||
// Fetch a webhook for this channel, and send the proxied message
|
||||
var webhook = await GetWebhookByChannelCaching(message.Channel as ITextChannel);
|
||||
var webhook = await _webhookCache.GetWebhook(message.Channel as ITextChannel);
|
||||
var hookMessage = await ExecuteWebhook(webhook, match.InnerText, match.ProxyName, match.Member.AvatarUrl, message.Attachments.FirstOrDefault());
|
||||
|
||||
// Store the message in the database, and log it in the log channel (if applicable)
|
||||
@ -96,28 +95,6 @@ namespace PluralKit.Bot
|
||||
return await webhook.Channel.GetMessageAsync(messageId);
|
||||
}
|
||||
|
||||
private async Task<IWebhook> GetWebhookByChannelCaching(ITextChannel channel) {
|
||||
// We cache the webhook through a Lazy<Task<T>>, this way we make sure to only create one webhook per channel
|
||||
// TODO: make sure this is sharding-safe. Intuition says yes, since one channel is guaranteed to only be handled by one shard, but best to make sure
|
||||
var webhookFactory = _webhooks.GetOrAdd(channel.Id, new Lazy<Task<IWebhook>>(() => FindWebhookByChannel(channel)));
|
||||
return await webhookFactory.Value;
|
||||
}
|
||||
|
||||
private async Task<IWebhook> FindWebhookByChannel(ITextChannel channel) {
|
||||
IWebhook webhook;
|
||||
|
||||
webhook = (await channel.GetWebhooksAsync()).FirstOrDefault(IsWebhookMine);
|
||||
if (webhook != null) return webhook;
|
||||
|
||||
webhook = await channel.CreateWebhookAsync("PluralKit Proxy Webhook");
|
||||
return webhook;
|
||||
}
|
||||
|
||||
private bool IsWebhookMine(IWebhook arg)
|
||||
{
|
||||
return arg.Creator.Id == this._client.CurrentUser.Id && arg.Name == "PluralKit Proxy Webhook";
|
||||
}
|
||||
|
||||
public async Task HandleReactionAddedAsync(Cacheable<IUserMessage, ulong> message, ISocketMessageChannel channel, SocketReaction reaction)
|
||||
{
|
||||
// Make sure it's the right emoji (red X)
|
||||
|
48
PluralKit.Bot/Services/WebhookCacheService.cs
Normal file
48
PluralKit.Bot/Services/WebhookCacheService.cs
Normal file
@ -0,0 +1,48 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Discord;
|
||||
using Discord.WebSocket;
|
||||
|
||||
namespace PluralKit.Bot
|
||||
{
|
||||
public class WebhookCacheService
|
||||
{
|
||||
public static readonly string WebhookName = "PluralKit Proxy Webhook";
|
||||
|
||||
private IDiscordClient _client;
|
||||
private ConcurrentDictionary<ulong, Lazy<Task<IWebhook>>> _webhooks;
|
||||
|
||||
public WebhookCacheService(IDiscordClient client)
|
||||
{
|
||||
this._client = client;
|
||||
_webhooks = new ConcurrentDictionary<ulong, Lazy<Task<IWebhook>>>();
|
||||
}
|
||||
|
||||
public async Task<IWebhook> GetWebhook(ulong channelId)
|
||||
{
|
||||
var channel = await _client.GetChannelAsync(channelId) as ITextChannel;
|
||||
if (channel == null) return null;
|
||||
return await GetWebhook(channel);
|
||||
}
|
||||
|
||||
public async Task<IWebhook> GetWebhook(ITextChannel channel)
|
||||
{
|
||||
// We cache the webhook through a Lazy<Task<T>>, this way we make sure to only create one webhook per channel
|
||||
// If the webhook is requested twice before it's actually been found, the Lazy<T> wrapper will stop the
|
||||
// webhook from being created twice.
|
||||
var lazyWebhookValue =
|
||||
_webhooks.GetOrAdd(channel.Id, new Lazy<Task<IWebhook>>(() => GetOrCreateWebhook(channel)));
|
||||
return await lazyWebhookValue.Value;
|
||||
}
|
||||
|
||||
private async Task<IWebhook> GetOrCreateWebhook(ITextChannel channel) =>
|
||||
await FindExistingWebhook(channel) ?? await GetOrCreateWebhook(channel);
|
||||
|
||||
private async Task<IWebhook> FindExistingWebhook(ITextChannel channel) => (await channel.GetWebhooksAsync()).FirstOrDefault(IsWebhookMine);
|
||||
|
||||
private async Task<IWebhook> DoCreateWebhook(ITextChannel channel) => await channel.CreateWebhookAsync(WebhookName);
|
||||
private bool IsWebhookMine(IWebhook arg) => arg.Creator.Id == _client.CurrentUser.Id && arg.Name == WebhookName;
|
||||
}
|
||||
}
|
@ -1,7 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
using Dapper;
|
||||
using Discord;
|
||||
@ -9,7 +9,7 @@ using Discord.Commands;
|
||||
using Discord.Commands.Builders;
|
||||
using Discord.WebSocket;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NodaTime;
|
||||
using Image = SixLabors.ImageSharp.Image;
|
||||
|
||||
namespace PluralKit.Bot
|
||||
{
|
||||
@ -17,6 +17,48 @@ namespace PluralKit.Bot
|
||||
public static string NameAndMention(this IUser user) {
|
||||
return $"{user.Username}#{user.Discriminator} ({user.Mention})";
|
||||
}
|
||||
|
||||
public static async Task VerifyAvatarOrThrow(string url)
|
||||
{
|
||||
// List of MIME types we consider acceptable
|
||||
var acceptableMimeTypes = new[]
|
||||
{
|
||||
"image/jpeg",
|
||||
"image/gif",
|
||||
"image/png"
|
||||
// TODO: add image/webp once ImageSharp supports this
|
||||
};
|
||||
|
||||
using (var client = new HttpClient())
|
||||
{
|
||||
Uri uri;
|
||||
try
|
||||
{
|
||||
uri = new Uri(url);
|
||||
if (!uri.IsAbsoluteUri) throw Errors.InvalidUrl(url);
|
||||
}
|
||||
catch (UriFormatException)
|
||||
{
|
||||
throw Errors.InvalidUrl(url);
|
||||
}
|
||||
|
||||
var response = await client.GetAsync(uri);
|
||||
if (!response.IsSuccessStatusCode) // Check status code
|
||||
throw Errors.AvatarServerError(response.StatusCode);
|
||||
if (response.Content.Headers.ContentLength == null) // Check presence of content length
|
||||
throw Errors.AvatarNotAnImage(null);
|
||||
if (response.Content.Headers.ContentLength > Limits.AvatarFileSizeLimit) // Check content length
|
||||
throw Errors.AvatarFileSizeLimit(response.Content.Headers.ContentLength.Value);
|
||||
if (!acceptableMimeTypes.Contains(response.Content.Headers.ContentType.MediaType)) // Check MIME type
|
||||
throw Errors.AvatarNotAnImage(response.Content.Headers.ContentType.MediaType);
|
||||
|
||||
// Parse the image header in a worker
|
||||
var stream = await response.Content.ReadAsStreamAsync();
|
||||
var image = await Task.Run(() => Image.Identify(stream));
|
||||
if (image.Width > Limits.AvatarDimensionLimit || image.Height > Limits.AvatarDimensionLimit) // Check image size
|
||||
throw Errors.AvatarDimensionsTooLarge(image.Width, image.Height);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class UlongEncodeAsLongHandler : SqlMapper.TypeHandler<ulong>
|
||||
|
Loading…
Reference in New Issue
Block a user