From b17e912597c91fe6e651a04e942f00dc74a1bf1d Mon Sep 17 00:00:00 2001 From: Vankka Date: Sat, 22 Jun 2024 12:07:59 +0300 Subject: [PATCH] Ignore markdown characters inside links --- .../discord/util/DiscordFormattingUtil.java | 40 ++++++++++++++----- 1 file changed, 29 insertions(+), 11 deletions(-) diff --git a/api/src/main/java/com/discordsrv/api/discord/util/DiscordFormattingUtil.java b/api/src/main/java/com/discordsrv/api/discord/util/DiscordFormattingUtil.java index acb461de..16bb767b 100644 --- a/api/src/main/java/com/discordsrv/api/discord/util/DiscordFormattingUtil.java +++ b/api/src/main/java/com/discordsrv/api/discord/util/DiscordFormattingUtil.java @@ -23,10 +23,27 @@ package com.discordsrv.api.discord.util; +import java.util.Arrays; +import java.util.List; import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; public final class DiscordFormattingUtil { + // If first group is present the match will be ignored + private static final List FORMATTING_CHARACTERS = Arrays.asList('*', '_', '|', '`', '~', ':', '['); + private static final Pattern FORMATTING_PATTERN = Pattern.compile( + "(https?://.*\\.[^ ]*)?" + + "([" + + FORMATTING_CHARACTERS.stream() + .map(character -> Pattern.quote(String.valueOf(character))) + .collect(Collectors.joining()) + + "])" + ); + private static final Pattern QUOTE_PATTERN = Pattern.compile("(^|\n)>"); + private static final Pattern MENTION_PATTERN = Pattern.compile("(<[@#][0-9]{16,20}>)"); + private DiscordFormattingUtil() {} public static String escapeContent(String content) { @@ -37,23 +54,24 @@ public final class DiscordFormattingUtil { } public static String escapeFormatting(String content) { - return escapeChars(content, '*', '_', '|', '`', '~', ':', '['); - } - - private static String escapeChars(String input, char... characters) { - for (char character : characters) { - input = input.replace( - String.valueOf(character), - "\\" + character); + Matcher matcher = FORMATTING_PATTERN.matcher(content); + StringBuffer output = new StringBuffer(); + int lastEnd = 0; + while (matcher.find()) { + if (matcher.group(1) == null) { + matcher.appendReplacement(output, Matcher.quoteReplacement("\\" + matcher.group(2))); + lastEnd = matcher.end(); + } } - return input; + output.append(content.substring(lastEnd)); + return output.toString(); } public static String escapeQuotes(String input) { - return input.replaceAll("^>", Matcher.quoteReplacement("\\>")); + return QUOTE_PATTERN.matcher(input).replaceAll("$1" + Matcher.quoteReplacement("\\>")); } public static String escapeMentions(String input) { - return input.replaceAll("<([@#])", Matcher.quoteReplacement("\\<") + "$1"); + return MENTION_PATTERN.matcher(input).replaceAll(Matcher.quoteReplacement("\\") + "$1"); } }