refactor project structure
This commit is contained in:
45
PluralKit.Bot/Services/EmbedService.cs
Normal file
45
PluralKit.Bot/Services/EmbedService.cs
Normal file
@@ -0,0 +1,45 @@
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Discord;
|
||||
|
||||
namespace PluralKit.Bot {
|
||||
public class EmbedService {
|
||||
private SystemStore _systems;
|
||||
private IDiscordClient _client;
|
||||
|
||||
public EmbedService(SystemStore systems, IDiscordClient client)
|
||||
{
|
||||
this._systems = systems;
|
||||
this._client = client;
|
||||
}
|
||||
|
||||
public async Task<Embed> CreateSystemEmbed(PKSystem system) {
|
||||
var accounts = await _systems.GetLinkedAccountIds(system);
|
||||
|
||||
// Fetch/render info for all accounts simultaneously
|
||||
var users = await Task.WhenAll(accounts.Select(async uid => (await _client.GetUserAsync(uid)).NameAndMention() ?? $"(deleted account {uid})"));
|
||||
|
||||
var eb = new EmbedBuilder()
|
||||
.WithColor(Color.Blue)
|
||||
.WithTitle(system.Name ?? null)
|
||||
.WithDescription(system.Description?.Truncate(1024))
|
||||
.WithThumbnailUrl(system.AvatarUrl ?? null)
|
||||
.WithFooter($"System ID: {system.Hid}");
|
||||
|
||||
eb.AddField("Linked accounts", string.Join(", ", users));
|
||||
eb.AddField("Members", $"(see `pk;system {system.Hid} list` or `pk;system {system.Hid} list full`)");
|
||||
// TODO: fronter
|
||||
return eb.Build();
|
||||
}
|
||||
|
||||
public Embed CreateLoggedMessageEmbed(PKSystem system, PKMember member, IMessage message, IUser sender) {
|
||||
// TODO: pronouns in ?-reacted response using this card
|
||||
return new EmbedBuilder()
|
||||
.WithAuthor($"#{message.Channel.Name}: {member.Name}", member.AvatarUrl)
|
||||
.WithDescription(message.Content)
|
||||
.WithFooter($"System ID: {system.Hid} | Member ID: {member.Hid} | Sender: ${sender.Username}#{sender.Discriminator} ({sender.Id}) | Message ID: ${message.Id}")
|
||||
.WithTimestamp(message.Timestamp)
|
||||
.Build();
|
||||
}
|
||||
}
|
||||
}
|
47
PluralKit.Bot/Services/LogChannelService.cs
Normal file
47
PluralKit.Bot/Services/LogChannelService.cs
Normal file
@@ -0,0 +1,47 @@
|
||||
using System.Data;
|
||||
using System.Threading.Tasks;
|
||||
using Dapper;
|
||||
using Discord;
|
||||
|
||||
namespace PluralKit.Bot {
|
||||
class ServerDefinition {
|
||||
public ulong Id;
|
||||
public ulong LogChannel;
|
||||
}
|
||||
|
||||
class LogChannelService {
|
||||
private IDiscordClient _client;
|
||||
private IDbConnection _connection;
|
||||
private EmbedService _embed;
|
||||
|
||||
public LogChannelService(IDiscordClient client, IDbConnection connection, EmbedService embed)
|
||||
{
|
||||
this._client = client;
|
||||
this._connection = connection;
|
||||
this._embed = embed;
|
||||
}
|
||||
|
||||
public async Task LogMessage(PKSystem system, PKMember member, IMessage message, IUser sender) {
|
||||
var channel = await GetLogChannel((message.Channel as IGuildChannel).Guild);
|
||||
if (channel == null) return;
|
||||
|
||||
var embed = _embed.CreateLoggedMessageEmbed(system, member, message, sender);
|
||||
await channel.SendMessageAsync(text: message.GetJumpUrl(), embed: embed);
|
||||
}
|
||||
|
||||
public async Task<ITextChannel> GetLogChannel(IGuild guild) {
|
||||
var server = await _connection.QueryFirstAsync<ServerDefinition>("select * from servers where id = @Id", new { Id = guild.Id });
|
||||
if (server == null) return null;
|
||||
return await _client.GetChannelAsync(server.LogChannel) as ITextChannel;
|
||||
}
|
||||
|
||||
public async Task SetLogChannel(IGuild guild, ITextChannel newLogChannel) {
|
||||
var def = new ServerDefinition {
|
||||
Id = guild.Id,
|
||||
LogChannel = newLogChannel.Id
|
||||
};
|
||||
|
||||
await _connection.ExecuteAsync("insert into servers(id, log_channel) values (@Id, @LogChannel) on conflict (id) do update set log_channel = @LogChannel", def);
|
||||
}
|
||||
}
|
||||
}
|
151
PluralKit.Bot/Services/ProxyService.cs
Normal file
151
PluralKit.Bot/Services/ProxyService.cs
Normal file
@@ -0,0 +1,151 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Threading.Tasks;
|
||||
using Dapper;
|
||||
using Discord;
|
||||
using Discord.Rest;
|
||||
using Discord.Webhook;
|
||||
using Discord.WebSocket;
|
||||
|
||||
namespace PluralKit.Bot
|
||||
{
|
||||
class ProxyDatabaseResult
|
||||
{
|
||||
public PKSystem System;
|
||||
public PKMember Member;
|
||||
}
|
||||
|
||||
class ProxyMatch {
|
||||
public PKMember Member;
|
||||
public PKSystem System;
|
||||
public string InnerText;
|
||||
|
||||
public string ProxyName => Member.Name + (System.Tag.Length > 0 ? " " + System.Tag : "");
|
||||
}
|
||||
|
||||
class ProxyService {
|
||||
private IDiscordClient _client;
|
||||
private IDbConnection _connection;
|
||||
private LogChannelService _logger;
|
||||
private MessageStore _messageStorage;
|
||||
|
||||
private ConcurrentDictionary<ulong, Lazy<Task<IWebhook>>> _webhooks;
|
||||
|
||||
public ProxyService(IDiscordClient client, IDbConnection connection, LogChannelService logger, MessageStore messageStorage)
|
||||
{
|
||||
this._client = client;
|
||||
this._connection = connection;
|
||||
this._logger = logger;
|
||||
this._messageStorage = messageStorage;
|
||||
|
||||
_webhooks = new ConcurrentDictionary<ulong, Lazy<Task<IWebhook>>>();
|
||||
}
|
||||
|
||||
private ProxyMatch GetProxyTagMatch(string message, IEnumerable<ProxyDatabaseResult> potentials) {
|
||||
// TODO: add detection of leading @mention
|
||||
|
||||
// Sort by specificity (prefix+suffix first, prefix/suffix second)
|
||||
var ordered = potentials.OrderByDescending((p) => (p.Member.Prefix != null ? 0 : 1) + (p.Member.Suffix != null ? 0 : 1));
|
||||
foreach (var potential in ordered) {
|
||||
var prefix = potential.Member.Prefix ?? "";
|
||||
var suffix = potential.Member.Suffix ?? "";
|
||||
|
||||
if (message.StartsWith(prefix) && message.EndsWith(suffix)) {
|
||||
var inner = message.Substring(prefix.Length, message.Length - prefix.Length - suffix.Length);
|
||||
return new ProxyMatch { Member = potential.Member, System = potential.System, InnerText = inner };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public async Task HandleMessageAsync(IMessage message) {
|
||||
var results = await _connection.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 });
|
||||
|
||||
// Find a member with proxy tags matching the message
|
||||
var match = GetProxyTagMatch(message.Content, results);
|
||||
if (match == null) return;
|
||||
|
||||
// Fetch a webhook for this channel, and send the proxied message
|
||||
var webhook = await GetWebhookByChannelCaching(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)
|
||||
await _messageStorage.Store(message.Author.Id, hookMessage.Id, hookMessage.Channel.Id, match.Member);
|
||||
await _logger.LogMessage(match.System, match.Member, hookMessage, message.Author);
|
||||
|
||||
// Wait a second or so before deleting the original message
|
||||
await Task.Delay(1000);
|
||||
await message.DeleteAsync();
|
||||
}
|
||||
|
||||
private async Task<IMessage> ExecuteWebhook(IWebhook webhook, string text, string username, string avatarUrl, IAttachment attachment) {
|
||||
var client = new DiscordWebhookClient(webhook);
|
||||
|
||||
ulong messageId;
|
||||
if (attachment != null) {
|
||||
using (var stream = await WebRequest.CreateHttp(attachment.Url).GetRequestStreamAsync()) {
|
||||
messageId = await client.SendFileAsync(stream, filename: attachment.Filename, text: text, username: username, avatarUrl: avatarUrl);
|
||||
}
|
||||
} else {
|
||||
messageId = await client.SendMessageAsync(text, username: username, avatarUrl: avatarUrl);
|
||||
}
|
||||
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)
|
||||
if (reaction.Emote.Name != "\u274C") return;
|
||||
|
||||
// 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
|
||||
if (storedMessage.SenderId != reaction.UserId) return;
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user