PluralKit/PluralKit.Bot/CommandSystem/Context/ContextAvatarExt.cs

70 lines
2.3 KiB
C#
Raw Normal View History

2020-09-03 06:46:23 -04:00
#nullable enable
2020-12-24 14:52:44 +01:00
using Myriad.Extensions;
using Myriad.Types;
2020-07-07 23:41:51 +02:00
namespace PluralKit.Bot;
public static class ContextAvatarExt
2020-07-07 23:41:51 +02:00
{
public static async Task<ParsedImage?> MatchImage(this Context ctx)
2020-07-07 23:41:51 +02:00
{
// If we have a user @mention/ID, use their avatar
if (await ctx.MatchUser() is { } user)
2020-07-07 23:41:51 +02:00
{
var url = user.AvatarUrl("png", 256);
return new ParsedImage { Url = url, Source = AvatarSource.User, SourceUser = user };
}
2021-08-27 11:03:47 -04:00
// If we have raw or plaintext, don't try to parse as a URL
if (ctx.PeekMatchFormat() != ReplyFormat.Standard)
return null;
// If we have a positional argument, try to parse it as a URL
var arg = ctx.RemainderOrNull();
if (arg != null)
{
// Allow surrounding the URL with <angle brackets> to "de-embed"
if (arg.StartsWith("<") && arg.EndsWith(">"))
arg = arg.Substring(1, arg.Length - 2);
2020-07-07 23:41:51 +02:00
2022-12-06 10:15:20 +00:00
if (!Core.MiscUtils.TryMatchUri(arg, out var uri))
throw Errors.InvalidUrl;
2021-08-27 11:03:47 -04:00
// ToString URL-decodes, which breaks URLs to spaces; AbsoluteUri doesn't
return new ParsedImage { Url = uri.AbsoluteUri, Source = AvatarSource.Url };
}
2021-08-27 11:03:47 -04:00
// If we have an attachment, use that
if (ctx.Message.Attachments.FirstOrDefault() is { } attachment)
{
// XXX: discord attachment URLs are unable to be validated without their query params
// keep both the URL with query (for validation) and the clean URL (for storage) around
var uriBuilder = new UriBuilder(attachment.ProxyUrl);
ParsedImage img = new ParsedImage { Url = uriBuilder.Uri.AbsoluteUri, Source = AvatarSource.Attachment };
uriBuilder.Query = "";
img.CleanUrl = uriBuilder.Uri.AbsoluteUri;
return img;
2020-07-07 23:41:51 +02:00
}
// We should only get here if there are no arguments (which would get parsed as URL + throw if error)
// and if there are no attachments (which would have been caught just before)
return null;
2020-07-07 23:41:51 +02:00
}
}
2020-07-07 23:41:51 +02:00
public struct ParsedImage
{
public string Url;
public string? CleanUrl;
public AvatarSource Source;
public User? SourceUser;
}
public enum AvatarSource
{
Url,
User,
2024-02-14 04:41:02 +13:00
Attachment,
HostedCdn
2021-08-27 11:03:47 -04:00
}