From 203dbc65a19518e544597706122c12e74d8ae8c6 Mon Sep 17 00:00:00 2001 From: Ske Date: Tue, 25 Aug 2020 22:44:52 +0200 Subject: [PATCH] Replace most "code-escaped" literals with properly-escaping helpers --- PluralKit.Bot/Commands/Autoproxy.cs | 2 +- PluralKit.Bot/Commands/CommandTree.cs | 4 +-- PluralKit.Bot/Commands/MemberProxy.cs | 11 +++----- PluralKit.Bot/Commands/Misc.cs | 4 +-- .../Commands/Privacy/ContextPrivacyExt.cs | 8 +++--- PluralKit.Bot/Commands/SystemEdit.cs | 4 +-- PluralKit.Bot/Errors.cs | 14 +++++----- PluralKit.Bot/Handlers/ReactionAdded.cs | 2 +- PluralKit.Bot/Services/EmbedService.cs | 6 ++-- PluralKit.Bot/Utils/DiscordUtils.cs | 28 +++++++++++++++---- PluralKit.Bot/Utils/MiscUtils.cs | 3 +- 11 files changed, 50 insertions(+), 36 deletions(-) diff --git a/PluralKit.Bot/Commands/Autoproxy.cs b/PluralKit.Bot/Commands/Autoproxy.cs index af91da11..e78f226f 100644 --- a/PluralKit.Bot/Commands/Autoproxy.cs +++ b/PluralKit.Bot/Commands/Autoproxy.cs @@ -35,7 +35,7 @@ namespace PluralKit.Bot else if (!ctx.HasNext()) await ctx.Reply(embed: await CreateAutoproxyStatusEmbed(ctx)); else - throw new PKSyntaxError($"Invalid autoproxy mode `{ctx.PopArgument().EscapeMarkdown()}`."); + throw new PKSyntaxError($"Invalid autoproxy mode {ctx.PopArgument().AsCode()}."); } private async Task AutoproxyOff(Context ctx) diff --git a/PluralKit.Bot/Commands/CommandTree.cs b/PluralKit.Bot/Commands/CommandTree.cs index fce76f08..1ecd90a8 100644 --- a/PluralKit.Bot/Commands/CommandTree.cs +++ b/PluralKit.Bot/Commands/CommandTree.cs @@ -190,7 +190,7 @@ namespace PluralKit.Bot return ctx.Execute(MemberRandom, m => m.MemberRandom(ctx)); ctx.Reply( - $"{Emojis.Error} Unknown command `{ctx.PeekArgument()}`. For a list of possible commands, see ."); + $"{Emojis.Error} Unknown command {ctx.PeekArgument().AsCode()}. For a list of possible commands, see ."); return Task.CompletedTask; } @@ -442,7 +442,7 @@ namespace PluralKit.Bot return $"Account with ID `{id}` not found."; } - return $"System with ID `{input}` not found."; + return $"System with ID {input.AsCode()} not found."; } } } diff --git a/PluralKit.Bot/Commands/MemberProxy.cs b/PluralKit.Bot/Commands/MemberProxy.cs index b4802144..c80f3c3b 100644 --- a/PluralKit.Bot/Commands/MemberProxy.cs +++ b/PluralKit.Bot/Commands/MemberProxy.cs @@ -65,10 +65,7 @@ namespace PluralKit.Bot if (target.ProxyTags.Count == 0) await ctx.Reply("This member does not have any proxy tags."); else - { - var tags = string.Join("\n", target.ProxyTags.Select(t => $"``{t.ProxyString.EscapeBacktickPair()}``")); - await ctx.Reply($"This member's proxy tags are:\n{tags}"); - } + await ctx.Reply($"This member's proxy tags are:\n{target.ProxyTagsString("\n")}"); } // Subcommand: "add" else if (ctx.Match("add", "append")) @@ -88,7 +85,7 @@ namespace PluralKit.Bot var patch = new MemberPatch {ProxyTags = Partial.Present(newTags.ToArray())}; await _db.Execute(conn => conn.UpdateMember(target.Id, patch)); - await ctx.Reply($"{Emojis.Success} Added proxy tags ``{tagToAdd.ProxyString.EscapeBacktickPair()}``."); + await ctx.Reply($"{Emojis.Success} Added proxy tags {tagToAdd.ProxyString.AsCode()}."); } // Subcommand: "remove" else if (ctx.Match("remove", "delete")) @@ -105,7 +102,7 @@ namespace PluralKit.Bot var patch = new MemberPatch {ProxyTags = Partial.Present(newTags.ToArray())}; await _db.Execute(conn => conn.UpdateMember(target.Id, patch)); - await ctx.Reply($"{Emojis.Success} Removed proxy tags ``{tagToRemove.ProxyString.EscapeBacktickPair()}``."); + await ctx.Reply($"{Emojis.Success} Removed proxy tags {tagToRemove.ProxyString.AsCode()}."); } // Subcommand: bare proxy tag given else @@ -129,7 +126,7 @@ namespace PluralKit.Bot var patch = new MemberPatch {ProxyTags = Partial.Present(newTags)}; await _db.Execute(conn => conn.UpdateMember(target.Id, patch)); - await ctx.Reply($"{Emojis.Success} Member proxy tags set to ``{requestedTag.ProxyString.EscapeBacktickPair()}``."); + await ctx.Reply($"{Emojis.Success} Member proxy tags set to {requestedTag.ProxyString.AsCode()}."); } } } diff --git a/PluralKit.Bot/Commands/Misc.cs b/PluralKit.Bot/Commands/Misc.cs index 8b9c4bd8..b63cae5d 100644 --- a/PluralKit.Bot/Commands/Misc.cs +++ b/PluralKit.Bot/Commands/Misc.cs @@ -105,7 +105,7 @@ namespace PluralKit.Bot { { var guildIdStr = ctx.RemainderOrNull() ?? throw new PKSyntaxError("You must pass a server ID or run this command in a server."); if (!ulong.TryParse(guildIdStr, out var guildId)) - throw new PKSyntaxError($"Could not parse `{guildIdStr}` as an ID."); + throw new PKSyntaxError($"Could not parse {guildIdStr.AsCode()} as an ID."); guild = ctx.Client.GetGuild(guildId); if (guild != null) senderGuildUser = await guild.GetMember(ctx.Author.Id); @@ -196,7 +196,7 @@ namespace PluralKit.Bot { messageId = id; else if (Regex.Match(word, "https://discord(?:app)?.com/channels/\\d+/\\d+/(\\d+)") is Match match && match.Success) messageId = ulong.Parse(match.Groups[1].Value); - else throw new PKSyntaxError($"Could not parse `{word}` as a message ID or link."); + else throw new PKSyntaxError($"Could not parse {word.AsCode()} as a message ID or link."); var message = await _data.GetMessage(messageId); if (message == null) throw Errors.MessageNotFound(messageId); diff --git a/PluralKit.Bot/Commands/Privacy/ContextPrivacyExt.cs b/PluralKit.Bot/Commands/Privacy/ContextPrivacyExt.cs index 8a0ef845..04e88a1b 100644 --- a/PluralKit.Bot/Commands/Privacy/ContextPrivacyExt.cs +++ b/PluralKit.Bot/Commands/Privacy/ContextPrivacyExt.cs @@ -15,13 +15,13 @@ namespace PluralKit.Bot if (!ctx.HasNext()) throw new PKSyntaxError("You must pass a privacy level (`public` or `private`)"); - throw new PKSyntaxError($"Invalid privacy level `{ctx.PopArgument()}` (must be `public` or `private`)."); + throw new PKSyntaxError($"Invalid privacy level {ctx.PopArgument().AsCode()} (must be `public` or `private`)."); } public static SystemPrivacySubject PopSystemPrivacySubject(this Context ctx) { if (!SystemPrivacyUtils.TryParseSystemPrivacy(ctx.PeekArgument(), out var subject)) - throw new PKSyntaxError($"Invalid privacy subject `{ctx.PopArgument()}` (must be `description`, `members`, `front`, `fronthistory`, or `all`)."); + throw new PKSyntaxError($"Invalid privacy subject {ctx.PopArgument().AsCode()} (must be `description`, `members`, `front`, `fronthistory`, or `all`)."); ctx.PopArgument(); return subject; @@ -30,7 +30,7 @@ namespace PluralKit.Bot public static MemberPrivacySubject PopMemberPrivacySubject(this Context ctx) { if (!MemberPrivacyUtils.TryParseMemberPrivacy(ctx.PeekArgument(), out var subject)) - throw new PKSyntaxError($"Invalid privacy subject `{ctx.PopArgument()}` (must be `name`, `description`, `avatar`, `birthday`, `pronouns`, `metadata`, `visibility`, or `all)."); + throw new PKSyntaxError($"Invalid privacy subject {ctx.PopArgument().AsCode()} (must be `name`, `description`, `avatar`, `birthday`, `pronouns`, `metadata`, `visibility`, or `all)."); ctx.PopArgument(); return subject; @@ -39,7 +39,7 @@ namespace PluralKit.Bot public static GroupPrivacySubject PopGroupPrivacySubject(this Context ctx) { if (!GroupPrivacyUtils.TryParseGroupPrivacy(ctx.PeekArgument(), out var subject)) - throw new PKSyntaxError($"Invalid privacy subject `{ctx.PopArgument()}` (must be `description`, `icon`, `visibility`, or `all)."); + throw new PKSyntaxError($"Invalid privacy subject {ctx.PopArgument().AsCode()} (must be `description`, `icon`, `visibility`, or `all)."); ctx.PopArgument(); return subject; diff --git a/PluralKit.Bot/Commands/SystemEdit.cs b/PluralKit.Bot/Commands/SystemEdit.cs index 143fef45..cea4e113 100644 --- a/PluralKit.Bot/Commands/SystemEdit.cs +++ b/PluralKit.Bot/Commands/SystemEdit.cs @@ -114,7 +114,7 @@ namespace PluralKit.Bot if (ctx.System.Tag == null) await ctx.Reply($"You currently have no system tag. To set one, type `pk;s tag `."); else - await ctx.Reply($"Your current system tag is `{ctx.System.Tag}`. To change it, type `pk;s tag `. To clear it, type `pk;s tag -clear`."); + await ctx.Reply($"Your current system tag is {ctx.System.Tag.AsCode()}. To change it, type `pk;s tag `. To clear it, type `pk;s tag -clear`."); } else { @@ -126,7 +126,7 @@ namespace PluralKit.Bot var patch = new SystemPatch {Tag = newTag}; await _db.Execute(conn => conn.UpdateSystem(ctx.System.Id, patch)); - await ctx.Reply($"{Emojis.Success} System tag changed. Member names will now end with `{newTag}` when proxied."); + await ctx.Reply($"{Emojis.Success} System tag changed. Member names will now end with {newTag.AsCode()} when proxied."); } } diff --git a/PluralKit.Bot/Errors.cs b/PluralKit.Bot/Errors.cs index 9058948a..a136ece0 100644 --- a/PluralKit.Bot/Errors.cs +++ b/PluralKit.Bot/Errors.cs @@ -96,20 +96,20 @@ namespace PluralKit.Bot { public static PKError ImportCancelled => new PKError("Import cancelled."); public static PKError MessageNotFound(ulong id) => new PKError($"Message with ID '{id}' not found. Are you sure it's a message proxied by PluralKit?"); - public static PKError DurationParseError(string durationStr) => new PKError($"Could not parse '{durationStr}' as a valid duration. Try a format such as `30d`, `1d3h` or `20m30s`."); + public static PKError DurationParseError(string durationStr) => new PKError($"Could not parse {durationStr.AsCode()} as a valid duration. Try a format such as `30d`, `1d3h` or `20m30s`."); public static PKError FrontPercentTimeInFuture => new PKError("Cannot get the front percent between now and a time in the future."); public static PKError GuildNotFound(ulong guildId) => new PKError($"Guild with ID {guildId} not found. Note that you must be a member of the guild you are querying."); public static PKError DisplayNameTooLong(string displayName, int maxLength) => new PKError( $"Display name too long ({displayName.Length} > {maxLength} characters). Use a shorter display name, or shorten your system tag."); - public static PKError ProxyNameTooShort(string name) => new PKError($"The webhook's name, `{name}`, is shorter than two characters, and thus cannot be proxied. Please change the member name or use a longer system tag."); - public static PKError ProxyNameTooLong(string name) => new PKError($"The webhook's name, {name}, is too long ({name.Length} > {Limits.MaxProxyNameLength} characters), and thus cannot be proxied. Please change the member name, display name or server display name, or use a shorter system tag."); + public static PKError ProxyNameTooShort(string name) => new PKError($"The webhook's name, {name.AsCode()}, is shorter than two characters, and thus cannot be proxied. Please change the member name or use a longer system tag."); + public static PKError ProxyNameTooLong(string name) => new PKError($"The webhook's name, {name.AsCode()}, is too long ({name.Length} > {Limits.MaxProxyNameLength} characters), and thus cannot be proxied. Please change the member name, display name or server display name, or use a shorter system tag."); - public static PKError ProxyTagAlreadyExists(ProxyTag tagToAdd, PKMember member) => new PKError($"That member already has the proxy tag `` {tagToAdd.ProxyString.EscapeBacktickPair()} ``. The member currently has these tags: {member.ProxyTagsString()}"); - public static PKError ProxyTagDoesNotExist(ProxyTag tagToRemove, PKMember member) => new PKError($"That member does not have the proxy tag ``{tagToRemove.ProxyString.EscapeBacktickPair()}``. The member currently has these tags: {member.ProxyTagsString()}"); - public static PKError LegacyAlreadyHasProxyTag(ProxyTag requested, PKMember member) => new PKError($"This member already has more than one proxy tag set: {member.ProxyTagsString()}\nConsider using the ``pk;member {member.Hid} proxy add {requested.ProxyString.EscapeBacktickPair()}`` command instead."); - public static PKError EmptyProxyTags(PKMember member) => new PKError($"The example proxy `text` is equivalent to having no proxy tags at all, since there are no symbols or brackets on either end. If you'd like to clear your proxy tags, use `pk;member {member.Hid} proxy clear`."); + public static PKError ProxyTagAlreadyExists(ProxyTag tagToAdd, PKMember member) => new PKError($"That member already has the proxy tag {tagToAdd.ProxyString.AsCode()}. The member currently has these tags: {member.ProxyTagsString()}"); + public static PKError ProxyTagDoesNotExist(ProxyTag tagToRemove, PKMember member) => new PKError($"That member does not have the proxy tag {tagToRemove.ProxyString.AsCode()}. The member currently has these tags: {member.ProxyTagsString()}"); + public static PKError LegacyAlreadyHasProxyTag(ProxyTag requested, PKMember member) => new PKError($"This member already has more than one proxy tag set: {member.ProxyTagsString()}\nConsider using the {$"pk;member {member.Reference()} proxy add {requested.ProxyString}".AsCode()} command instead."); + public static PKError EmptyProxyTags(PKMember member) => new PKError($"The example proxy `text` is equivalent to having no proxy tags at all, since there are no symbols or brackets on either end. If you'd like to clear your proxy tags, use `pk;member {member.Reference()} proxy clear`."); public static PKError GenericCancelled() => new PKError("Operation cancelled."); diff --git a/PluralKit.Bot/Handlers/ReactionAdded.cs b/PluralKit.Bot/Handlers/ReactionAdded.cs index 9c8100fa..ce98d0e8 100644 --- a/PluralKit.Bot/Handlers/ReactionAdded.cs +++ b/PluralKit.Bot/Handlers/ReactionAdded.cs @@ -124,7 +124,7 @@ namespace PluralKit.Bot try { await guildUser.SendMessageFixedAsync($"{Emojis.Error} {msg.Member.DisplayName()}'s system has disabled reaction pings. If you want to mention them anyway, you can copy/paste the following message:"); - await guildUser.SendMessageFixedAsync($"`<@{msg.Message.Sender}>`"); + await guildUser.SendMessageFixedAsync($"<@{msg.Message.Sender}>".AsCode()); } catch (UnauthorizedException) { } } diff --git a/PluralKit.Bot/Services/EmbedService.cs b/PluralKit.Bot/Services/EmbedService.cs index 5985a3e5..e27e892c 100644 --- a/PluralKit.Bot/Services/EmbedService.cs +++ b/PluralKit.Bot/Services/EmbedService.cs @@ -110,9 +110,7 @@ namespace PluralKit.Bot { var avatar = guildSettings?.AvatarUrl ?? member.AvatarFor(ctx); var groups = (await conn.QueryMemberGroups(member.Id)).Where(g => g.Visibility.CanAccess(ctx)).ToList(); - - var proxyTagsStr = string.Join('\n', member.ProxyTags.Select(t => $"`` {t.ProxyString} ``")); - + var eb = new DiscordEmbedBuilder() // TODO: add URL of website when that's up .WithAuthor(name, iconUrl: DiscordUtils.WorkaroundForUrlBug(avatar)) @@ -136,7 +134,7 @@ namespace PluralKit.Bot { if (member.BirthdayFor(ctx) != null) eb.AddField("Birthdate", member.BirthdayString, true); if (member.PronounsFor(ctx) is {} pronouns && !string.IsNullOrWhiteSpace(pronouns)) eb.AddField("Pronouns", pronouns.Truncate(1024), true); if (member.MessageCountFor(ctx) is {} count && count > 0) eb.AddField("Message Count", member.MessageCount.ToString(), true); - if (member.HasProxyTags) eb.AddField("Proxy Tags", string.Join('\n', proxyTagsStr).Truncate(1024), true); + if (member.HasProxyTags) eb.AddField("Proxy Tags", member.ProxyTagsString("\n").Truncate(1024), true); // --- For when this gets added to the member object itself or however they get added // if (member.LastMessage != null && member.MetadataPrivacy.CanAccess(ctx)) eb.AddField("Last message:" FormatTimestamp(DiscordUtils.SnowflakeToInstant(m.LastMessage.Value))); // if (member.LastSwitchTime != null && m.MetadataPrivacy.CanAccess(ctx)) eb.AddField("Last switched in:", FormatTimestamp(member.LastSwitchTime.Value)); diff --git a/PluralKit.Bot/Utils/DiscordUtils.cs b/PluralKit.Bot/Utils/DiscordUtils.cs index 28067d4b..57422636 100644 --- a/PluralKit.Bot/Utils/DiscordUtils.cs +++ b/PluralKit.Bot/Utils/DiscordUtils.cs @@ -209,11 +209,29 @@ namespace PluralKit.Bot else return input; } - public static string EscapeBacktickPair(this string input){ - Regex doubleBacktick = new Regex(@"``", RegexOptions.Multiline); - //Run twice to catch any pairs that are created from the first pass, pairs shouldn't be created in the second as they are created from odd numbers of backticks, even numbers are all caught on the first pass - if(input != null) return doubleBacktick.Replace(doubleBacktick.Replace(input, "`‌\ufeff`"),"`‌\ufeff`"); - else return input; + public static string EscapeBacktickPair(this string input) + { + if (input == null) + return null; + + // Break all pairs of backticks by placing a ZWNBSP (U+FEFF) between them. + // Run twice to catch any pairs that are created from the first pass + var escaped = input + .Replace("``", "`\ufeff`") + .Replace("``", "`\ufeff`"); + + // Escape the start/end of the string if necessary to better "connect" with other things + if (escaped.StartsWith("`")) escaped = "\ufeff" + escaped; + if (escaped.EndsWith("`")) escaped = escaped + "\ufeff"; + + return escaped; + } + + public static string AsCode(this string input) + { + // Inline code blocks started with two backticks need to end with two backticks + // So, surrounding with two backticks, then escaping all backtick pairs makes it impossible(!) to "break out" + return $"``{EscapeBacktickPair(input)}``"; } public static Task GetUser(this DiscordRestClient client, ulong id) => diff --git a/PluralKit.Bot/Utils/MiscUtils.cs b/PluralKit.Bot/Utils/MiscUtils.cs index 5d881729..96e7d7cb 100644 --- a/PluralKit.Bot/Utils/MiscUtils.cs +++ b/PluralKit.Bot/Utils/MiscUtils.cs @@ -14,7 +14,8 @@ using PluralKit.Core; namespace PluralKit.Bot { public static class MiscUtils { - public static string ProxyTagsString(this PKMember member) => string.Join(", ", member.ProxyTags.Select(t => $"``{t.ProxyString.EscapeBacktickPair()}``")); + public static string ProxyTagsString(this PKMember member, string separator = ", ") => + string.Join(separator, member.ProxyTags.Select(t => t.ProxyString.AsCode())); public static bool IsOurProblem(this Exception e) {