2019-04-21 13:33:22 +00:00
|
|
|
using System;
|
2019-06-15 10:19:44 +00:00
|
|
|
using System.Globalization;
|
2019-04-29 15:42:09 +00:00
|
|
|
using System.Linq;
|
2019-05-16 23:23:09 +00:00
|
|
|
using System.Net.Http;
|
2019-07-10 11:44:03 +00:00
|
|
|
using System.Text.RegularExpressions;
|
2019-04-21 13:33:22 +00:00
|
|
|
using System.Threading.Tasks;
|
|
|
|
using Discord;
|
|
|
|
using Discord.Commands;
|
|
|
|
using Discord.Commands.Builders;
|
|
|
|
using Discord.WebSocket;
|
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
2019-07-09 22:19:18 +00:00
|
|
|
using PluralKit.Core;
|
2019-05-16 23:23:09 +00:00
|
|
|
using Image = SixLabors.ImageSharp.Image;
|
2019-04-21 13:33:22 +00:00
|
|
|
|
|
|
|
namespace PluralKit.Bot
|
|
|
|
{
|
|
|
|
public static class Utils {
|
|
|
|
public static string NameAndMention(this IUser user) {
|
|
|
|
return $"{user.Username}#{user.Discriminator} ({user.Mention})";
|
|
|
|
}
|
2019-05-16 23:23:09 +00:00
|
|
|
|
2019-06-15 10:19:44 +00:00
|
|
|
public static Color? ToDiscordColor(this string color)
|
|
|
|
{
|
|
|
|
if (uint.TryParse(color, NumberStyles.HexNumber, null, out var colorInt))
|
|
|
|
return new Color(colorInt);
|
|
|
|
throw new ArgumentException($"Invalid color string '{color}'.");
|
|
|
|
}
|
|
|
|
|
2019-05-16 23:23:09 +00:00
|
|
|
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);
|
|
|
|
}
|
2019-08-09 10:55:15 +00:00
|
|
|
|
2019-05-16 23:23:09 +00:00
|
|
|
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));
|
2019-08-09 10:55:15 +00:00
|
|
|
if (image.Width > Limits.AvatarDimensionLimit || image.Height > Limits.AvatarDimensionLimit) // Check image size
|
2019-05-16 23:23:09 +00:00
|
|
|
throw Errors.AvatarDimensionsTooLarge(image.Width, image.Height);
|
|
|
|
}
|
|
|
|
}
|
2019-08-09 10:55:15 +00:00
|
|
|
|
2019-06-27 08:38:45 +00:00
|
|
|
public static bool HasMentionPrefix(string content, ref int argPos)
|
|
|
|
{
|
|
|
|
// Roughly ported from Discord.Commands.MessageExtensions.HasMentionPrefix
|
|
|
|
if (string.IsNullOrEmpty(content) || content.Length <= 3 || (content[0] != '<' || content[1] != '@'))
|
|
|
|
return false;
|
|
|
|
int num = content.IndexOf('>');
|
|
|
|
if (num == -1 || content.Length < num + 2 || content[num + 1] != ' ' || !MentionUtils.TryParseUser(content.Substring(0, num + 1), out _))
|
|
|
|
return false;
|
|
|
|
argPos = num + 2;
|
|
|
|
return true;
|
|
|
|
}
|
2019-07-10 11:44:03 +00:00
|
|
|
|
|
|
|
public static string Sanitize(this string input) =>
|
|
|
|
Regex.Replace(Regex.Replace(input, "<@[!&]?(\\d{17,19})>", "<\\@$1>"), "@(everyone|here)", "@\u200B$1");
|
2019-08-09 10:55:15 +00:00
|
|
|
|
|
|
|
public static string SanitizeEveryone(this string input) =>
|
2019-07-28 13:38:28 +00:00
|
|
|
Regex.Replace(input, "@(everyone|here)", "@\u200B$1");
|
2019-07-14 03:23:27 +00:00
|
|
|
|
2019-08-09 10:55:15 +00:00
|
|
|
public static string EscapeMarkdown(this string input)
|
|
|
|
{
|
|
|
|
Regex pattern = new Regex(@"[*_~>`(||)\\]", RegexOptions.Multiline);
|
|
|
|
if (input != null) return pattern.Replace(input, @"\$&");
|
|
|
|
else return input;
|
|
|
|
}
|
|
|
|
|
2019-07-14 03:23:27 +00:00
|
|
|
public static async Task<ChannelPermissions> PermissionsIn(this IChannel channel)
|
|
|
|
{
|
|
|
|
switch (channel)
|
|
|
|
{
|
|
|
|
case IDMChannel _:
|
|
|
|
return ChannelPermissions.DM;
|
|
|
|
case IGroupChannel _:
|
|
|
|
return ChannelPermissions.Group;
|
|
|
|
case IGuildChannel gc:
|
|
|
|
var currentUser = await gc.Guild.GetCurrentUserAsync();
|
|
|
|
return currentUser.GetPermissions(gc);
|
|
|
|
default:
|
|
|
|
return ChannelPermissions.None;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public static async Task<bool> HasPermission(this IChannel channel, ChannelPermission permission) =>
|
|
|
|
(await PermissionsIn(channel)).Has(permission);
|
2019-04-21 13:33:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
class PKSystemTypeReader : TypeReader
|
|
|
|
{
|
|
|
|
public override async Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
|
|
|
|
{
|
|
|
|
var client = services.GetService<IDiscordClient>();
|
2019-05-21 21:40:26 +00:00
|
|
|
var systems = services.GetService<SystemStore>();
|
2019-04-21 13:33:22 +00:00
|
|
|
|
|
|
|
// System references can take three forms:
|
|
|
|
// - The direct user ID of an account connected to the system
|
|
|
|
// - A @mention of an account connected to the system (<@uid>)
|
|
|
|
// - A system hid
|
|
|
|
|
|
|
|
// First, try direct user ID parsing
|
2019-05-21 21:40:26 +00:00
|
|
|
if (ulong.TryParse(input, out var idFromNumber)) return await FindSystemByAccountHelper(idFromNumber, client, systems);
|
2019-04-21 13:33:22 +00:00
|
|
|
|
|
|
|
// Then, try mention parsing.
|
2019-05-21 21:40:26 +00:00
|
|
|
if (MentionUtils.TryParseUser(input, out var idFromMention)) return await FindSystemByAccountHelper(idFromMention, client, systems);
|
2019-04-21 13:33:22 +00:00
|
|
|
|
|
|
|
// Finally, try HID parsing
|
2019-05-21 21:40:26 +00:00
|
|
|
var res = await systems.GetByHid(input);
|
2019-04-21 13:33:22 +00:00
|
|
|
if (res != null) return TypeReaderResult.FromSuccess(res);
|
|
|
|
return TypeReaderResult.FromError(CommandError.ObjectNotFound, $"System with ID `{input}` not found.");
|
|
|
|
}
|
|
|
|
|
2019-05-21 21:40:26 +00:00
|
|
|
async Task<TypeReaderResult> FindSystemByAccountHelper(ulong id, IDiscordClient client, SystemStore systems)
|
2019-04-21 13:33:22 +00:00
|
|
|
{
|
2019-05-21 21:40:26 +00:00
|
|
|
var foundByAccountId = await systems.GetByAccount(id);
|
2019-04-21 13:33:22 +00:00
|
|
|
if (foundByAccountId != null) return TypeReaderResult.FromSuccess(foundByAccountId);
|
|
|
|
|
|
|
|
// We didn't find any, so we try to resolve the user ID to find the associated account,
|
|
|
|
// so we can print their username.
|
|
|
|
var user = await client.GetUserAsync(id);
|
|
|
|
|
|
|
|
// Return descriptive errors based on whether we found the user or not.
|
|
|
|
if (user == null) return TypeReaderResult.FromError(CommandError.ObjectNotFound, $"System or account with ID `{id}` not found.");
|
|
|
|
return TypeReaderResult.FromError(CommandError.ObjectNotFound, $"Account **{user.Username}#{user.Discriminator}** not found.");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class PKMemberTypeReader : TypeReader
|
|
|
|
{
|
|
|
|
public override async Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
|
|
|
|
{
|
2019-05-08 18:53:01 +00:00
|
|
|
var members = services.GetRequiredService<MemberStore>();
|
2019-04-21 13:33:22 +00:00
|
|
|
|
|
|
|
// If the sender of the command is in a system themselves,
|
|
|
|
// then try searching by the member's name
|
|
|
|
if (context is PKCommandContext ctx && ctx.SenderSystem != null)
|
|
|
|
{
|
2019-05-08 18:53:01 +00:00
|
|
|
var foundByName = await members.GetByName(ctx.SenderSystem, input);
|
2019-04-21 13:33:22 +00:00
|
|
|
if (foundByName != null) return TypeReaderResult.FromSuccess(foundByName);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise, if sender isn't in a system, or no member found by that name,
|
|
|
|
// do a standard by-hid search.
|
2019-05-08 18:53:01 +00:00
|
|
|
var foundByHid = await members.GetByHid(input);
|
2019-04-21 13:33:22 +00:00
|
|
|
if (foundByHid != null) return TypeReaderResult.FromSuccess(foundByHid);
|
2019-07-18 12:00:30 +00:00
|
|
|
return TypeReaderResult.FromError(CommandError.ObjectNotFound, $"Member with ID `{input}` not found.");
|
2019-04-21 13:33:22 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Subclass of ICommandContext with PK-specific additional fields and functionality
|
2019-07-15 15:17:57 +00:00
|
|
|
public class PKCommandContext : ShardedCommandContext
|
2019-04-21 13:33:22 +00:00
|
|
|
{
|
|
|
|
public PKSystem SenderSystem { get; }
|
2019-08-09 10:47:46 +00:00
|
|
|
public IServiceProvider ServiceProvider { get; }
|
|
|
|
|
2019-04-21 13:33:22 +00:00
|
|
|
private object _entity;
|
|
|
|
|
2019-08-09 10:47:46 +00:00
|
|
|
public PKCommandContext(DiscordShardedClient client, SocketUserMessage msg, PKSystem system, IServiceProvider serviceProvider) : base(client, msg)
|
2019-04-21 13:33:22 +00:00
|
|
|
{
|
|
|
|
SenderSystem = system;
|
2019-08-09 10:47:46 +00:00
|
|
|
ServiceProvider = serviceProvider;
|
2019-04-21 13:33:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public T GetContextEntity<T>() where T: class {
|
|
|
|
return _entity as T;
|
|
|
|
}
|
|
|
|
|
|
|
|
public void SetContextEntity(object entity) {
|
|
|
|
_entity = entity;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public abstract class ContextParameterModuleBase<T> : ModuleBase<PKCommandContext> where T: class
|
|
|
|
{
|
|
|
|
public IServiceProvider _services { get; set; }
|
|
|
|
public CommandService _commands { get; set; }
|
|
|
|
|
|
|
|
public abstract string Prefix { get; }
|
2019-04-27 14:30:34 +00:00
|
|
|
public abstract string ContextNoun { get; }
|
2019-04-21 13:33:22 +00:00
|
|
|
public abstract Task<T> ReadContextParameterAsync(string value);
|
|
|
|
|
|
|
|
public T ContextEntity => Context.GetContextEntity<T>();
|
|
|
|
|
|
|
|
protected override void OnModuleBuilding(CommandService commandService, ModuleBuilder builder) {
|
|
|
|
// We create a catch-all command that intercepts the first argument, tries to parse it as
|
|
|
|
// the context parameter, then runs the command service AGAIN with that given in a wrapped
|
|
|
|
// context, with the context argument removed so it delegates to the subcommand executor
|
|
|
|
builder.AddCommand("", async (ctx, param, services, info) => {
|
|
|
|
var pkCtx = ctx as PKCommandContext;
|
2019-04-29 17:43:09 +00:00
|
|
|
pkCtx.SetContextEntity(param[0] as T);
|
2019-04-21 13:33:22 +00:00
|
|
|
|
|
|
|
await commandService.ExecuteAsync(pkCtx, Prefix + " " + param[1] as string, services);
|
|
|
|
}, (cb) => {
|
|
|
|
cb.WithPriority(-9999);
|
2019-04-29 17:43:09 +00:00
|
|
|
cb.AddPrecondition(new MustNotHaveContextPrecondition());
|
|
|
|
cb.AddParameter<T>("contextValue", (pb) => pb.WithDefault(""));
|
2019-04-21 13:33:22 +00:00
|
|
|
cb.AddParameter<string>("rest", (pb) => pb.WithDefault("").WithIsRemainder(true));
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-29 17:43:09 +00:00
|
|
|
public class MustNotHaveContextPrecondition : PreconditionAttribute
|
2019-04-21 13:33:22 +00:00
|
|
|
{
|
2019-04-29 17:43:09 +00:00
|
|
|
public MustNotHaveContextPrecondition()
|
2019-04-21 13:33:22 +00:00
|
|
|
{
|
|
|
|
}
|
|
|
|
|
2019-07-21 14:43:28 +00:00
|
|
|
public override Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
|
2019-04-21 13:33:22 +00:00
|
|
|
{
|
2019-05-11 22:22:48 +00:00
|
|
|
// This stops the "delegating command" we define above from being called multiple times
|
|
|
|
// If we've already added a context object to the context, then we'll return with the same
|
|
|
|
// error you get when there's an invalid command - it's like it didn't exist
|
|
|
|
// This makes sure the user gets the proper error, instead of the command trying to parse things weirdly
|
2019-07-21 14:43:28 +00:00
|
|
|
if ((context as PKCommandContext)?.GetContextEntity<object>() == null) return Task.FromResult(PreconditionResult.FromSuccess());
|
|
|
|
return Task.FromResult(PreconditionResult.FromError(command.Module.Service.Search("<unknown>")));
|
2019-04-21 13:33:22 +00:00
|
|
|
}
|
|
|
|
}
|
2019-04-29 17:43:09 +00:00
|
|
|
|
|
|
|
public class PKError : Exception
|
2019-04-21 13:33:22 +00:00
|
|
|
{
|
2019-04-26 15:14:20 +00:00
|
|
|
public PKError(string message) : base(message)
|
2019-04-21 13:33:22 +00:00
|
|
|
{
|
|
|
|
}
|
|
|
|
}
|
2019-04-29 17:43:09 +00:00
|
|
|
|
|
|
|
public class PKSyntaxError : PKError
|
|
|
|
{
|
|
|
|
public PKSyntaxError(string message) : base(message)
|
|
|
|
{
|
|
|
|
}
|
|
|
|
}
|
2019-04-21 13:33:22 +00:00
|
|
|
}
|