PluralKit/PluralKit.Bot/Commands/Avatars/ContextAvatarExt.cs

66 lines
2.1 KiB
C#
Raw Normal View History

2020-09-03 10:46:23 +00:00
#nullable enable
2020-07-07 21:41:51 +00:00
using System;
using System.Linq;
using System.Threading.Tasks;
2020-12-24 13:52:44 +00:00
using Myriad.Extensions;
using Myriad.Types;
2020-07-07 21:41:51 +00:00
namespace PluralKit.Bot
{
public static class ContextAvatarExt
{
public static async Task<ParsedImage?> MatchImage(this Context ctx)
{
// If we have a user @mention/ID, use their avatar
if (await ctx.MatchUser() is { } user)
{
2020-12-24 13:52:44 +00:00
var url = user.AvatarUrl("png", 256);
2021-08-27 15:03:47 +00:00
return new ParsedImage { Url = url, Source = AvatarSource.User, SourceUser = user };
2020-07-07 21:41:51 +00:00
}
2021-08-27 15:03:47 +00:00
2020-07-07 21:41:51 +00:00
// If we have a positional argument, try to parse it as a URL
var arg = ctx.RemainderOrNull();
if (arg != null)
{
2020-07-07 21:52:54 +00:00
// Allow surrounding the URL with <angle brackets> to "de-embed"
if (arg.StartsWith("<") && arg.EndsWith(">"))
arg = arg.Substring(1, arg.Length - 2);
2021-08-27 15:03:47 +00:00
2020-07-07 21:41:51 +00:00
if (!Uri.TryCreate(arg, UriKind.Absolute, out var uri))
throw Errors.InvalidUrl(arg);
if (uri.Scheme != "http" && uri.Scheme != "https")
throw Errors.InvalidUrl(arg);
2021-08-27 15:03:47 +00:00
2020-09-12 17:43:54 +00:00
// ToString URL-decodes, which breaks URLs to spaces; AbsoluteUri doesn't
2021-08-27 15:03:47 +00:00
return new ParsedImage { Url = uri.AbsoluteUri, Source = AvatarSource.Url };
2020-07-07 21:41:51 +00:00
}
2021-08-27 15:03:47 +00:00
2020-07-07 21:41:51 +00:00
// If we have an attachment, use that
2021-08-27 15:03:47 +00:00
if (ctx.Message.Attachments.FirstOrDefault() is { } attachment)
2020-07-07 21:41:51 +00:00
{
var url = attachment.ProxyUrl;
2021-08-27 15:03:47 +00:00
return new ParsedImage { Url = url, Source = AvatarSource.Attachment };
2020-07-07 21:41:51 +00:00
}
2021-08-27 15:03:47 +00:00
2020-07-07 21:41:51 +00: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;
}
}
public struct ParsedImage
{
public string Url;
public AvatarSource Source;
2020-12-24 13:52:44 +00:00
public User? SourceUser;
2020-07-07 21:41:51 +00:00
}
public enum AvatarSource
{
Url,
User,
Attachment
}
2021-08-27 15:03:47 +00:00
}