diff --git a/application/build.gradle b/application/build.gradle
index 75ede0d319..23075c96f7 100644
--- a/application/build.gradle
+++ b/application/build.gradle
@@ -44,6 +44,7 @@ dependencies {
implementation project(':database')
implementation project(':utils')
+ implementation project(':formatter')
implementation 'net.dv8tion:JDA:5.0.0-alpha.20'
@@ -52,7 +53,7 @@ dependencies {
implementation 'club.minnced:discord-webhooks:0.8.2'
- implementation 'org.jooq:jooq:3.17.2'
+ implementation "org.jooq:jooq:$jooqVersion"
implementation 'io.mikael:urlbuilder:2.0.9'
@@ -60,10 +61,10 @@ dependencies {
implementation 'org.scilab.forge:jlatexmath-font-greek:1.0.7'
implementation 'org.scilab.forge:jlatexmath-font-cyrillic:1.0.7'
- implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-csv:2.13.0'
- implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.13.0'
- implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.13.0'
- implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.0'
+ implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-csv:2.14.0'
+ implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.14.0'
+ implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.14.0'
+ implementation 'com.fasterxml.jackson.core:jackson-databind:2.14.0'
implementation 'com.github.freva:ascii-table:1.8.0'
diff --git a/application/config.json.template b/application/config.json.template
index d7a3563a38..780e844ed1 100644
--- a/application/config.json.template
+++ b/application/config.json.template
@@ -5,10 +5,11 @@
"projectWebsite": "https://github.com/Together-Java/TJ-Bot",
"discordGuildInvite": "https://discord.com/invite/XXFUXzK",
"modAuditLogChannelPattern": "mod_audit_log",
+ "modMailChannelPattern": "modmail",
"mutedRolePattern": "Muted",
"heavyModerationRolePattern": "Moderator",
- "softModerationRolePattern": "Moderator|Staff Assistant",
- "tagManageRolePattern": "Moderator|Staff Assistant|Top Helpers .+",
+ "softModerationRolePattern": "Moderator|Community Ambassador",
+ "tagManageRolePattern": "Moderator|Community Ambassador|Top Helpers .+",
"suggestions": {
"channelPattern": "tj_suggestions",
"upVoteEmoteName": "peepo_yes",
@@ -18,6 +19,7 @@
"scamBlocker": {
"mode": "AUTO_DELETE_BUT_APPROVE_QUARANTINE",
"reportChannelPattern": "commands",
+ "suspiciousKeywords": ["nitro", "boob", "sexy", "sexi", "esex"],
"hostWhitelist": ["discord.com", "discord.gg", "discord.media", "discordapp.com", "discordapp.net", "discordstatus.com"],
"hostBlacklist": ["bit.ly"],
"suspiciousHostKeywords": ["discord", "nitro", "premium"],
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/BotCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/BotCommand.java
index 0bd53a32b7..769659d0ad 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/BotCommand.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/BotCommand.java
@@ -19,7 +19,7 @@
*
* After registration, the system will notify a command whenever one of its corresponding command
* method, buttons ({@link #onButtonClick(ButtonInteractionEvent, List)}) or menus
- * ({@link #onSelectionMenu(SelectMenuInteractionEvent, List)}) have been triggered.
+ * ({@link #onSelectMenuSelection(SelectMenuInteractionEvent, List)}) have been triggered.
*
* Some example commands are available in {@link org.togetherjava.tjbot.commands.basic}.
*/
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/BotCommandAdapter.java b/application/src/main/java/org/togetherjava/tjbot/commands/BotCommandAdapter.java
index c9c4a52dbb..f7e4d5a4d6 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/BotCommandAdapter.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/BotCommandAdapter.java
@@ -1,5 +1,6 @@
package org.togetherjava.tjbot.commands;
+import net.dv8tion.jda.api.events.interaction.ModalInteractionEvent;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent;
import net.dv8tion.jda.api.events.interaction.component.SelectMenuInteractionEvent;
@@ -20,8 +21,8 @@
* {@link Features}.
*
* Further, {@link #onButtonClick(ButtonInteractionEvent, List)} and
- * {@link #onSelectionMenu(SelectMenuInteractionEvent, List)} can be overridden if desired. The
- * default implementation is empty, the adapter will not react to such events.
+ * {@link #onSelectMenuSelection(SelectMenuInteractionEvent, List)} can be overridden if desired.
+ * The default implementation is empty, the adapter will not react to such events.
*
* The adapter manages some getters for you, you've to create the {@link CommandData} yourself. See
* {@link #BotCommandAdapter(CommandData, CommandVisibility)}} for more info on that. Minimal
@@ -100,7 +101,13 @@ public void onButtonClick(ButtonInteractionEvent event, List args) {
@SuppressWarnings("NoopMethodInAbstractClass")
@Override
- public void onSelectionMenu(SelectMenuInteractionEvent event, List args) {
+ public void onSelectMenuSelection(SelectMenuInteractionEvent event, List args) {
+ // Adapter does not react by default, subclasses may change this behavior
+ }
+
+ @SuppressWarnings("NoopMethodInAbstractClass")
+ @Override
+ public void onModalSubmitted(ModalInteractionEvent event, List args) {
// Adapter does not react by default, subclasses may change this behavior
}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java
index 581296a77d..853b5be019 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java
@@ -6,6 +6,7 @@
import org.togetherjava.tjbot.commands.basic.RoleSelectCommand;
import org.togetherjava.tjbot.commands.basic.SuggestionsUpDownVoter;
import org.togetherjava.tjbot.commands.basic.VcActivityCommand;
+import org.togetherjava.tjbot.commands.code.CodeMessageHandler;
import org.togetherjava.tjbot.commands.filesharing.FileSharingMessageListener;
import org.togetherjava.tjbot.commands.help.*;
import org.togetherjava.tjbot.commands.mathcommands.TeXCommand;
@@ -13,12 +14,13 @@
import org.togetherjava.tjbot.commands.mediaonly.MediaOnlyChannelListener;
import org.togetherjava.tjbot.commands.moderation.*;
import org.togetherjava.tjbot.commands.moderation.attachment.BlacklistedAttachmentListener;
+import org.togetherjava.tjbot.commands.moderation.modmail.ModMailCommand;
import org.togetherjava.tjbot.commands.moderation.scam.ScamBlocker;
import org.togetherjava.tjbot.commands.moderation.scam.ScamHistoryPurgeRoutine;
import org.togetherjava.tjbot.commands.moderation.scam.ScamHistoryStore;
import org.togetherjava.tjbot.commands.moderation.temp.TemporaryModerationRoutine;
-import org.togetherjava.tjbot.commands.reminder.RemindCommand;
import org.togetherjava.tjbot.commands.reminder.RemindRoutine;
+import org.togetherjava.tjbot.commands.reminder.ReminderCommand;
import org.togetherjava.tjbot.commands.system.BotCore;
import org.togetherjava.tjbot.commands.system.LogLevelCommand;
import org.togetherjava.tjbot.commands.tags.TagCommand;
@@ -93,10 +95,12 @@ public static Collection createFeatures(JDA jda, Database database, Con
features.add(new MediaOnlyChannelListener(config));
features.add(new FileSharingMessageListener(config));
features.add(new BlacklistedAttachmentListener(config, modAuditLogWriter));
+ features.add(new CodeMessageHandler());
// Event receivers
features.add(new RejoinModerationRoleListener(actionsStore, config));
features.add(new OnGuildLeaveCloseThreadListener(database));
+ features.add(new UserBannedDeleteRecentThreadsListener(database));
// Message context commands
@@ -120,12 +124,13 @@ public static Collection createFeatures(JDA jda, Database database, Con
features.add(new TopHelpersCommand(database));
features.add(new RoleSelectCommand());
features.add(new NoteCommand(actionsStore));
- features.add(new RemindCommand(database));
+ features.add(new ReminderCommand(database));
features.add(new QuarantineCommand(actionsStore, config));
features.add(new UnquarantineCommand(actionsStore, config));
features.add(new WhoIsCommand());
features.add(new WolframAlphaCommand(config));
- features.add(new AskCommand(config, helpSystemHelper));
+ features.add(new AskCommand(config, helpSystemHelper, database));
+ features.add(new ModMailCommand(jda, config));
features.add(new HelpThreadCommand(config, helpSystemHelper));
// Mixtures
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/MessageContextCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/MessageContextCommand.java
index 3983535f1d..0d0e767340 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/MessageContextCommand.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/MessageContextCommand.java
@@ -29,7 +29,7 @@
* After registration, the system will notify a command whenever one of its corresponding message
* context-commands ({@link #onMessageContext(MessageContextInteractionEvent)}), buttons
* ({@link #onButtonClick(ButtonInteractionEvent, List)}) or menus
- * ({@link #onSelectionMenu(SelectMenuInteractionEvent, List)}) have been triggered.
+ * ({@link #onSelectMenuSelection(SelectMenuInteractionEvent, List)}) have been triggered.
*
* Some example commands are available in {@link org.togetherjava.tjbot.commands.basic}.
*/
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/MessageReceiver.java b/application/src/main/java/org/togetherjava/tjbot/commands/MessageReceiver.java
index b0aaf80d59..35843ead1c 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/MessageReceiver.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/MessageReceiver.java
@@ -1,5 +1,6 @@
package org.togetherjava.tjbot.commands;
+import net.dv8tion.jda.api.events.message.MessageDeleteEvent;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.events.message.MessageUpdateEvent;
@@ -46,4 +47,13 @@ public interface MessageReceiver extends Feature {
* message that was edited
*/
void onMessageUpdated(MessageUpdateEvent event);
+
+ /**
+ * Triggered by the core system whenever an existing message was deleted in a text channel of a
+ * guild the bot has been added to.
+ *
+ * @param event the event that triggered this, containing information about the corresponding
+ * message that was deleted
+ */
+ void onMessageDeleted(MessageDeleteEvent event);
}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/MessageReceiverAdapter.java b/application/src/main/java/org/togetherjava/tjbot/commands/MessageReceiverAdapter.java
index 63a6bf841a..6a8f1a5fa3 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/MessageReceiverAdapter.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/MessageReceiverAdapter.java
@@ -1,5 +1,6 @@
package org.togetherjava.tjbot.commands;
+import net.dv8tion.jda.api.events.message.MessageDeleteEvent;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.events.message.MessageUpdateEvent;
@@ -43,4 +44,10 @@ public void onMessageReceived(MessageReceivedEvent event) {
public void onMessageUpdated(MessageUpdateEvent event) {
// Adapter does not react by default, subclasses may change this behavior
}
+
+ @SuppressWarnings("NoopMethodInAbstractClass")
+ @Override
+ public void onMessageDeleted(MessageDeleteEvent event) {
+ // Adapter does not react by default, subclasses may change this behavior
+ }
}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommand.java
index af7c17fa28..0e89ee50c1 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommand.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommand.java
@@ -35,7 +35,7 @@
* After registration, the system will notify a command whenever one of its corresponding slash
* commands ({@link #onSlashCommand(SlashCommandInteractionEvent)}), buttons
* ({@link #onButtonClick(ButtonInteractionEvent, List)}) or menus
- * ({@link #onSelectionMenu(SelectMenuInteractionEvent, List)}) have been triggered.
+ * ({@link #onSelectMenuSelection(SelectMenuInteractionEvent, List)}) have been triggered.
*
* Some example commands are available in {@link org.togetherjava.tjbot.commands.basic}.
*/
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommandAdapter.java b/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommandAdapter.java
index 9923a15ea4..48a4caf4c6 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommandAdapter.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommandAdapter.java
@@ -23,8 +23,8 @@
* adding it to {@link Features}.
*
* Further, {@link #onButtonClick(ButtonInteractionEvent, List)} and
- * {@link #onSelectionMenu(SelectMenuInteractionEvent, List)} can be overridden if desired. The
- * default implementation is empty, the adapter will not react to such events.
+ * {@link #onSelectMenuSelection(SelectMenuInteractionEvent, List)} can be overridden if desired.
+ * The default implementation is empty, the adapter will not react to such events.
*
* The adapter manages all command related data itself, which can be provided during construction
* (see {@link #SlashCommandAdapter(String, String, CommandVisibility)}). In order to add options,
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/UserContextCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/UserContextCommand.java
index 4d25446f15..36a7aeb5cc 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/UserContextCommand.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/UserContextCommand.java
@@ -30,7 +30,7 @@
* After registration, the system will notify a command whenever one of its corresponding user
* context-commands ({@link #onUserContext(UserContextInteractionEvent)}), buttons
* ({@link #onButtonClick(ButtonInteractionEvent, List)}) or menus
- * ({@link #onSelectionMenu(SelectMenuInteractionEvent, List)}) have been triggered.
+ * ({@link #onSelectMenuSelection(SelectMenuInteractionEvent, List)}) have been triggered.
*
* Some example commands are available in {@link org.togetherjava.tjbot.commands.basic}.
*/
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/UserInteractor.java b/application/src/main/java/org/togetherjava/tjbot/commands/UserInteractor.java
index 714a944afd..7bae9e1036 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/UserInteractor.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/UserInteractor.java
@@ -1,5 +1,6 @@
package org.togetherjava.tjbot.commands;
+import net.dv8tion.jda.api.events.interaction.ModalInteractionEvent;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent;
import net.dv8tion.jda.api.events.interaction.component.SelectMenuInteractionEvent;
@@ -75,7 +76,26 @@ public interface UserInteractor extends Feature {
* {@link SlashCommand#onSlashCommand(SlashCommandInteractionEvent)} for details on how
* these are created
*/
- void onSelectionMenu(SelectMenuInteractionEvent event, List args);
+ void onSelectMenuSelection(SelectMenuInteractionEvent event, List args);
+
+
+ /**
+ * Triggered by the core system when a modal corresponding to this implementation (based on
+ * {@link #getName()}) has been clicked.
+ *
+ * This method may be called multithreaded. In particular, there are no guarantees that it will
+ * be executed on the same thread repeatedly or on the same thread that other event methods have
+ * been called on.
+ *
+ * Details are available in the given event and the event also enables implementations to
+ * respond to it.
+ *
+ * @param event the event that triggered this
+ * @param args the arguments transported with the modal, see
+ * {@link SlashCommand#onSlashCommand(SlashCommandInteractionEvent)} for details on how
+ * these are created
+ */
+ void onModalSubmitted(ModalInteractionEvent event, List args);
/**
* Triggered by the core system during its setup phase. It will provide the command a component
@@ -90,7 +110,7 @@ public interface UserInteractor extends Feature {
* given to this method during system setup. The required {@link ComponentId} instance accepts
* optional extra arguments, which, if provided, can be picked up during the corresponding event
* (see {@link #onButtonClick(ButtonInteractionEvent, List)},
- * {@link #onSelectionMenu(SelectMenuInteractionEvent, List)}).
+ * {@link #onSelectMenuSelection(SelectMenuInteractionEvent, List)}).
*
* Alternatively, if {@link BotCommandAdapter} has been extended, it also offers a handy
* {@link BotCommandAdapter#generateComponentId(String...)} method to ease the flow.
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/basic/RoleSelectCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/basic/RoleSelectCommand.java
index d8e6970132..a96ddef619 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/basic/RoleSelectCommand.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/basic/RoleSelectCommand.java
@@ -204,7 +204,7 @@ private static SelectOption mapToSelectOption(Role role) {
}
@Override
- public void onSelectionMenu(SelectMenuInteractionEvent event, List args) {
+ public void onSelectMenuSelection(SelectMenuInteractionEvent event, List args) {
Guild guild = event.getGuild();
List selectedRoles = event.getSelectedOptions()
.stream()
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/code/CodeAction.java b/application/src/main/java/org/togetherjava/tjbot/commands/code/CodeAction.java
new file mode 100644
index 0000000000..8cec47141b
--- /dev/null
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/code/CodeAction.java
@@ -0,0 +1,25 @@
+package org.togetherjava.tjbot.commands.code;
+
+import net.dv8tion.jda.api.entities.MessageEmbed;
+
+import org.togetherjava.tjbot.commands.utils.CodeFence;
+
+/**
+ * Actions that can be executed on code, such as running it.
+ */
+interface CodeAction {
+ /**
+ * The name of the action, displayed to the user for applying it.
+ *
+ * @return the label of the action
+ */
+ String getLabel();
+
+ /**
+ * Applies the action to the given code and returns a message.
+ *
+ * @param codeFence the code to apply the action to
+ * @return the message to send to the user
+ */
+ MessageEmbed apply(CodeFence codeFence);
+}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/code/CodeMessageHandler.java b/application/src/main/java/org/togetherjava/tjbot/commands/code/CodeMessageHandler.java
new file mode 100644
index 0000000000..9b087bf39a
--- /dev/null
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/code/CodeMessageHandler.java
@@ -0,0 +1,253 @@
+package org.togetherjava.tjbot.commands.code;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import net.dv8tion.jda.api.entities.Message;
+import net.dv8tion.jda.api.events.interaction.ModalInteractionEvent;
+import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent;
+import net.dv8tion.jda.api.events.interaction.component.SelectMenuInteractionEvent;
+import net.dv8tion.jda.api.events.message.MessageDeleteEvent;
+import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
+import net.dv8tion.jda.api.events.message.MessageUpdateEvent;
+import net.dv8tion.jda.api.interactions.components.buttons.Button;
+import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder;
+import net.dv8tion.jda.api.utils.messages.MessageCreateData;
+import net.dv8tion.jda.internal.requests.CompletedRestAction;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.togetherjava.tjbot.commands.MessageReceiverAdapter;
+import org.togetherjava.tjbot.commands.UserInteractionType;
+import org.togetherjava.tjbot.commands.UserInteractor;
+import org.togetherjava.tjbot.commands.componentids.ComponentIdGenerator;
+import org.togetherjava.tjbot.commands.componentids.ComponentIdInteractor;
+import org.togetherjava.tjbot.commands.utils.CodeFence;
+import org.togetherjava.tjbot.commands.utils.MessageUtils;
+
+import javax.annotation.Nullable;
+
+import java.awt.Color;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Function;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+
+/**
+ * Handler that detects code in messages and offers code actions to the user, such as formatting
+ * their code.
+ *
+ * Code actions are automatically updated whenever the code in the original message is edited or
+ * deleted.
+ */
+public final class CodeMessageHandler extends MessageReceiverAdapter implements UserInteractor {
+ private static final Logger logger = LoggerFactory.getLogger(CodeMessageHandler.class);
+
+ static final Color AMBIENT_COLOR = Color.decode("#FDFD96");
+
+ private final ComponentIdInteractor componentIdInteractor;
+ private final Map labelToCodeAction;
+
+ /**
+ * Memorizes the ID of the bots code-reply message that a message belongs to. That way, the
+ * code-reply can be retrieved and managed easily when the original message is edited or
+ * deleted. Losing this cache, for example during bot-restart, effectively disables this
+ * update-feature for old messages.
+ *
+ * The feature is secondary though, which is why its kept in RAM and not in the DB.
+ */
+ private final Cache originalMessageToCodeReply =
+ Caffeine.newBuilder().maximumSize(2_000).build();
+
+ /**
+ * Creates a new instance.
+ */
+ public CodeMessageHandler() {
+ super(Pattern.compile(".*"));
+
+ componentIdInteractor = new ComponentIdInteractor(getInteractionType(), getName());
+
+ List codeActions = List.of(new FormatCodeCommand());
+
+ labelToCodeAction = codeActions.stream()
+ .collect(Collectors.toMap(CodeAction::getLabel, Function.identity(), (x, y) -> y,
+ LinkedHashMap::new));
+ }
+
+ @Override
+ public String getName() {
+ return "code-actions";
+ }
+
+ @Override
+ public UserInteractionType getInteractionType() {
+ return UserInteractionType.OTHER;
+ }
+
+ @Override
+ public void onSelectMenuSelection(SelectMenuInteractionEvent event, List args) {
+ throw new UnsupportedOperationException("Not used");
+ }
+
+ @Override
+ public void onModalSubmitted(ModalInteractionEvent event, List args) {
+ throw new UnsupportedOperationException("Not used");
+ }
+
+ @Override
+ public void acceptComponentIdGenerator(ComponentIdGenerator generator) {
+ componentIdInteractor.acceptComponentIdGenerator(generator);
+ }
+
+ @Override
+ public void onMessageReceived(MessageReceivedEvent event) {
+ if (event.isWebhookMessage() || event.getAuthor().isBot()) {
+ return;
+ }
+
+ Message originalMessage = event.getMessage();
+ String content = originalMessage.getContentRaw();
+
+ Optional maybeCode = MessageUtils.extractCode(content);
+ if (maybeCode.isEmpty()) {
+ // There is no code in the message, ignore it
+ return;
+ }
+
+ // Suggest code actions and remember the message <-> reply
+ originalMessage.reply(createCodeReplyMessage(originalMessage.getIdLong()))
+ .onSuccess(replyMessage -> originalMessageToCodeReply.put(originalMessage.getIdLong(),
+ replyMessage.getIdLong()))
+ .queue();
+ }
+
+ private MessageCreateData createCodeReplyMessage(long originalMessageId) {
+ return new MessageCreateBuilder().setContent("Detected code, here are some useful tools:")
+ .setActionRow(createButtons(originalMessageId, null))
+ .build();
+ }
+
+ private List createButtons(long originalMessageId,
+ @Nullable CodeAction currentlyActiveAction) {
+ return labelToCodeAction.values().stream().map(action -> {
+ Button button = createButtonForAction(action, originalMessageId);
+ return action == currentlyActiveAction ? button.asDisabled() : button;
+ }).toList();
+ }
+
+ private Button createButtonForAction(CodeAction action, long originalMessageId) {
+ return Button.primary(
+ componentIdInteractor.generateComponentId(Long.toString(originalMessageId)),
+ action.getLabel());
+ }
+
+ @Override
+ public void onButtonClick(ButtonInteractionEvent event, List args) {
+ long originalMessageId = Long.parseLong(args.get(0));
+ CodeAction codeAction = getActionOfEvent(event);
+
+ event.deferEdit().queue();
+
+ // User decided for an action, apply it to the code
+ event.getChannel()
+ .retrieveMessageById(originalMessageId)
+ .mapToResult()
+ .flatMap(originalMessage -> {
+ if (originalMessage.isFailure()) {
+ return event.getHook()
+ .sendMessage(
+ "Sorry, I am unable to locate the original message that contained the code, was it deleted?")
+ .setEphemeral(true);
+ }
+
+ // If the bot got restarted in the meantime, it forgot about the message
+ // since we have the context here, we can restore that information
+ originalMessageToCodeReply.put(originalMessageId, event.getMessageIdLong());
+
+ Optional maybeCode =
+ MessageUtils.extractCode(originalMessage.get().getContentRaw());
+ if (maybeCode.isEmpty()) {
+ return event.getHook()
+ .sendMessage(
+ "Sorry, I am unable to locate any code in the original message, was it removed?")
+ .setEphemeral(true);
+ }
+
+ // Apply the selected action
+ return event.getHook()
+ .editOriginalEmbeds(codeAction.apply(maybeCode.orElseThrow()))
+ .setActionRow(createButtons(originalMessageId, codeAction));
+ })
+ .queue();
+ }
+
+ private CodeAction getActionOfEvent(ButtonInteractionEvent event) {
+ return labelToCodeAction.get(event.getButton().getLabel());
+ }
+
+ @Override
+ public void onMessageUpdated(MessageUpdateEvent event) {
+ long originalMessageId = event.getMessageIdLong();
+
+ Long codeReplyMessageId = originalMessageToCodeReply.getIfPresent(originalMessageId);
+ if (codeReplyMessageId == null) {
+ // Some unrelated non-code message was edited
+ return;
+ }
+
+ // Edit the code reply as well by re-applying the current action
+ String content = event.getMessage().getContentRaw();
+
+ Optional maybeCode = MessageUtils.extractCode(content);
+ if (maybeCode.isEmpty()) {
+ // The original message had code, but now the code was removed
+ return;
+ }
+
+ event.getChannel().retrieveMessageById(codeReplyMessageId).flatMap(codeReplyMessage -> {
+ Optional maybeCodeAction = getCurrentActionFromCodeReply(codeReplyMessage);
+ if (maybeCodeAction.isEmpty()) {
+ // The user did not decide on an action yet, nothing to update
+ return new CompletedRestAction<>(event.getJDA(), null);
+ }
+
+ // Re-apply the current action
+ return codeReplyMessage
+ .editMessageEmbeds(maybeCodeAction.orElseThrow().apply(maybeCode.orElseThrow()));
+ }).queue(any -> {
+ }, failure -> logger.warn(
+ "Attempted to update a code-reply-message ({}), but failed. The original code-message was {}",
+ codeReplyMessageId, originalMessageId, failure));
+ }
+
+ private Optional getCurrentActionFromCodeReply(Message codeReplyMessage) {
+ // The disabled action is the currently applied action
+ return codeReplyMessage.getButtons()
+ .stream()
+ .filter(Button::isDisabled)
+ .map(Button::getLabel)
+ .map(labelToCodeAction::get)
+ .findAny();
+ }
+
+ @Override
+ public void onMessageDeleted(MessageDeleteEvent event) {
+ long originalMessageId = event.getMessageIdLong();
+
+ Long codeReplyMessageId = originalMessageToCodeReply.getIfPresent(originalMessageId);
+ if (codeReplyMessageId == null) {
+ // Some unrelated non-code message was deleted
+ return;
+ }
+
+ // Delete the code reply as well
+ originalMessageToCodeReply.invalidate(codeReplyMessageId);
+
+ event.getChannel().deleteMessageById(codeReplyMessageId).queue(any -> {
+ }, failure -> logger.warn(
+ "Attempted to delete a code-reply-message ({}), but failed. The original code-message was {}",
+ codeReplyMessageId, originalMessageId, failure));
+ }
+}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/code/FormatCodeCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/code/FormatCodeCommand.java
new file mode 100644
index 0000000000..2a3b086cc4
--- /dev/null
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/code/FormatCodeCommand.java
@@ -0,0 +1,39 @@
+package org.togetherjava.tjbot.commands.code;
+
+import net.dv8tion.jda.api.EmbedBuilder;
+import net.dv8tion.jda.api.entities.MessageEmbed;
+
+import org.togetherjava.tjbot.commands.utils.CodeFence;
+import org.togetherjava.tjbot.formatter.Formatter;
+
+/**
+ * Formats the given code.
+ *
+ * While it will attempt formatting for any language, best results are achieved for Java code.
+ */
+final class FormatCodeCommand implements CodeAction {
+ private final Formatter formatter = new Formatter();
+
+ @Override
+ public String getLabel() {
+ return "Format";
+ }
+
+ @Override
+ public MessageEmbed apply(CodeFence codeFence) {
+ String formattedCode = formatCode(codeFence.code());
+ // Any syntax highlighting is better than none
+ String language = codeFence.language() == null ? "java" : codeFence.language();
+
+ CodeFence formattedCodeFence = new CodeFence(language, formattedCode);
+
+ return new EmbedBuilder().setTitle("Formatted code")
+ .setDescription(formattedCodeFence.toMarkdown())
+ .setColor(CodeMessageHandler.AMBIENT_COLOR)
+ .build();
+ }
+
+ private String formatCode(CharSequence code) {
+ return formatter.format(code);
+ }
+}
diff --git a/formatter/src/main/java/org/togetherjava/tjbot/formatter/util/package-info.java b/application/src/main/java/org/togetherjava/tjbot/commands/code/package-info.java
similarity index 59%
rename from formatter/src/main/java/org/togetherjava/tjbot/formatter/util/package-info.java
rename to application/src/main/java/org/togetherjava/tjbot/commands/code/package-info.java
index 25fb52e1d0..b8adb1ffd2 100644
--- a/formatter/src/main/java/org/togetherjava/tjbot/formatter/util/package-info.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/code/package-info.java
@@ -1,9 +1,9 @@
/**
- * Contains utility used by the formatter.
+ * This package offers all the functionality for working with messages containing code.
*/
@MethodsReturnNonnullByDefault
@ParametersAreNonnullByDefault
-package org.togetherjava.tjbot.formatter.util;
+package org.togetherjava.tjbot.commands.code;
import org.togetherjava.tjbot.annotations.MethodsReturnNonnullByDefault;
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/filesharing/FileSharingMessageListener.java b/application/src/main/java/org/togetherjava/tjbot/commands/filesharing/FileSharingMessageListener.java
index f4c0316ac5..67e29900f7 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/filesharing/FileSharingMessageListener.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/filesharing/FileSharingMessageListener.java
@@ -2,16 +2,27 @@
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
+import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Message;
+import net.dv8tion.jda.api.entities.Role;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.entities.channel.ChannelType;
import net.dv8tion.jda.api.entities.channel.concrete.ThreadChannel;
+import net.dv8tion.jda.api.entities.emoji.Emoji;
+import net.dv8tion.jda.api.events.interaction.ModalInteractionEvent;
+import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent;
+import net.dv8tion.jda.api.events.interaction.component.SelectMenuInteractionEvent;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
+import net.dv8tion.jda.api.interactions.components.ActionRow;
import net.dv8tion.jda.api.interactions.components.buttons.Button;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.togetherjava.tjbot.commands.MessageReceiverAdapter;
+import org.togetherjava.tjbot.commands.UserInteractionType;
+import org.togetherjava.tjbot.commands.UserInteractor;
+import org.togetherjava.tjbot.commands.componentids.ComponentIdGenerator;
+import org.togetherjava.tjbot.commands.componentids.ComponentIdInteractor;
import org.togetherjava.tjbot.config.Config;
import java.io.IOException;
@@ -37,11 +48,14 @@
* contains a file with the given extension in the
* {@link FileSharingMessageListener#extensionFilter}.
*/
-public class FileSharingMessageListener extends MessageReceiverAdapter {
+public class FileSharingMessageListener extends MessageReceiverAdapter implements UserInteractor {
private static final Logger LOGGER = LoggerFactory.getLogger(FileSharingMessageListener.class);
private static final ObjectMapper JSON = new ObjectMapper();
+ private final ComponentIdInteractor componentIdInteractor =
+ new ComponentIdInteractor(getInteractionType(), getName());
+
private static final String SHARE_API = "https://api.github.com/gists";
private static final HttpClient CLIENT = HttpClient.newHttpClient();
@@ -51,6 +65,7 @@ public class FileSharingMessageListener extends MessageReceiverAdapter {
private final Predicate isStagingChannelName;
private final Predicate isOverviewChannelName;
+ private final Predicate isSoftModRole;
/**
* Creates a new instance.
@@ -66,6 +81,7 @@ public FileSharingMessageListener(Config config) {
.asMatchPredicate();
isOverviewChannelName = Pattern.compile(config.getHelpSystem().getOverviewChannelPattern())
.asMatchPredicate();
+ isSoftModRole = Pattern.compile(config.getSoftModerationRolePattern()).asMatchPredicate();
}
@Override
@@ -128,8 +144,10 @@ private void processAttachments(MessageReceivedEvent event,
GistFiles files = new GistFiles(nameToFile);
GistRequest request = new GistRequest(event.getAuthor().getName(), false, files);
- String url = uploadToGist(request);
- sendResponse(event, url);
+ GistResponse response = uploadToGist(request);
+ String url = response.getHtmlUrl();
+ String gistId = response.getGistId();
+ sendResponse(event, url, gistId);
}
private String readAttachment(InputStream stream) {
@@ -160,7 +178,7 @@ private String getNameOf(Message.Attachment attachment) {
return fileName;
}
- private String uploadToGist(GistRequest jsonRequest) {
+ private GistResponse uploadToGist(GistRequest jsonRequest) {
String body;
try {
body = JSON.writeValueAsString(jsonRequest);
@@ -203,15 +221,21 @@ private String uploadToGist(GistRequest jsonRequest) {
throw new IllegalStateException(
"Attempting to upload file to gist, but unable to parse its JSON response.", e);
}
- return gistResponse.getHtmlUrl();
+ return gistResponse;
}
- private void sendResponse(MessageReceivedEvent event, String url) {
+ private void sendResponse(MessageReceivedEvent event, String url, String gistId) {
Message message = event.getMessage();
String messageContent =
"I uploaded your attachments as **gist**. That way, they are easier to read for everyone, especially mobile users 👍";
- message.reply(messageContent).setActionRow(Button.link(url, "gist")).queue();
+ Button gist = Button.link(url, "gist");
+
+ Button delete = Button.danger(
+ componentIdInteractor.generateComponentId(message.getAuthor().getId(), gistId),
+ Emoji.fromUnicode("🗑️"));
+
+ message.reply(messageContent).setActionRow(gist, delete).queue();
}
private boolean isHelpThread(MessageReceivedEvent event) {
@@ -224,4 +248,77 @@ private boolean isHelpThread(MessageReceivedEvent event) {
return isStagingChannelName.test(rootChannelName)
|| isOverviewChannelName.test(rootChannelName);
}
+
+ private void deleteGist(String gistId) {
+ HttpRequest request = HttpRequest.newBuilder()
+ .uri(URI.create(SHARE_API + "/" + gistId))
+ .header("Accept", "application/json")
+ .header("Authorization", "token " + gistApiKey)
+ .DELETE()
+ .build();
+
+ HttpResponse apiResponse;
+ try {
+ apiResponse = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException(
+ "Attempting to delete a gist, but the request got interrupted.", e);
+ }
+
+ int status = apiResponse.statusCode();
+ if (status == 404) {
+ String responseBody = apiResponse.body();
+ LOGGER.warn("Gist API unexpected response while deleting gist: {}.", responseBody);
+ }
+ }
+
+ @Override
+ public String getName() {
+ return "filesharing";
+ }
+
+ @Override
+ public void acceptComponentIdGenerator(ComponentIdGenerator generator) {
+ componentIdInteractor.acceptComponentIdGenerator(generator);
+ }
+
+ @Override
+ public UserInteractionType getInteractionType() {
+ return UserInteractionType.OTHER;
+ }
+
+ @Override
+ public void onButtonClick(ButtonInteractionEvent event, List args) {
+ Member interactionUser = event.getMember();
+ String gistAuthorId = args.get(0);
+ boolean hasSoftModPermissions =
+ interactionUser.getRoles().stream().map(Role::getName).anyMatch(isSoftModRole);
+
+ if (!gistAuthorId.equals(interactionUser.getId()) && !hasSoftModPermissions) {
+ event.reply("You do not have permission for this action.").setEphemeral(true).queue();
+ return;
+ }
+
+ Message message = event.getMessage();
+ List buttons = message.getButtons();
+ event.editComponents(ActionRow.of(buttons.stream().map(Button::asDisabled).toList()))
+ .queue();
+
+ String gistId = args.get(1);
+ deleteGist(gistId);
+ }
+
+ @Override
+ public void onSelectMenuSelection(SelectMenuInteractionEvent event, List args) {
+ throw new UnsupportedOperationException("Not used");
+ }
+
+ @Override
+ public void onModalSubmitted(ModalInteractionEvent event, List args) {
+ throw new UnsupportedOperationException("Not used");
+ }
+
}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/filesharing/GistResponse.java b/application/src/main/java/org/togetherjava/tjbot/commands/filesharing/GistResponse.java
index 7359bf5006..3e193c533d 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/filesharing/GistResponse.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/filesharing/GistResponse.java
@@ -12,6 +12,17 @@ final class GistResponse {
@JsonProperty("html_url")
private String htmlUrl;
+ @JsonProperty("id")
+ private String gistId;
+
+ public String getGistId() {
+ return gistId;
+ }
+
+ public void setGistId(String gistId) {
+ this.gistId = gistId;
+ }
+
public String getHtmlUrl() {
return htmlUrl;
}
@@ -19,4 +30,5 @@ public String getHtmlUrl() {
public void setHtmlUrl(String htmlUrl) {
this.htmlUrl = htmlUrl;
}
+
}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/help/AskCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/help/AskCommand.java
index 2b0c253e09..ed4e0c518e 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/help/AskCommand.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/help/AskCommand.java
@@ -1,9 +1,8 @@
package org.togetherjava.tjbot.commands.help;
-import net.dv8tion.jda.api.entities.Guild;
-import net.dv8tion.jda.api.entities.IMentionable;
-import net.dv8tion.jda.api.entities.Member;
-import net.dv8tion.jda.api.entities.Message;
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
import net.dv8tion.jda.api.entities.channel.concrete.ThreadChannel;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
@@ -19,12 +18,25 @@
import org.togetherjava.tjbot.commands.CommandVisibility;
import org.togetherjava.tjbot.commands.SlashCommandAdapter;
+import org.togetherjava.tjbot.commands.utils.MessageUtils;
import org.togetherjava.tjbot.config.Config;
+import org.togetherjava.tjbot.db.Database;
+import org.togetherjava.tjbot.db.generated.tables.records.HelpThreadsRecord;
+import javax.annotation.Nullable;
+
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.List;
import java.util.Optional;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Function;
import static org.togetherjava.tjbot.commands.help.HelpSystemHelper.TITLE_COMPACT_LENGTH_MAX;
import static org.togetherjava.tjbot.commands.help.HelpSystemHelper.TITLE_COMPACT_LENGTH_MIN;
+import static org.togetherjava.tjbot.commands.help.HelpThreadCommand.CHANGE_CATEGORY_SUBCOMMAND;
+import static org.togetherjava.tjbot.commands.help.HelpThreadCommand.CHANGE_TITLE_SUBCOMMAND;
+import static org.togetherjava.tjbot.db.generated.Tables.HELP_THREADS;
/**
* Implements the {@code /ask} command, which is the main way of asking questions. The command can
@@ -47,19 +59,27 @@
*
*/
public final class AskCommand extends SlashCommandAdapter {
+ private static final int COOLDOWN_DURATION_VALUE = 5;
+ private static final ChronoUnit COOLDOWN_DURATION_UNIT = ChronoUnit.MINUTES;
private static final Logger logger = LoggerFactory.getLogger(AskCommand.class);
public static final String COMMAND_NAME = "ask";
private static final String TITLE_OPTION = "title";
private static final String CATEGORY_OPTION = "category";
+ private final Cache userToLastAsk = Caffeine.newBuilder()
+ .maximumSize(1_000)
+ .expireAfterAccess(COOLDOWN_DURATION_VALUE, TimeUnit.of(COOLDOWN_DURATION_UNIT))
+ .build();
private final HelpSystemHelper helper;
+ private final Database database;
/**
* Creates a new instance.
*
* @param config the config to use
* @param helper the helper to use
+ * @param database the database to get help threads from
*/
- public AskCommand(Config config, HelpSystemHelper helper) {
+ public AskCommand(Config config, HelpSystemHelper helper, Database database) {
super("ask", "Ask a question - use this in the staging channel", CommandVisibility.GUILD);
OptionData title =
@@ -73,10 +93,16 @@ public AskCommand(Config config, HelpSystemHelper helper) {
getData().addOptions(title, category);
this.helper = helper;
+ this.database = database;
}
@Override
public void onSlashCommand(SlashCommandInteractionEvent event) {
+ if (isUserOnCooldown(event.getUser())) {
+ sendCooldownResponse(event);
+ return;
+ }
+
String title = event.getOption(TITLE_OPTION).getAsString();
String category = event.getOption(CATEGORY_OPTION).getAsString();
@@ -102,8 +128,67 @@ public void onSlashCommand(SlashCommandInteractionEvent event) {
overviewChannel.createThreadChannel(name.toChannelName())
.flatMap(threadChannel -> handleEvent(eventHook, threadChannel, author, title, category,
guild))
- .queue(any -> {
- }, e -> handleFailure(e, eventHook));
+ .queue(any -> userToLastAsk.put(event.getUser().getIdLong(), Instant.now()),
+ e -> handleFailure(e, eventHook));
+ }
+
+ private boolean isUserOnCooldown(User user) {
+ return Optional.ofNullable(userToLastAsk.getIfPresent(user.getIdLong()))
+ .map(lastAction -> lastAction.plus(COOLDOWN_DURATION_VALUE, COOLDOWN_DURATION_UNIT))
+ .filter(Instant.now()::isBefore)
+ .isPresent();
+ }
+
+ private void sendCooldownResponse(SlashCommandInteractionEvent event) {
+ User user = event.getUser();
+ Guild guild = event.getGuild();
+
+ HelpThreadsRecord lastThreadByAuthor = getLatestHelpThread(user);
+
+ String cooldownDuration =
+ COOLDOWN_DURATION_VALUE + " " + COOLDOWN_DURATION_UNIT.name().toLowerCase();
+
+ if (lastThreadByAuthor == null) {
+ logger.warn("Can't find the last help thread created by the user with id ({})",
+ user.getId());
+ event
+ .reply("Sorry, something went wrong. Please try again after %s."
+ .formatted(cooldownDuration))
+ .setEphemeral(true)
+ .queue();
+ return;
+ }
+
+ Function, String> formatMessage = commandMentions -> {
+ String message =
+ """
+ Sorry, you can only create a single help thread every %s. Please use your existing thread %s instead.
+ If you made a typo or similar, you can adjust the title using the command %s and the category with %s 👌""";
+
+ String lastThreadMention =
+ MessageUtils.mentionChannelById(lastThreadByAuthor.getChannelId());
+
+ return message.formatted(cooldownDuration, lastThreadMention, commandMentions.get(0),
+ commandMentions.get(1));
+ };
+
+ RestAction changeTitle = mentionHelpChangeCommand(guild, CHANGE_TITLE_SUBCOMMAND);
+ RestAction changeCategory =
+ mentionHelpChangeCommand(guild, CHANGE_CATEGORY_SUBCOMMAND);
+
+ RestAction.allOf(changeCategory, changeTitle)
+ .map(formatMessage)
+ .flatMap(text -> event.reply(text).setEphemeral(true))
+ .queue();
+ }
+
+ @Nullable
+ private HelpThreadsRecord getLatestHelpThread(User user) {
+ return database.read(context -> context.selectFrom(HELP_THREADS)
+ .where(HELP_THREADS.AUTHOR_ID.eq(user.getIdLong()))
+ .orderBy(HELP_THREADS.CREATED_AT.desc())
+ .limit(1)
+ .fetchOne());
}
private boolean handleIsValidTitle(CharSequence title, IReplyCallback event) {
@@ -173,4 +258,9 @@ private static void handleFailure(Throwable exception, InteractionHook eventHook
logger.error("Attempted to create a help thread, but failed", exception);
}
+
+ private static RestAction mentionHelpChangeCommand(Guild guild, String subcommand) {
+ return MessageUtils.mentionGuildSlashCommand(guild, HelpThreadCommand.COMMAND_NAME,
+ HelpThreadCommand.CHANGE_SUBCOMMAND_GROUP, subcommand);
+ }
}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/help/HelpSystemHelper.java b/application/src/main/java/org/togetherjava/tjbot/commands/help/HelpSystemHelper.java
index 4dce9512e0..9f622837b1 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/help/HelpSystemHelper.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/help/HelpSystemHelper.java
@@ -96,7 +96,7 @@ public HelpSystemHelper(JDA jda, Config config, Database database) {
RestAction sendExplanationMessage(GuildMessageChannel threadChannel) {
return MessageUtils
- .mentionSlashCommand(threadChannel.getGuild(), HelpThreadCommand.COMMAND_NAME,
+ .mentionGuildSlashCommand(threadChannel.getGuild(), HelpThreadCommand.COMMAND_NAME,
HelpThreadCommand.Subcommand.CLOSE.getCommandName())
.flatMap(closeCommandMention -> sendExplanationMessage(threadChannel,
closeCommandMention));
@@ -313,7 +313,7 @@ private void executeUncategorizedAdviceCheck(long threadChannelId, long authorId
// Still no category, send advice
return MessageUtils
- .mentionSlashCommand(threadChannel.getGuild(), HelpThreadCommand.COMMAND_NAME,
+ .mentionGuildSlashCommand(threadChannel.getGuild(), HelpThreadCommand.COMMAND_NAME,
HelpThreadCommand.CHANGE_SUBCOMMAND_GROUP,
HelpThreadCommand.Subcommand.CHANGE_CATEGORY.getCommandName())
.flatMap(command -> {
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/help/HelpThreadCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/help/HelpThreadCommand.java
index b4e52339f6..9d708a90cc 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/help/HelpThreadCommand.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/help/HelpThreadCommand.java
@@ -41,10 +41,10 @@
public final class HelpThreadCommand extends SlashCommandAdapter {
private static final int COOLDOWN_DURATION_VALUE = 30;
private static final ChronoUnit COOLDOWN_DURATION_UNIT = ChronoUnit.MINUTES;
- private static final String CHANGE_CATEGORY_SUBCOMMAND = "category";
+ public static final String CHANGE_CATEGORY_SUBCOMMAND = "category";
private static final String CHANGE_CATEGORY_OPTION = "category";
+ public static final String CHANGE_TITLE_SUBCOMMAND = "title";
private static final String CHANGE_TITLE_OPTION = "title";
- private static final String CHANGE_TITLE_SUBCOMMAND = "title";
public static final String CHANGE_SUBCOMMAND_GROUP = "change";
public static final String COMMAND_NAME = "help-thread";
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/help/ImplicitAskListener.java b/application/src/main/java/org/togetherjava/tjbot/commands/help/ImplicitAskListener.java
index 3b550cb0b0..22ad2eca3f 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/help/ImplicitAskListener.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/help/ImplicitAskListener.java
@@ -118,7 +118,7 @@ private boolean handleIsNotOnCooldown(Message message) {
String threadDescription = lastHelpThread == null ? "your previously created help thread"
: lastHelpThread.getAsMention();
- MessageUtils.mentionSlashCommand(message.getGuild(), AskCommand.COMMAND_NAME)
+ MessageUtils.mentionGuildSlashCommand(message.getGuild(), AskCommand.COMMAND_NAME)
.flatMap(command -> message.getChannel()
.sendMessage("""
%s Please use %s to follow up on your question, \
@@ -185,7 +185,7 @@ private static RestAction sendInitialMessage(ThreadChannel threadChanne
.build();
return MessageUtils
- .mentionSlashCommand(originalMessage.getGuild(), HelpThreadCommand.COMMAND_NAME,
+ .mentionGuildSlashCommand(originalMessage.getGuild(), HelpThreadCommand.COMMAND_NAME,
HelpThreadCommand.CHANGE_SUBCOMMAND_GROUP,
HelpThreadCommand.Subcommand.CHANGE_CATEGORY.getCommandName())
.flatMap(command -> {
@@ -204,7 +204,7 @@ private static RestAction sendInitialMessage(ThreadChannel threadChanne
}
private static RestAction notifyUser(IMentionable threadChannel, Message message) {
- return MessageUtils.mentionSlashCommand(message.getGuild(), AskCommand.COMMAND_NAME)
+ return MessageUtils.mentionGuildSlashCommand(message.getGuild(), AskCommand.COMMAND_NAME)
.flatMap(command -> message.getChannel()
.sendMessage(
"""
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/help/UserBannedDeleteRecentThreadsListener.java b/application/src/main/java/org/togetherjava/tjbot/commands/help/UserBannedDeleteRecentThreadsListener.java
new file mode 100644
index 0000000000..c0fd23822b
--- /dev/null
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/help/UserBannedDeleteRecentThreadsListener.java
@@ -0,0 +1,67 @@
+package org.togetherjava.tjbot.commands.help;
+
+import net.dv8tion.jda.api.entities.User;
+import net.dv8tion.jda.api.events.guild.GuildBanEvent;
+import net.dv8tion.jda.api.hooks.ListenerAdapter;
+import org.jooq.Record1;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.togetherjava.tjbot.commands.EventReceiver;
+import org.togetherjava.tjbot.db.Database;
+
+import java.time.Duration;
+import java.time.Instant;
+import java.util.List;
+import java.util.Objects;
+
+import static org.togetherjava.tjbot.db.generated.Tables.HELP_THREADS;
+
+/**
+ * Reacts on users being banned from a guild. It then deletes (not just closes) all their recently
+ * created help threads.
+ *
+ * This for example tackles threads created by scammers, which are otherwise not automatically
+ * cleaned up on ban.
+ */
+public final class UserBannedDeleteRecentThreadsListener extends ListenerAdapter
+ implements EventReceiver {
+ private static final Logger logger =
+ LoggerFactory.getLogger(UserBannedDeleteRecentThreadsListener.class);
+ private static final Duration RECENT_THREAD_DURATION = Duration.ofMinutes(30);
+
+ private final Database database;
+
+ /**
+ * Creates a new instance.
+ *
+ * @param database to find help threads created by the banned user
+ */
+ public UserBannedDeleteRecentThreadsListener(Database database) {
+ this.database = database;
+ }
+
+ @Override
+ public void onGuildBan(GuildBanEvent event) {
+ getUsersRecentHelpThreadIDs(event.getUser()).stream()
+ .map(event.getJDA()::getThreadChannelById)
+ .filter(Objects::nonNull)
+ .forEach(threadChannel -> threadChannel.delete().queue(any -> {
+ }, failure -> logger.warn("Failed to delete thread {} from banned user {}.",
+ threadChannel.getId(), event.getUser().getId(), failure)));
+ }
+
+ private List getUsersRecentHelpThreadIDs(User user) {
+ Instant recentThreadThreshold = Instant.now().minus(RECENT_THREAD_DURATION);
+
+ return database
+ .read(context -> context.select(HELP_THREADS.CHANNEL_ID)
+ .from(HELP_THREADS)
+ .where(HELP_THREADS.AUTHOR_ID.eq(user.getIdLong())
+ .and(HELP_THREADS.CREATED_AT.greaterThan(recentThreadThreshold)))
+ .fetch())
+ .stream()
+ .map(Record1::value1)
+ .toList();
+ }
+}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java
index 0a173c63ed..d490713b2d 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java
@@ -21,6 +21,7 @@
import org.togetherjava.tjbot.commands.CommandVisibility;
import org.togetherjava.tjbot.commands.SlashCommandAdapter;
+import org.togetherjava.tjbot.commands.utils.Pagination;
import javax.annotation.Nullable;
@@ -106,7 +107,7 @@ private > RestAction auditUser(
if (pageNumber == -1) {
pageNumberInLimits = totalPages;
} else {
- pageNumberInLimits = clamp(1, pageNumber, totalPages);
+ pageNumberInLimits = Pagination.clamp(1, pageNumber, totalPages);
}
return jda.retrieveUserById(targetId)
@@ -130,10 +131,6 @@ private List> groupActionsByPages(List actions)
return groupedActions;
}
- private static int clamp(int minInclusive, int value, int maxInclusive) {
- return Math.min(Math.max(minInclusive, value), maxInclusive);
- }
-
private static EmbedBuilder createSummaryEmbed(User user, Collection actions) {
return new EmbedBuilder().setTitle("Audit log of **%s**".formatted(user.getAsTag()))
.setAuthor(user.getName(), null, user.getAvatarUrl())
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java
index 58a2e232ce..b4877fc0e5 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java
@@ -3,11 +3,15 @@
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.*;
+import net.dv8tion.jda.api.entities.channel.concrete.PrivateChannel;
import net.dv8tion.jda.api.interactions.callbacks.IReplyCallback;
+import net.dv8tion.jda.api.requests.RestAction;
import net.dv8tion.jda.api.requests.restaction.AuditableRestAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.togetherjava.tjbot.commands.moderation.modmail.ModMailCommand;
+import org.togetherjava.tjbot.commands.utils.MessageUtils;
import org.togetherjava.tjbot.config.Config;
import javax.annotation.Nullable;
@@ -16,8 +20,11 @@
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
+import java.util.EnumSet;
import java.util.Optional;
+import java.util.Set;
import java.util.function.Predicate;
+import java.util.function.UnaryOperator;
import java.util.regex.Pattern;
/**
@@ -45,6 +52,25 @@ private ModerationUtils() {
*/
static final Color AMBIENT_COLOR = Color.decode("#895FE8");
+ /**
+ * Actions with timely constraint, like being muted for 1 hour.
+ */
+ private static final Set TEMPORARY_ACTIONS =
+ EnumSet.of(ModerationAction.MUTE);
+ /**
+ * Actions with revoking previously made actions on the user, like unmuting the user after it
+ * has been muted.
+ */
+ private static final Set REVOKE_ACTIONS =
+ EnumSet.of(ModerationAction.UNMUTE, ModerationAction.UNQUARANTINE);
+ /**
+ * Soft violations were the user still remains member of the guild, such as a warning
+ */
+ private static final Set SOFT_ACTIONS =
+ EnumSet.of(ModerationAction.WARN, ModerationAction.QUARANTINE);
+
+
+
/**
* Checks whether the given reason is valid. If not, it will handle the situation and respond to
* the user.
@@ -372,4 +398,56 @@ static Optional computeTemporaryData(String durationText) {
*/
record TemporaryData(Instant expiresAt, String duration) {
}
+
+ /**
+ * Gives out advice depending on the {@link ModerationAction} and the parameters passed into it.
+ *
+ * @param action the action that is being performed, such as banning a user.
+ * @param temporaryData if the action is a temporary action, such as a 1 hour mute.
+ * @param additionalDescription any extra description that should be part of the message, if
+ * desired
+ * @param guild for which the action was triggered.
+ * @param reason for the action.
+ * @param textChannel for which messages are being sent to.
+ *
+ * @return the appropriate advice.
+ */
+ public static RestAction sendDmAdvice(ModerationAction action,
+ @Nullable TemporaryData temporaryData, @Nullable String additionalDescription,
+ Guild guild, String reason, PrivateChannel textChannel) {
+ String additionalDescriptionInfix =
+ additionalDescription == null ? "" : "\n" + additionalDescription;
+
+ if (REVOKE_ACTIONS.contains(action)) {
+ return textChannel.sendMessage("""
+ Hey there, you have been %s in the server %s.%s
+ The reason for being %s is: %s
+ """.formatted(action.getVerb(), guild.getName(), additionalDescriptionInfix,
+ action.getVerb(), reason));
+ }
+ String durationMessage;
+ if (SOFT_ACTIONS.contains(action)) {
+ durationMessage = "";
+ } else if (TEMPORARY_ACTIONS.contains(action)) {
+ durationMessage =
+ temporaryData == null ? " permanently" : " for " + temporaryData.duration();
+ } else {
+ throw new IllegalArgumentException(
+ "Action '%s' is not supported by this method".formatted(action));
+ }
+
+ UnaryOperator createDmMessage =
+ commandMention -> """
+ Hey there, sorry to tell you but unfortunately you have been %s%s in the server %s.%s
+ To get in touch with a moderator, you can simply use the %s command here in this chat. \
+ Your message will then be forwarded and a moderator will get back to you soon 😊
+ The reason for being %s is: %s
+ """
+ .formatted(action.getVerb(), durationMessage, guild.getName(),
+ additionalDescriptionInfix, commandMention, action.getVerb(), reason);
+
+ return MessageUtils.mentionGlobalSlashCommand(guild.getJDA(), ModMailCommand.COMMAND_NAME)
+ .map(createDmMessage)
+ .flatMap(textChannel::sendMessage);
+ }
}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java
index c925496ad1..94a4efed9a 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java
@@ -73,19 +73,11 @@ private static void handleAlreadyMutedTarget(IReplyCallback event) {
private static RestAction sendDm(ISnowflake target,
@Nullable ModerationUtils.TemporaryData temporaryData, String reason, Guild guild,
GenericEvent event) {
- String durationMessage =
- temporaryData == null ? "permanently" : "for " + temporaryData.duration();
- String dmMessage =
- """
- Hey there, sorry to tell you but unfortunately you have been muted %s in the server %s.
- This means you can no longer send any messages in the server until you have been unmuted again.
- If you think this was a mistake, please contact a moderator or admin of the server.
- The reason for the mute is: %s
- """
- .formatted(durationMessage, guild.getName(), reason);
return event.getJDA()
.openPrivateChannelById(target.getId())
- .flatMap(channel -> channel.sendMessage(dmMessage))
+ .flatMap(channel -> ModerationUtils.sendDmAdvice(ModerationAction.MUTE, temporaryData,
+ "This means you can no longer send any messages in the server until you have been unmuted again.",
+ guild, reason, channel))
.mapToResult()
.map(Result::isSuccess);
}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java
index 7dd2efdb5d..dffb29292e 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java
@@ -63,18 +63,11 @@ private static void handleAlreadyQuarantinedTarget(IReplyCallback event) {
private static RestAction sendDm(ISnowflake target, String reason, Guild guild,
GenericEvent event) {
- String dmMessage =
- """
- Hey there, sorry to tell you but unfortunately you have been put under quarantine in the server %s.
- This means you can no longer interact with anyone in the server until you have been unquarantined again.
- If you think this was a mistake, or the reason no longer applies, please contact a moderator or admin of the server.
- The reason for the quarantine is: %s
- """
- .formatted(guild.getName(), reason);
-
return event.getJDA()
.openPrivateChannelById(target.getIdLong())
- .flatMap(channel -> channel.sendMessage(dmMessage))
+ .flatMap(channel -> ModerationUtils.sendDmAdvice(ModerationAction.QUARANTINE, null,
+ "This means you can no longer interact with anyone in the server until you have been unquarantined again.",
+ guild, reason, channel))
.mapToResult()
.map(Result::isSuccess);
}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java
index 0e388a2911..ce050fcd07 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java
@@ -60,14 +60,11 @@ private static void handleNotMutedTarget(IReplyCallback event) {
private static RestAction sendDm(ISnowflake target, String reason, Guild guild,
GenericEvent event) {
- String dmMessage = """
- Hey there, you have been unmuted in the server %s.
- This means you can now send messages in the server again.
- The reason for the unmute is: %s
- """.formatted(guild.getName(), reason);
return event.getJDA()
.openPrivateChannelById(target.getId())
- .flatMap(channel -> channel.sendMessage(dmMessage))
+ .flatMap(channel -> ModerationUtils.sendDmAdvice(ModerationAction.UNMUTE, null,
+ "This means you can now send messages in the server again 👌", guild, reason,
+ channel))
.mapToResult()
.map(Result::isSuccess);
}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java
index 2839d77b2f..771d9e787f 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java
@@ -64,15 +64,11 @@ private static void handleNotQuarantinedTarget(IReplyCallback event) {
private static RestAction sendDm(ISnowflake target, String reason, Guild guild,
GenericEvent event) {
- String dmMessage = """
- Hey there, you have been put out of quarantine in the server %s.
- This means you can now interact with others in the server again.
- The reason for the unquarantine is: %s
- """.formatted(guild.getName(), reason);
-
return event.getJDA()
.openPrivateChannelById(target.getIdLong())
- .flatMap(channel -> channel.sendMessage(dmMessage))
+ .flatMap(channel -> ModerationUtils.sendDmAdvice(ModerationAction.UNQUARANTINE, null,
+ "This means you can now interact with others in the server again 👌", guild,
+ reason, channel))
.mapToResult()
.map(Result::isSuccess);
}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java
index 0e52fea049..26b767b652 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java
@@ -60,13 +60,8 @@ private static RestAction dmUser(ISnowflake target, String reason, Guil
SlashCommandInteractionEvent event) {
return event.getJDA()
.openPrivateChannelById(target.getId())
- .flatMap(channel -> channel.sendMessage(
- """
- Hey there, sorry to tell you but unfortunately you have been warned in the server %s.
- If you think this was a mistake, please contact a moderator or admin of the server.
- The reason for the warning is: %s
- """
- .formatted(guild.getName(), reason)))
+ .flatMap(channel -> ModerationUtils.sendDmAdvice(ModerationAction.WARN, null, null,
+ guild, reason, channel))
.mapToResult()
.map(Result::isSuccess);
}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/BlacklistedAttachmentListener.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/BlacklistedAttachmentListener.java
index cd42cc2d82..69a8e6024c 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/BlacklistedAttachmentListener.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/BlacklistedAttachmentListener.java
@@ -3,18 +3,22 @@
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.MessageEmbed;
+import net.dv8tion.jda.api.entities.channel.concrete.PrivateChannel;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.requests.RestAction;
import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder;
import net.dv8tion.jda.api.utils.messages.MessageCreateData;
import org.togetherjava.tjbot.commands.MessageReceiverAdapter;
+import org.togetherjava.tjbot.commands.moderation.modmail.ModMailCommand;
+import org.togetherjava.tjbot.commands.utils.MessageUtils;
import org.togetherjava.tjbot.config.Config;
import org.togetherjava.tjbot.moderation.ModAuditLogWriter;
import java.awt.Color;
import java.util.List;
import java.util.Locale;
+import java.util.function.UnaryOperator;
import java.util.regex.Pattern;
/**
@@ -53,28 +57,36 @@ private void handleBadMessage(Message message) {
private RestAction dmUser(Message message) {
return message.getAuthor()
.openPrivateChannel()
- .flatMap(privateChannel -> privateChannel.sendMessage(createDmMessage(message)));
+ .flatMap(privateChannel -> sendDmMessage(message, privateChannel));
}
- private MessageCreateData createDmMessage(Message originalMessage) {
+ private RestAction sendDmMessage(Message originalMessage, PrivateChannel channel) {
String contentRaw = originalMessage.getContentRaw();
String blacklistedAttachments =
String.join(", ", getBlacklistedAttachmentsFromMessage(originalMessage));
- String dmMessageContent =
- """
+ UnaryOperator createDmText =
+ commandMention -> """
Hey there, you posted a message containing a blacklisted file attachment: %s.
We had to delete your message for security reasons.
+ To get in touch with a moderator, you can simply use the %s command here in this chat. \
+ Your message will then be forwarded and a moderator will get back to you soon 👍
Feel free to repost your message without, or with a different file instead. Sorry for any inconvenience caused by this 🙇️
"""
- .formatted(blacklistedAttachments);
-
- // No embed needed if there was no message from the user
- if (contentRaw.isEmpty()) {
- return new MessageCreateBuilder().setContent(dmMessageContent).build();
- }
- return createBaseResponse(contentRaw, dmMessageContent);
+ .formatted(blacklistedAttachments, commandMention);
+
+ return MessageUtils
+ .mentionGlobalSlashCommand(originalMessage.getJDA(), ModMailCommand.COMMAND_NAME)
+ .map(createDmText)
+ .map(dmMessageContent -> {
+ // No embed needed if there was no message from the user
+ if (contentRaw.isEmpty()) {
+ return new MessageCreateBuilder().setContent(dmMessageContent).build();
+ }
+ return createBaseResponse(contentRaw, dmMessageContent);
+ })
+ .flatMap(channel::sendMessage);
}
private MessageCreateData createBaseResponse(String originalMessageContent,
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/package-info.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/package-info.java
index cb62b969b0..9fb7d29f53 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/package-info.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/package-info.java
@@ -1,5 +1,7 @@
/**
- * This packages offers all the functionality for checking attachment safety.
+ * This packages offers all the functionality for checking attachment safety see
+ * {@link org.togetherjava.tjbot.commands.moderation.attachment.BlacklistedAttachmentListener
+ * BlacklistedAttachmentListener} as main entry point.
*/
@MethodsReturnNonnullByDefault
@ParametersAreNonnullByDefault
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java
new file mode 100644
index 0000000000..c50f8af208
--- /dev/null
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java
@@ -0,0 +1,183 @@
+package org.togetherjava.tjbot.commands.moderation.modmail;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import net.dv8tion.jda.api.EmbedBuilder;
+import net.dv8tion.jda.api.JDA;
+import net.dv8tion.jda.api.entities.MessageEmbed;
+import net.dv8tion.jda.api.entities.User;
+import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
+import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
+import net.dv8tion.jda.api.interactions.InteractionHook;
+import net.dv8tion.jda.api.interactions.commands.Command;
+import net.dv8tion.jda.api.interactions.commands.OptionType;
+import net.dv8tion.jda.api.interactions.commands.build.OptionData;
+import net.dv8tion.jda.api.requests.restaction.MessageCreateAction;
+import org.jetbrains.annotations.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.togetherjava.tjbot.commands.CommandVisibility;
+import org.togetherjava.tjbot.commands.SlashCommandAdapter;
+import org.togetherjava.tjbot.commands.utils.DiscordClientAction;
+import org.togetherjava.tjbot.config.Config;
+
+import java.awt.*;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Predicate;
+import java.util.regex.Pattern;
+
+
+/**
+ * Implements the /modmail command, which allows users to contact a moderator within the server
+ * which forwards messages to moderators in a dedicated channel given by
+ * {@link Config#getModAuditLogChannelPattern()}.
+ */
+
+public final class ModMailCommand extends SlashCommandAdapter {
+
+ private static final Logger logger = LoggerFactory.getLogger(ModMailCommand.class);
+ public static final String COMMAND_NAME = "modmail";
+ private static final String OPTION_MESSAGE = "message";
+ private static final String OPTION_STAY_ANONYMOUS = "stay-anonymous";
+ private static final String OPTION_GUILD = "server";
+ private static final int COOLDOWN_DURATION_VALUE = 30;
+ private static final ChronoUnit COOLDOWN_DURATION_UNIT = ChronoUnit.MINUTES;
+ private static final Color AMBIENT_COLOR = Color.BLACK;
+ private final Cache authorToLastModMailInvocation = createCooldownCache();
+ private final Predicate modMailChannelNamePredicate;
+ private final String configModMailChannelPattern;
+
+
+ /**
+ * Creates a new instance.
+ *
+ * @param jda the JDA instance to retrieve guildCache
+ * @param config to get the channel to forward modmails to
+ */
+ public ModMailCommand(JDA jda, Config config) {
+ super(COMMAND_NAME, "Contact the moderators of the selected guild",
+ CommandVisibility.GLOBAL);
+
+ OptionData messageOption = new OptionData(OptionType.STRING, OPTION_MESSAGE,
+ "What do you want to tell them?", true);
+ OptionData guildOption = new OptionData(OptionType.STRING, OPTION_GUILD,
+ "The server to contact mods from", true);
+ OptionData anonymousOption = new OptionData(OptionType.BOOLEAN, OPTION_STAY_ANONYMOUS,
+ "If set, your name is hidden - note that mods then can not get back to you", true);
+
+ List choices = jda.getGuildCache()
+ .stream()
+ .map(guild -> new Command.Choice(guild.getName(), guild.getIdLong()))
+ .toList();
+
+ guildOption.addChoices(choices);
+
+ getData().addOptions(messageOption, guildOption, anonymousOption);
+
+ modMailChannelNamePredicate =
+ Pattern.compile(config.getModMailChannelPattern()).asMatchPredicate();
+
+ configModMailChannelPattern = config.getModMailChannelPattern();
+ }
+
+ private Cache createCooldownCache() {
+ return Caffeine.newBuilder()
+ .maximumSize(1_000)
+ .expireAfterAccess(COOLDOWN_DURATION_VALUE, TimeUnit.of(COOLDOWN_DURATION_UNIT))
+ .build();
+ }
+
+ @Override
+ public void onSlashCommand(SlashCommandInteractionEvent event) {
+ long userId = event.getUser().getIdLong();
+
+ if (handleIsOnCooldown(userId, event)) {
+ return;
+ }
+ authorToLastModMailInvocation.put(userId, Instant.now());
+ event.deferReply().setEphemeral(true).queue();
+
+ long userGuildId = event.getOption(OPTION_GUILD).getAsLong();
+ Optional modMailAuditLog = getModMailChannel(event.getJDA(), userGuildId);
+ if (modMailAuditLog.isEmpty()) {
+ logger.warn(
+ "Cannot find the designated modmail channel in server by id {} with the pattern {}",
+ userGuildId, configModMailChannelPattern);
+ return;
+ }
+
+ MessageCreateAction message =
+ createModMessage(event, userId, modMailAuditLog.orElseThrow());
+
+ sendMessage(event, message);
+
+ }
+
+ private boolean handleIsOnCooldown(long userId, SlashCommandInteractionEvent event) {
+ if (!isChannelOnCooldown(userId)) {
+ return false;
+ }
+ event.reply("Can only be used once per %s minutes.".formatted(COOLDOWN_DURATION_VALUE))
+ .setEphemeral(true)
+ .queue();
+ return true;
+ }
+
+ private Optional getModMailChannel(JDA jda, long guildId) {
+ return jda.getGuildById(guildId)
+ .getTextChannelCache()
+ .stream()
+ .filter(channel -> modMailChannelNamePredicate.test(channel.getName()))
+ .findAny();
+ }
+
+ private MessageCreateAction createModMessage(SlashCommandInteractionEvent event, long userId,
+ TextChannel modMailAuditLog) {
+ String userMessage = event.getOption(OPTION_MESSAGE).getAsString();
+ boolean wantsToStayAnonymous = event.getOption(OPTION_STAY_ANONYMOUS).getAsBoolean();
+
+ User user = wantsToStayAnonymous ? null : event.getUser();
+ MessageCreateAction message =
+ modMailAuditLog.sendMessageEmbeds(createModMailMessage(user, userMessage));
+ if (!wantsToStayAnonymous) {
+ message.addActionRow(DiscordClientAction.General.USER.asLinkButton("Author Profile",
+ String.valueOf(userId)));
+ }
+ return message;
+ }
+
+ private void sendMessage(SlashCommandInteractionEvent event, MessageCreateAction message) {
+ InteractionHook hook = event.getHook();
+ message.mapToResult().map(result -> {
+ if (result.isSuccess()) {
+ return "Your message has been forwarded, thanks.";
+ }
+ logger.warn("There was an issue with forwarding users message.");
+ return "There was an issue forwarding your message, sorry. We are investigating.";
+ }).flatMap(hook::editOriginal).queue();
+ }
+
+ private MessageEmbed createModMailMessage(@Nullable User author, String userMessage) {
+ String authorTag = author == null ? "Anonymous" : author.getAsTag();
+ String authorAvatar = author == null ? null : author.getAvatarUrl();
+ return new EmbedBuilder().setTitle("Modmail")
+ .setAuthor(authorTag, null, authorAvatar)
+ .setDescription(userMessage)
+ .setColor(AMBIENT_COLOR)
+ .build();
+ }
+
+ private boolean isChannelOnCooldown(long userId) {
+ return Optional.ofNullable(authorToLastModMailInvocation.getIfPresent(userId))
+ .map(sinceCommandInvoked -> sinceCommandInvoked.plus(COOLDOWN_DURATION_VALUE,
+ COOLDOWN_DURATION_UNIT))
+ .filter(Instant.now()::isBefore)
+ .isPresent();
+ }
+
+}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/package-info.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/package-info.java
new file mode 100644
index 0000000000..d0a2de9825
--- /dev/null
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/package-info.java
@@ -0,0 +1,11 @@
+/**
+ * This packages offers all the functionality for messaging moderators trough mod mail see
+ * {@link org.togetherjava.tjbot.commands.moderation.modmail.ModMailCommand} as main entry point.
+ */
+@MethodsReturnNonnullByDefault
+@ParametersAreNonnullByDefault
+package org.togetherjava.tjbot.commands.moderation.modmail;
+
+import org.togetherjava.tjbot.annotations.MethodsReturnNonnullByDefault;
+
+import javax.annotation.ParametersAreNonnullByDefault;
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamBlocker.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamBlocker.java
index de54d7e19a..d38584ddf0 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamBlocker.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamBlocker.java
@@ -3,7 +3,9 @@
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.*;
+import net.dv8tion.jda.api.entities.channel.concrete.PrivateChannel;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
+import net.dv8tion.jda.api.events.interaction.ModalInteractionEvent;
import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent;
import net.dv8tion.jda.api.events.interaction.component.SelectMenuInteractionEvent;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
@@ -11,6 +13,7 @@
import net.dv8tion.jda.api.interactions.components.buttons.Button;
import net.dv8tion.jda.api.interactions.components.buttons.ButtonStyle;
import net.dv8tion.jda.api.requests.ErrorResponse;
+import net.dv8tion.jda.api.requests.RestAction;
import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder;
import net.dv8tion.jda.api.utils.messages.MessageCreateData;
import org.slf4j.Logger;
@@ -24,6 +27,7 @@
import org.togetherjava.tjbot.commands.moderation.ModerationAction;
import org.togetherjava.tjbot.commands.moderation.ModerationActionsStore;
import org.togetherjava.tjbot.commands.moderation.ModerationUtils;
+import org.togetherjava.tjbot.commands.moderation.modmail.ModMailCommand;
import org.togetherjava.tjbot.commands.utils.MessageUtils;
import org.togetherjava.tjbot.config.Config;
import org.togetherjava.tjbot.config.ScamBlockerConfig;
@@ -33,6 +37,7 @@
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Predicate;
+import java.util.function.UnaryOperator;
import java.util.regex.Pattern;
/**
@@ -97,7 +102,12 @@ public UserInteractionType getInteractionType() {
}
@Override
- public void onSelectionMenu(SelectMenuInteractionEvent event, List args) {
+ public void onSelectMenuSelection(SelectMenuInteractionEvent event, List args) {
+ throw new UnsupportedOperationException("Not used");
+ }
+
+ @Override
+ public void onModalSubmitted(ModalInteractionEvent event, List args) {
throw new UnsupportedOperationException("Not used");
}
@@ -243,19 +253,24 @@ private void dmUser(MessageReceivedEvent event) {
}
private void dmUser(Guild guild, long userId, JDA jda) {
- String dmMessage =
- """
+ jda.openPrivateChannelById(userId).flatMap(channel -> dmUser(guild, channel)).queue();
+ }
+
+ private RestAction dmUser(Guild guild, PrivateChannel channel) {
+ UnaryOperator createDmMessage =
+ commandMention -> """
Hey there, we detected that you did send scam in the server %s and therefore put you under quarantine.
This means you can no longer interact with anyone in the server until you have been unquarantined again.
If you think this was a mistake (for example, your account was hacked, but you got back control over it),
- please contact a moderator or admin of the server.
+ you can get in touch with a moderator by using the %s command. \
+ Your message will then be forwarded and a moderator will get back to you soon 👍
"""
- .formatted(guild.getName());
+ .formatted(guild.getName(), commandMention);
- jda.openPrivateChannelById(userId)
- .flatMap(channel -> channel.sendMessage(dmMessage))
- .queue();
+ return MessageUtils.mentionGlobalSlashCommand(guild.getJDA(), ModMailCommand.COMMAND_NAME)
+ .map(createDmMessage)
+ .flatMap(channel::sendMessage);
}
private Optional getReportChannel(Guild guild) {
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamDetector.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamDetector.java
index d4a2281834..f0203588b6 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamDetector.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamDetector.java
@@ -5,6 +5,7 @@
import org.togetherjava.tjbot.config.ScamBlockerConfig;
import java.net.URI;
+import java.util.Locale;
import java.util.regex.Pattern;
/**
@@ -39,19 +40,23 @@ public boolean isScam(CharSequence message) {
}
private boolean isScam(AnalyseResults results) {
- if (results.pingsEveryone && results.containsNitroKeyword && results.hasUrl) {
+ if (results.pingsEveryone && results.containsSuspiciousKeyword && results.hasUrl) {
return true;
}
- return results.containsNitroKeyword && results.hasSuspiciousUrl;
+ return results.containsSuspiciousKeyword && results.hasSuspiciousUrl;
}
private void analyzeToken(String token, AnalyseResults results) {
- if ("@everyone".equalsIgnoreCase(token)) {
+ if (token.isBlank()) {
+ return;
+ }
+
+ if (!results.pingsEveryone && "@everyone".equalsIgnoreCase(token)) {
results.pingsEveryone = true;
}
- if ("nitro".equalsIgnoreCase(token)) {
- results.containsNitroKeyword = true;
+ if (!results.containsSuspiciousKeyword && containsSuspiciousKeyword(token)) {
+ results.containsSuspiciousKeyword = true;
}
if (token.startsWith("http")) {
@@ -91,6 +96,15 @@ private void analyzeUrl(String url, AnalyseResults results) {
}
}
+ private boolean containsSuspiciousKeyword(String token) {
+ String preparedToken = token.toLowerCase(Locale.US);
+
+ return config.getSuspiciousKeywords()
+ .stream()
+ .map(keyword -> keyword.toLowerCase(Locale.US))
+ .anyMatch(preparedToken::contains);
+ }
+
private boolean isHostSimilarToKeyword(String host, String keyword) {
// NOTE This algorithm is far from optimal.
// It is good enough for our purpose though and not that complex.
@@ -116,7 +130,7 @@ private boolean isHostSimilarToKeyword(String host, String keyword) {
private static class AnalyseResults {
private boolean pingsEveryone;
- private boolean containsNitroKeyword;
+ private boolean containsSuspiciousKeyword;
private boolean hasUrl;
private boolean hasSuspiciousUrl;
}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/reminder/RemindCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/reminder/RemindCommand.java
deleted file mode 100644
index 97ab7d02cd..0000000000
--- a/application/src/main/java/org/togetherjava/tjbot/commands/reminder/RemindCommand.java
+++ /dev/null
@@ -1,154 +0,0 @@
-package org.togetherjava.tjbot.commands.reminder;
-
-import net.dv8tion.jda.api.entities.Guild;
-import net.dv8tion.jda.api.entities.ISnowflake;
-import net.dv8tion.jda.api.entities.User;
-import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
-import net.dv8tion.jda.api.interactions.callbacks.IReplyCallback;
-import net.dv8tion.jda.api.interactions.commands.OptionType;
-import net.dv8tion.jda.api.interactions.commands.build.OptionData;
-
-import org.togetherjava.tjbot.commands.CommandVisibility;
-import org.togetherjava.tjbot.commands.SlashCommandAdapter;
-import org.togetherjava.tjbot.db.Database;
-
-import java.time.*;
-import java.time.temporal.TemporalAmount;
-import java.util.List;
-
-import static org.togetherjava.tjbot.db.generated.Tables.PENDING_REMINDERS;
-
-/**
- * Implements the '/remind' command which can be used to automatically send reminders to oneself at
- * a future date.
- *
- * Example usage:
- *
- *
- * {@code
- * /remind time-amount: 5 time-unit: weeks content: Hello World!
- * }
- *
- *
- * Pending reminders are processed and send by {@link RemindRoutine}.
- */
-public final class RemindCommand extends SlashCommandAdapter {
- private static final String COMMAND_NAME = "remind";
- static final String TIME_AMOUNT_OPTION = "time-amount";
- static final String TIME_UNIT_OPTION = "time-unit";
- static final String CONTENT_OPTION = "content";
-
- private static final int MIN_TIME_AMOUNT = 1;
- private static final int MAX_TIME_AMOUNT = 1_000;
- private static final List TIME_UNITS =
- List.of("minutes", "hours", "days", "weeks", "months", "years");
- private static final Period MAX_TIME_PERIOD = Period.ofYears(3);
- static final int MAX_PENDING_REMINDERS_PER_USER = 100;
-
- private final Database database;
-
- /**
- * Creates an instance of the command.
- *
- * @param database to store and fetch the reminders from
- */
- public RemindCommand(Database database) {
- super(COMMAND_NAME, "Reminds you after a given time period has passed (e.g. in 5 weeks)",
- CommandVisibility.GUILD);
-
- // TODO As soon as JDA offers date/time selector input, this should also offer
- // "/remind at" next to "/remind in" and use subcommands then
- OptionData timeAmount = new OptionData(OptionType.INTEGER, TIME_AMOUNT_OPTION,
- "period to remind you in, the amount of time (e.g. [5] weeks)", true)
- .setRequiredRange(MIN_TIME_AMOUNT, MAX_TIME_AMOUNT);
- OptionData timeUnit = new OptionData(OptionType.STRING, TIME_UNIT_OPTION,
- "period to remind you in, the unit of time (e.g. 5 [weeks])", true);
- TIME_UNITS.forEach(unit -> timeUnit.addChoice(unit, unit));
-
- getData().addOptions(timeUnit, timeAmount)
- .addOption(OptionType.STRING, CONTENT_OPTION, "what to remind you about", true);
-
- this.database = database;
- }
-
- @Override
- public void onSlashCommand(SlashCommandInteractionEvent event) {
- int timeAmount = Math.toIntExact(event.getOption(TIME_AMOUNT_OPTION).getAsLong());
- String timeUnit = event.getOption(TIME_UNIT_OPTION).getAsString();
- String content = event.getOption(CONTENT_OPTION).getAsString();
-
- Instant remindAt = parseWhen(timeAmount, timeUnit);
- User author = event.getUser();
- Guild guild = event.getGuild();
-
- if (!handleIsRemindAtWithinLimits(remindAt, event)) {
- return;
- }
- if (!handleIsUserBelowMaxPendingReminders(author, guild, event)) {
- return;
- }
-
- event.reply("Will remind you about '%s' in %d %s.".formatted(content, timeAmount, timeUnit))
- .setEphemeral(true)
- .queue();
-
- database.write(context -> context.newRecord(PENDING_REMINDERS)
- .setCreatedAt(Instant.now())
- .setGuildId(guild.getIdLong())
- .setChannelId(event.getChannel().getIdLong())
- .setAuthorId(author.getIdLong())
- .setRemindAt(remindAt)
- .setContent(content)
- .insert());
- }
-
- private static Instant parseWhen(int whenAmount, String whenUnit) {
- TemporalAmount period = switch (whenUnit) {
- case "second", "seconds" -> Duration.ofSeconds(whenAmount);
- case "minute", "minutes" -> Duration.ofMinutes(whenAmount);
- case "hour", "hours" -> Duration.ofHours(whenAmount);
- case "day", "days" -> Period.ofDays(whenAmount);
- case "week", "weeks" -> Period.ofWeeks(whenAmount);
- case "month", "months" -> Period.ofMonths(whenAmount);
- case "year", "years" -> Period.ofYears(whenAmount);
- default -> throw new IllegalArgumentException("Unsupported unit, was: " + whenUnit);
- };
-
- return ZonedDateTime.now(ZoneOffset.UTC).plus(period).toInstant();
- }
-
- private static boolean handleIsRemindAtWithinLimits(Instant remindAt, IReplyCallback event) {
- ZonedDateTime maxWhen = ZonedDateTime.now(ZoneOffset.UTC).plus(MAX_TIME_PERIOD);
-
- if (remindAt.atZone(ZoneOffset.UTC).isBefore(maxWhen)) {
- return true;
- }
-
- event
- .reply("The reminder is set too far in the future. The maximal allowed period is '%s'."
- .formatted(MAX_TIME_PERIOD))
- .setEphemeral(true)
- .queue();
-
- return false;
- }
-
- private boolean handleIsUserBelowMaxPendingReminders(ISnowflake author, ISnowflake guild,
- IReplyCallback event) {
- int pendingReminders = database.read(context -> context.fetchCount(PENDING_REMINDERS,
- PENDING_REMINDERS.AUTHOR_ID.equal(author.getIdLong())
- .and(PENDING_REMINDERS.GUILD_ID.equal(guild.getIdLong()))));
-
- if (pendingReminders < MAX_PENDING_REMINDERS_PER_USER) {
- return true;
- }
-
- event.reply(
- "You have reached the maximum amount of pending reminders per user (%s). Please wait until some of them have been sent."
- .formatted(MAX_PENDING_REMINDERS_PER_USER))
- .setEphemeral(true)
- .queue();
-
- return false;
- }
-}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/reminder/RemindRoutine.java b/application/src/main/java/org/togetherjava/tjbot/commands/reminder/RemindRoutine.java
index db09fe8ea4..b5bedd5906 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/reminder/RemindRoutine.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/reminder/RemindRoutine.java
@@ -28,11 +28,11 @@
/**
* Routine that processes and sends pending reminders.
*
- * Reminders can be set by using {@link RemindCommand}.
+ * Reminders can be set by using {@link ReminderCommand}.
*/
public final class RemindRoutine implements Routine {
static final Logger logger = LoggerFactory.getLogger(RemindRoutine.class);
- private static final Color AMBIENT_COLOR = Color.decode("#F7F492");
+ static final Color AMBIENT_COLOR = Color.decode("#F7F492");
private static final int SCHEDULE_INTERVAL_SECONDS = 30;
private final Database database;
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/reminder/ReminderCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/reminder/ReminderCommand.java
new file mode 100644
index 0000000000..a0bb1ee9a3
--- /dev/null
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/reminder/ReminderCommand.java
@@ -0,0 +1,289 @@
+package org.togetherjava.tjbot.commands.reminder;
+
+import net.dv8tion.jda.api.EmbedBuilder;
+import net.dv8tion.jda.api.entities.Guild;
+import net.dv8tion.jda.api.entities.ISnowflake;
+import net.dv8tion.jda.api.entities.MessageEmbed;
+import net.dv8tion.jda.api.entities.User;
+import net.dv8tion.jda.api.entities.emoji.Emoji;
+import net.dv8tion.jda.api.entities.emoji.EmojiUnion;
+import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
+import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent;
+import net.dv8tion.jda.api.interactions.callbacks.IReplyCallback;
+import net.dv8tion.jda.api.interactions.commands.OptionType;
+import net.dv8tion.jda.api.interactions.commands.build.OptionData;
+import net.dv8tion.jda.api.interactions.commands.build.SubcommandData;
+import net.dv8tion.jda.api.interactions.components.buttons.Button;
+import net.dv8tion.jda.api.utils.TimeFormat;
+import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder;
+import net.dv8tion.jda.api.utils.messages.MessageCreateData;
+import net.dv8tion.jda.api.utils.messages.MessageEditData;
+import org.jooq.Result;
+
+import org.togetherjava.tjbot.commands.CommandVisibility;
+import org.togetherjava.tjbot.commands.SlashCommandAdapter;
+import org.togetherjava.tjbot.commands.utils.MessageUtils;
+import org.togetherjava.tjbot.commands.utils.Pagination;
+import org.togetherjava.tjbot.db.Database;
+import org.togetherjava.tjbot.db.generated.tables.records.PendingRemindersRecord;
+
+import java.time.*;
+import java.time.temporal.TemporalAmount;
+import java.util.List;
+
+import static org.togetherjava.tjbot.db.generated.Tables.PENDING_REMINDERS;
+
+/**
+ * Implements the '/reminder' command which can be used to automatically send reminders to oneself
+ * at a future date.
+ *
+ * Example usage:
+ *
+ *
+ * {@code
+ * /reminder create time-amount: 5 time-unit: weeks content: Hello World!
+ * }
+ *
+ * {@code
+ * /reminder list
+ * }
+ *
+ *
+ * Pending reminders are processed and send by {@link RemindRoutine}.
+ */
+public final class ReminderCommand extends SlashCommandAdapter {
+ private static final String COMMAND_NAME = "reminder";
+ private static final String LIST_SUBCOMMAND = "list";
+ static final String CREATE_SUBCOMMAND = "create";
+ static final String TIME_AMOUNT_OPTION = "time-amount";
+ static final String TIME_UNIT_OPTION = "time-unit";
+ static final String CONTENT_OPTION = "content";
+
+ private static final int MIN_TIME_AMOUNT = 1;
+ private static final int MAX_TIME_AMOUNT = 1_000;
+ private static final List TIME_UNITS =
+ List.of("minutes", "hours", "days", "weeks", "months", "years");
+ private static final Period MAX_TIME_PERIOD = Period.ofYears(3);
+ private static final int REMINDERS_PER_PAGE = 10;
+ private static final Emoji PREVIOUS_BUTTON_EMOJI = Emoji.fromUnicode("⬅");
+ private static final Emoji NEXT_BUTTON_EMOJI = Emoji.fromUnicode("➡");
+ static final int MAX_PENDING_REMINDERS_PER_USER = 100;
+
+ private final Database database;
+
+ /**
+ * Creates an instance of the command.
+ *
+ * @param database to store and fetch the reminders from
+ */
+ public ReminderCommand(Database database) {
+ super(COMMAND_NAME, "Reminds you after a given time period has passed (e.g. in 5 weeks)",
+ CommandVisibility.GUILD);
+
+ // TODO As soon as JDA offers date/time selector input, this should also offer
+ // "/remind at" next to "/remind in" and use subcommands then
+ OptionData timeAmount = new OptionData(OptionType.INTEGER, TIME_AMOUNT_OPTION,
+ "period to remind you in, the amount of time (e.g. [5] weeks)", true)
+ .setRequiredRange(MIN_TIME_AMOUNT, MAX_TIME_AMOUNT);
+ OptionData timeUnit = new OptionData(OptionType.STRING, TIME_UNIT_OPTION,
+ "period to remind you in, the unit of time (e.g. 5 [weeks])", true);
+ TIME_UNITS.forEach(unit -> timeUnit.addChoice(unit, unit));
+ OptionData content =
+ new OptionData(OptionType.STRING, CONTENT_OPTION, "what to remind you about", true);
+
+ getData().addSubcommands(
+ new SubcommandData(CREATE_SUBCOMMAND, "creates a reminder").addOptions(timeAmount,
+ timeUnit, content),
+ new SubcommandData(LIST_SUBCOMMAND, "shows all your currently pending reminders"));
+
+ this.database = database;
+ }
+
+ @Override
+ public void onSlashCommand(SlashCommandInteractionEvent event) {
+ switch (event.getSubcommandName()) {
+ case CREATE_SUBCOMMAND -> handleCreateCommand(event);
+ case LIST_SUBCOMMAND -> handleListCommand(event);
+ default -> throw new AssertionError(
+ "Unexpected Subcommand: " + event.getSubcommandName());
+ }
+ }
+
+ @Override
+ public void onButtonClick(ButtonInteractionEvent event, List args) {
+ int pageToShow = Integer.parseInt(args.get(0));
+
+ EmojiUnion emoji = event.getButton().getEmoji();
+ if (PREVIOUS_BUTTON_EMOJI.equals(emoji)) {
+ pageToShow--;
+ } else if (NEXT_BUTTON_EMOJI.equals(emoji)) {
+ pageToShow++;
+ }
+
+ Result pendingReminders =
+ getPendingReminders(event.getGuild(), event.getUser());
+
+ MessageCreateData message = createPendingRemindersPage(pendingReminders, pageToShow);
+ event.editMessage(MessageEditData.fromCreateData(message)).queue();
+ }
+
+ private void handleCreateCommand(SlashCommandInteractionEvent event) {
+ int timeAmount = Math.toIntExact(event.getOption(TIME_AMOUNT_OPTION).getAsLong());
+ String timeUnit = event.getOption(TIME_UNIT_OPTION).getAsString();
+ String content = event.getOption(CONTENT_OPTION).getAsString();
+
+ Instant remindAt = parseWhen(timeAmount, timeUnit);
+ User author = event.getUser();
+ Guild guild = event.getGuild();
+
+ if (!handleIsRemindAtWithinLimits(remindAt, event)) {
+ return;
+ }
+ if (!handleIsUserBelowMaxPendingReminders(author, guild, event)) {
+ return;
+ }
+
+ event.reply("Will remind you about '%s' in %d %s.".formatted(content, timeAmount, timeUnit))
+ .setEphemeral(true)
+ .queue();
+
+ database.write(context -> context.newRecord(PENDING_REMINDERS)
+ .setCreatedAt(Instant.now())
+ .setGuildId(guild.getIdLong())
+ .setChannelId(event.getChannel().getIdLong())
+ .setAuthorId(author.getIdLong())
+ .setRemindAt(remindAt)
+ .setContent(content)
+ .insert());
+ }
+
+ private void handleListCommand(SlashCommandInteractionEvent event) {
+ Result pendingReminders =
+ getPendingReminders(event.getGuild(), event.getUser());
+
+ event.reply(createPendingRemindersPage(pendingReminders, 1)).setEphemeral(true).queue();
+ }
+
+ private Result getPendingReminders(Guild guild, User user) {
+ return database.read(context -> context.selectFrom(PENDING_REMINDERS)
+ .where(PENDING_REMINDERS.GUILD_ID.eq(guild.getIdLong())
+ .and(PENDING_REMINDERS.AUTHOR_ID.eq(user.getIdLong())))
+ .orderBy(PENDING_REMINDERS.REMIND_AT.asc())
+ .fetch());
+ }
+
+ private MessageCreateData createPendingRemindersPage(
+ List pendingReminders, int pageToShow) {
+ // 12 reminders, 10 per page, ceil(12 / 10) = 2
+ int totalPages = Math.ceilDiv(pendingReminders.size(), REMINDERS_PER_PAGE);
+
+ pageToShow = Pagination.clamp(1, pageToShow, totalPages);
+
+ EmbedBuilder remindersEmbed = new EmbedBuilder().setTitle("Pending reminders")
+ .setColor(RemindRoutine.AMBIENT_COLOR);
+ MessageCreateBuilder pendingRemindersPage = new MessageCreateBuilder();
+
+ if (pendingReminders.isEmpty()) {
+ remindersEmbed.setDescription("No pending reminders");
+ } else {
+ if (totalPages > 1) {
+ pendingReminders = getPageEntries(pendingReminders, pageToShow);
+ remindersEmbed.setFooter("Page: %d/%d".formatted(pageToShow, totalPages));
+ pendingRemindersPage.addActionRow(createPageTurnButtons(pageToShow, totalPages));
+ }
+ pendingReminders.forEach(reminder -> addReminderAsField(reminder, remindersEmbed));
+ }
+
+ return pendingRemindersPage.addEmbeds(remindersEmbed.build()).build();
+ }
+
+ private List createPageTurnButtons(int currentPage, int totalPages) {
+ String pageNumberString = String.valueOf(currentPage);
+
+ Button previousButton =
+ Button.primary(generateComponentId(pageNumberString), PREVIOUS_BUTTON_EMOJI);
+ if (currentPage <= 1) {
+ previousButton = previousButton.asDisabled();
+ }
+
+ Button nextButton =
+ Button.primary(generateComponentId(pageNumberString), NEXT_BUTTON_EMOJI);
+ if (currentPage >= totalPages) {
+ nextButton = nextButton.asDisabled();
+ }
+
+ return List.of(previousButton, nextButton);
+ }
+
+ private static List getPageEntries(
+ List remindersRecords, int pageToDisplay) {
+ int start = (pageToDisplay - 1) * REMINDERS_PER_PAGE;
+ int end = Math.min(start + REMINDERS_PER_PAGE, remindersRecords.size());
+
+ return remindersRecords.subList(start, end);
+ }
+
+ private static void addReminderAsField(PendingRemindersRecord reminder, EmbedBuilder embed) {
+ String content = reminder.getContent();
+ long channelId = reminder.getChannelId();
+ Instant remindAt = reminder.getRemindAt();
+
+ String description = """
+ Channel: %s
+ Remind at: %s""".formatted(MessageUtils.mentionChannelById(channelId),
+ TimeFormat.DEFAULT.format(remindAt));
+
+ embed.addField(MessageUtils.abbreviate(content, MessageEmbed.TITLE_MAX_LENGTH), description,
+ false);
+ }
+
+ private static Instant parseWhen(int whenAmount, String whenUnit) {
+ TemporalAmount period = switch (whenUnit) {
+ case "second", "seconds" -> Duration.ofSeconds(whenAmount);
+ case "minute", "minutes" -> Duration.ofMinutes(whenAmount);
+ case "hour", "hours" -> Duration.ofHours(whenAmount);
+ case "day", "days" -> Period.ofDays(whenAmount);
+ case "week", "weeks" -> Period.ofWeeks(whenAmount);
+ case "month", "months" -> Period.ofMonths(whenAmount);
+ case "year", "years" -> Period.ofYears(whenAmount);
+ default -> throw new IllegalArgumentException("Unsupported unit, was: " + whenUnit);
+ };
+
+ return ZonedDateTime.now(ZoneOffset.UTC).plus(period).toInstant();
+ }
+
+ private static boolean handleIsRemindAtWithinLimits(Instant remindAt, IReplyCallback event) {
+ ZonedDateTime maxWhen = ZonedDateTime.now(ZoneOffset.UTC).plus(MAX_TIME_PERIOD);
+
+ if (remindAt.atZone(ZoneOffset.UTC).isBefore(maxWhen)) {
+ return true;
+ }
+
+ event
+ .reply("The reminder is set too far in the future. The maximal allowed period is '%s'."
+ .formatted(MAX_TIME_PERIOD))
+ .setEphemeral(true)
+ .queue();
+
+ return false;
+ }
+
+ private boolean handleIsUserBelowMaxPendingReminders(ISnowflake author, ISnowflake guild,
+ IReplyCallback event) {
+ int pendingReminders = database.read(context -> context.fetchCount(PENDING_REMINDERS,
+ PENDING_REMINDERS.AUTHOR_ID.equal(author.getIdLong())
+ .and(PENDING_REMINDERS.GUILD_ID.equal(guild.getIdLong()))));
+
+ if (pendingReminders < MAX_PENDING_REMINDERS_PER_USER) {
+ return true;
+ }
+
+ event.reply(
+ "You have reached the maximum amount of pending reminders per user (%s). Please wait until some of them have been sent."
+ .formatted(MAX_PENDING_REMINDERS_PER_USER))
+ .setEphemeral(true)
+ .queue();
+
+ return false;
+ }
+}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/reminder/package-info.java b/application/src/main/java/org/togetherjava/tjbot/commands/reminder/package-info.java
index 5aafa9946f..482666ae56 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/reminder/package-info.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/reminder/package-info.java
@@ -1,6 +1,6 @@
/**
* This packages offers all the functionality for the remind-command. The core class is
- * {@link org.togetherjava.tjbot.commands.reminder.RemindCommand}.
+ * {@link org.togetherjava.tjbot.commands.reminder.ReminderCommand}.
*/
@MethodsReturnNonnullByDefault
@ParametersAreNonnullByDefault
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/system/BotCore.java b/application/src/main/java/org/togetherjava/tjbot/commands/system/BotCore.java
index 14ece90c2f..90305621f1 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/system/BotCore.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/system/BotCore.java
@@ -2,15 +2,18 @@
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.channel.Channel;
+import net.dv8tion.jda.api.events.interaction.ModalInteractionEvent;
import net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent;
import net.dv8tion.jda.api.events.interaction.command.MessageContextInteractionEvent;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.events.interaction.command.UserContextInteractionEvent;
import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent;
import net.dv8tion.jda.api.events.interaction.component.SelectMenuInteractionEvent;
+import net.dv8tion.jda.api.events.message.MessageDeleteEvent;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.events.message.MessageUpdateEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
+import net.dv8tion.jda.api.interactions.callbacks.IReplyCallback;
import net.dv8tion.jda.api.interactions.components.ComponentInteraction;
import org.jetbrains.annotations.Unmodifiable;
import org.slf4j.Logger;
@@ -211,6 +214,14 @@ public void onMessageUpdate(final MessageUpdateEvent event) {
}
}
+ @Override
+ public void onMessageDelete(final MessageDeleteEvent event) {
+ if (event.isFromGuild()) {
+ getMessageReceiversSubscribedTo(event.getChannel())
+ .forEach(messageReceiver -> messageReceiver.onMessageDeleted(event));
+ }
+ }
+
private Stream getMessageReceiversSubscribedTo(Channel channel) {
String channelName = channel.getName();
return channelNameToMessageReceiver.entrySet()
@@ -256,7 +267,29 @@ public void onSelectMenuInteraction(SelectMenuInteractionEvent event) {
logger.debug("Received selection menu event '{}' (#{}) on guild '{}'",
event.getComponentId(), event.getId(), event.getGuild());
COMMAND_SERVICE
- .execute(() -> forwardComponentCommand(event, UserInteractor::onSelectionMenu));
+ .execute(() -> forwardComponentCommand(event, UserInteractor::onSelectMenuSelection));
+ }
+
+ @Override
+ public void onModalInteraction(final ModalInteractionEvent event) {
+ logger.debug("Received modal event '{}' (#{}) on guild '{}'", event.getModalId(),
+ event.getId(), event.getGuild());
+ COMMAND_SERVICE.execute(() -> {
+ Optional componentIdOptional =
+ handleParseComponentId(event, event.getModalId());
+
+ if (componentIdOptional.isEmpty()) {
+ return;
+ }
+
+ ComponentId componentId = componentIdOptional.orElseThrow();
+
+ UserInteractor interactor =
+ requireUserInteractor(componentId.userInteractorName(), UserInteractor.class);
+ logger.trace("Routing a modal event with id '{}' back to user interactor '{}'",
+ event.getModalId(), interactor.getName());
+ interactor.onModalSubmitted(event, componentId.elements());
+ });
}
@Override
@@ -281,6 +314,42 @@ public void onUserContextInteraction(final UserContextInteractionEvent event) {
UserContextCommand.class).onUserContext(event));
}
+ /**
+ * Returns the {@link ComponentId} instace of the given componentId. If the component has
+ * expired, the user gets a message stating that.
+ *
+ * @param event the {@link IReplyCallback event} to reply to
+ * @param componentId the component's ID
+ * @return the relating {@link ComponentId}
+ */
+ public Optional handleParseComponentId(IReplyCallback event, String componentId) {
+ Optional componentIdOpt;
+ try {
+ componentIdOpt = componentIdParser.parse(componentId);
+ } catch (InvalidComponentIdFormatException | IllegalArgumentException e) {
+ logger.error(
+ """
+ Unable to route event (#{}) back to its corresponding {}}.
+ The component ID was in an unexpected format. All button and menu events have to use a component ID created in a specific format
+ (refer to the documentation of {}}). Component ID was: {}
+ {}
+ """,
+ event.getId(), UserInteractor.class.getSimpleName(),
+ UserInteractor.class.getSimpleName(), componentId, e);
+ // Unable to forward, simply fade out the event
+ return Optional.empty();
+ }
+
+ if (componentIdOpt.isEmpty()) {
+ logger.warn("The event (#{}) has an expired component ID, which was: {}.",
+ event.getId(), componentId);
+ event.reply("Sorry, but this event has expired. You can not use it anymore.")
+ .setEphemeral(true)
+ .queue();
+ }
+
+ return componentIdOpt;
+ }
/**
* Forwards the given component event to the associated user interactor.
@@ -300,27 +369,15 @@ public void onUserContextInteraction(final UserContextInteractionEvent event) {
*/
private void forwardComponentCommand(T event,
TriConsumer super UserInteractor, ? super T, ? super List> interactorArgumentConsumer) {
- Optional componentIdOpt;
- try {
- componentIdOpt = componentIdParser.parse(event.getComponentId());
- } catch (InvalidComponentIdFormatException e) {
- logger
- .error("Unable to route event (#{}) back to its corresponding user interactor. The component ID was in an unexpected format."
- + " All button and menu events have to use a component ID created in a specific format"
- + " (refer to the documentation of UserInteractor). Component ID was: {}",
- event.getId(), event.getComponentId(), e);
- // Unable to forward, simply fade out the event
- return;
- }
- if (componentIdOpt.isEmpty()) {
- logger.warn("The event (#{}) has an expired component ID, which was: {}.",
- event.getId(), event.getComponentId());
- event.reply("Sorry, but this event has expired. You can not use it anymore.")
- .setEphemeral(true)
- .queue();
+
+ Optional componentIdOptional =
+ handleParseComponentId(event, event.getComponentId());
+
+ if (componentIdOptional.isEmpty()) {
return;
}
- ComponentId componentId = componentIdOpt.orElseThrow();
+
+ ComponentId componentId = componentIdOptional.orElseThrow();
UserInteractor interactor =
requireUserInteractor(componentId.userInteractorName(), UserInteractor.class);
@@ -334,8 +391,8 @@ private void forwardComponentCommand(T event,
*
* @param prefixedName the prefixed name of the interactor
* @param typeToken a token of the type to expect
- * @return the user interactor with the given name
* @param the type to expect the user interactor to be of
+ * @return the user interactor with the given name
*/
private T requireUserInteractor(String prefixedName,
Class typeToken) {
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/tophelper/TopHelpersMessageListener.java b/application/src/main/java/org/togetherjava/tjbot/commands/tophelper/TopHelpersMessageListener.java
index 58603474cd..e1019ae39d 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/tophelper/TopHelpersMessageListener.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/tophelper/TopHelpersMessageListener.java
@@ -2,6 +2,7 @@
import net.dv8tion.jda.api.entities.channel.ChannelType;
import net.dv8tion.jda.api.entities.channel.concrete.ThreadChannel;
+import net.dv8tion.jda.api.entities.channel.unions.MessageChannelUnion;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import org.togetherjava.tjbot.commands.MessageReceiverAdapter;
@@ -18,6 +19,14 @@
* {@link TopHelpersCommand} to pick them up.
*/
public final class TopHelpersMessageListener extends MessageReceiverAdapter {
+ /**
+ * Matches invisible control characters and unused code points
+ *
+ * @see Unicode
+ * Categories
+ */
+ private static final Pattern INVALID_CHARACTERS = Pattern.compile("\\p{C}");
+
private final Database database;
private final Predicate isStagingChannelName;
@@ -42,36 +51,44 @@ public TopHelpersMessageListener(Database database, Config config) {
@Override
public void onMessageReceived(MessageReceivedEvent event) {
- if (event.getAuthor().isBot() || event.isWebhookMessage()) {
- return;
- }
-
- if (!isHelpThread(event)) {
+ if (shouldIgnoreMessage(event)) {
return;
}
addMessageRecord(event);
}
- private boolean isHelpThread(MessageReceivedEvent event) {
- if (event.getChannelType() != ChannelType.GUILD_PUBLIC_THREAD) {
- return false;
- }
-
- ThreadChannel thread = event.getChannel().asThreadChannel();
- String rootChannelName = thread.getParentChannel().getName();
- return isStagingChannelName.test(rootChannelName)
- || isOverviewChannelName.test(rootChannelName);
- }
-
private void addMessageRecord(MessageReceivedEvent event) {
+ long messageLength = countValidCharacters(event.getMessage().getContentRaw());
+
database.write(context -> context.newRecord(HELP_CHANNEL_MESSAGES)
.setMessageId(event.getMessage().getIdLong())
.setGuildId(event.getGuild().getIdLong())
.setChannelId(event.getChannel().getIdLong())
.setAuthorId(event.getAuthor().getIdLong())
.setSentAt(event.getMessage().getTimeCreated().toInstant())
- .setMessageLength((long) event.getMessage().getContentRaw().length())
+ .setMessageLength(messageLength)
.insert());
}
+
+ boolean shouldIgnoreMessage(MessageReceivedEvent event) {
+ return event.getAuthor().isBot() || event.isWebhookMessage()
+ || !isHelpThread(event.getChannel());
+ }
+
+ boolean isHelpThread(MessageChannelUnion channel) {
+ if (channel.getType() != ChannelType.GUILD_PUBLIC_THREAD) {
+ return false;
+ }
+
+ ThreadChannel thread = channel.asThreadChannel();
+ String rootChannelName = thread.getParentChannel().getName();
+ return isStagingChannelName.test(rootChannelName)
+ || isOverviewChannelName.test(rootChannelName);
+ }
+
+ static long countValidCharacters(String messageContent) {
+ return INVALID_CHARACTERS.matcher(messageContent).replaceAll("").length();
+ }
+
}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/utils/CodeFence.java b/application/src/main/java/org/togetherjava/tjbot/commands/utils/CodeFence.java
new file mode 100644
index 0000000000..41b219160d
--- /dev/null
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/utils/CodeFence.java
@@ -0,0 +1,24 @@
+package org.togetherjava.tjbot.commands.utils;
+
+import javax.annotation.Nullable;
+
+/**
+ * Represents code in a code-fence.
+ *
+ * @param language the language of the code, optional
+ * @param code the code itself
+ */
+public record CodeFence(@Nullable String language, String code) {
+ /**
+ * Creates the Discord- and markdown-conform representation of this code-fence.
+ *
+ * @return this code fence in markdown
+ */
+ public String toMarkdown() {
+ return """
+ ```%s
+ %s
+ ```
+ """.formatted(language == null ? "" : language, code);
+ }
+}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/utils/MessageUtils.java b/application/src/main/java/org/togetherjava/tjbot/commands/utils/MessageUtils.java
index 4768006d75..ff670b17f7 100644
--- a/application/src/main/java/org/togetherjava/tjbot/commands/utils/MessageUtils.java
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/utils/MessageUtils.java
@@ -1,5 +1,6 @@
package org.togetherjava.tjbot.commands.utils;
+import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.interactions.commands.Command;
@@ -9,6 +10,8 @@
import net.dv8tion.jda.api.utils.MarkdownSanitizer;
import java.util.List;
+import java.util.Optional;
+import java.util.function.Supplier;
/**
* Utility methods for {@link Message}.
@@ -18,6 +21,7 @@
*/
public class MessageUtils {
private static final String ABBREVIATION = "...";
+ private static final String CODE_FENCE_SYMBOL = "```";
private MessageUtils() {
throw new UnsupportedOperationException("Utility class, construction not supported");
@@ -47,7 +51,7 @@ public static void disableButtons(Message message) {
* Escapes every markdown content in the given string.
*
* If the escaped message is sent to Discord, it will display the original message.
- *
+ *
* @param text the text to escape
* @return the escaped text
*/
@@ -62,8 +66,8 @@ public static String escapeMarkdown(String text) {
}
/**
- * Converts a slash command text to a mentioned slash command, which you can directly click on
- * in Discord.
+ * Converts a guild slash command text to a mentioned slash command, which you can directly
+ * click on in Discord.
*
* @param guild the {@link Guild} that contains the command
* @param commandName the command's name
@@ -71,20 +75,50 @@ public static String escapeMarkdown(String text) {
* @return Formatted string for the mentioned slash command
* @throws IllegalArgumentException when the command isn't found in the guild
*/
- public static RestAction mentionSlashCommand(Guild guild, String commandName,
+ public static RestAction mentionGuildSlashCommand(Guild guild, String commandName,
String... subCommands) {
- return guild.retrieveCommands().map(guildCommands -> {
- Command guildCommand = guildCommands.stream()
- .filter(c -> c.getName().equalsIgnoreCase(commandName))
+ RestAction> availableCommands = guild.retrieveCommands();
+ Supplier notFoundMessage = () -> "Command '%s' does not exist in guild %s"
+ .formatted(commandName, guild.getId());
+
+ return mentionSlashCommand(availableCommands, notFoundMessage, commandName, subCommands);
+ }
+
+ /**
+ * Converts a global slash command text to a mentioned slash command, which you can directly
+ * click on in Discord.
+ *
+ * @param jda to retrieve global commands from
+ * @param commandName the command's name
+ * @param subCommands optional subcommand group & subcommand, depending on the base command used
+ * @return Formatted string for the mentioned slash command
+ * @throws IllegalArgumentException when the global command was not found
+ */
+ public static RestAction mentionGlobalSlashCommand(JDA jda, String commandName,
+ String... subCommands) {
+ RestAction> availableCommands = jda.retrieveCommands();
+ Supplier notFoundMessage =
+ () -> "The global command '%s' does not exist".formatted(commandName);
+
+ return mentionSlashCommand(availableCommands, notFoundMessage, commandName, subCommands);
+ }
+
+ private static RestAction mentionSlashCommand(
+ RestAction extends List> availableCommands, Supplier notFoundMessage,
+ String commandName, String... subCommands) {
+ return availableCommands.map(commands -> {
+ Command command = commands.stream()
+ .filter(commandCandidate -> commandCandidate.getName()
+ .equalsIgnoreCase(commandName))
.findAny()
- .orElseThrow(
- () -> new IllegalArgumentException("Command '%s' does not exist in guild %s"
- .formatted(commandName, guild.getId())));
+ .orElseThrow(() -> new IllegalArgumentException(notFoundMessage.get()));
+
String commandPath = commandName;
if (subCommands.length > 0) {
commandPath += " " + String.join(" ", subCommands);
}
- return String.format("%s:%s>", String.join(" ", commandPath), guildCommand.getId());
+
+ return String.format("%s:%s>", String.join(" ", commandPath), command.getId());
});
}
@@ -109,4 +143,65 @@ public static String abbreviate(String text, int maxLength) {
return text.substring(0, maxLength - ABBREVIATION.length()) + ABBREVIATION;
}
+ /**
+ * Mentions a guild channel by its id. If the given channelId is unknown, the formatted text
+ * will say #deleted-channel in Discord.
+ *
+ * @param channelId the ID of the channel to mention
+ * @return the channel as formatted string which Discord interprets as clickable mention
+ */
+ public static String mentionChannelById(long channelId) {
+ // Clone of JDAs Channel#getAsMention, but unfortunately channel instances can not be
+ // created out of just an ID, unlike User#fromId
+ return "<#%d>".formatted(channelId);
+ }
+
+ /**
+ * Attempts to extract code posted in code-fences from the given message.
+ *
+ * For example, it would extract {@code "int x = 5 + 3;"} from
+ *
+ *
+ * Look at this:
+ * ```java
+ * int x = 5 + 3;
+ * ```
+ * Nice code.
+ *
+ *
+ * If the message contains multiple code fences, only the first is extracted.
+ *
+ * @param fullMessage the message to extract code from
+ * @return the first found code snippet, if any
+ */
+ public static Optional extractCode(String fullMessage) {
+ int codeFenceStart = fullMessage.indexOf(CODE_FENCE_SYMBOL);
+ if (codeFenceStart == -1) {
+ return Optional.empty();
+ }
+
+ int codeFenceEnd = fullMessage.indexOf(CODE_FENCE_SYMBOL, codeFenceStart + 1);
+ if (codeFenceEnd == -1) {
+ return Optional.empty();
+ }
+
+ // Language is between ``` and newline, no spaces allowed, like ```java
+ // Look for the next newline and then assert no space between
+ String language = null;
+ int languageStart = codeFenceStart + CODE_FENCE_SYMBOL.length();
+ int languageEnd = fullMessage.indexOf('\n', codeFenceStart);
+ if (languageEnd != -1) {
+ String languageCandidate = fullMessage.substring(languageStart, languageEnd);
+ if (!languageCandidate.isEmpty() && languageCandidate.indexOf(' ') == -1) {
+ language = languageCandidate;
+ }
+ }
+ if (language == null) {
+ languageEnd = languageStart;
+ }
+
+ String code = fullMessage.substring(languageEnd, codeFenceEnd).strip();
+
+ return Optional.of(new CodeFence(language, code));
+ }
}
diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/utils/Pagination.java b/application/src/main/java/org/togetherjava/tjbot/commands/utils/Pagination.java
new file mode 100644
index 0000000000..d9871e6ac8
--- /dev/null
+++ b/application/src/main/java/org/togetherjava/tjbot/commands/utils/Pagination.java
@@ -0,0 +1,23 @@
+package org.togetherjava.tjbot.commands.utils;
+
+/**
+ * Utility for pagination.
+ */
+public class Pagination {
+ private Pagination() {
+ throw new UnsupportedOperationException("Utility class, construction not supported");
+ }
+
+ /**
+ * If the number is less than min value it'll return the min value, if the number is greater
+ * than max value it'll return the max value else it'll return the value.
+ *
+ * @param min minimum value (inclusive)
+ * @param value the value to verify
+ * @param max maximum value (inclusive)
+ * @return a number between min and max inclusive
+ */
+ public static int clamp(int min, int value, int max) {
+ return Math.min(Math.max(min, value), max);
+ }
+}
diff --git a/application/src/main/java/org/togetherjava/tjbot/config/Config.java b/application/src/main/java/org/togetherjava/tjbot/config/Config.java
index d9b9d8a88f..7c078a97f7 100644
--- a/application/src/main/java/org/togetherjava/tjbot/config/Config.java
+++ b/application/src/main/java/org/togetherjava/tjbot/config/Config.java
@@ -21,6 +21,7 @@ public final class Config {
private final String projectWebsite;
private final String discordGuildInvite;
private final String modAuditLogChannelPattern;
+ private final String modMailChannelPattern;
private final String mutedRolePattern;
private final String heavyModerationRolePattern;
private final String softModerationRolePattern;
@@ -44,6 +45,8 @@ private Config(@JsonProperty(value = "token", required = true) String token,
@JsonProperty(value = "discordGuildInvite", required = true) String discordGuildInvite,
@JsonProperty(value = "modAuditLogChannelPattern",
required = true) String modAuditLogChannelPattern,
+ @JsonProperty(value = "modMailChannelPattern",
+ required = true) String modMailChannelPattern,
@JsonProperty(value = "mutedRolePattern", required = true) String mutedRolePattern,
@JsonProperty(value = "heavyModerationRolePattern",
required = true) String heavyModerationRolePattern,
@@ -71,6 +74,7 @@ private Config(@JsonProperty(value = "token", required = true) String token,
this.projectWebsite = Objects.requireNonNull(projectWebsite);
this.discordGuildInvite = Objects.requireNonNull(discordGuildInvite);
this.modAuditLogChannelPattern = Objects.requireNonNull(modAuditLogChannelPattern);
+ this.modMailChannelPattern = Objects.requireNonNull(modMailChannelPattern);
this.mutedRolePattern = Objects.requireNonNull(mutedRolePattern);
this.heavyModerationRolePattern = Objects.requireNonNull(heavyModerationRolePattern);
this.softModerationRolePattern = Objects.requireNonNull(softModerationRolePattern);
@@ -117,6 +121,16 @@ public String getModAuditLogChannelPattern() {
return modAuditLogChannelPattern;
}
+ /**
+ * Gets the REGEX pattern used to identify the channel that is supposed to contain all messages
+ * from users who want to contact a moderator.
+ *
+ * @return the channel name pattern
+ */
+ public String getModMailChannelPattern() {
+ return modMailChannelPattern;
+ }
+
/**
* Gets the token of the Discord bot to connect this application to.
*
diff --git a/application/src/main/java/org/togetherjava/tjbot/config/ScamBlockerConfig.java b/application/src/main/java/org/togetherjava/tjbot/config/ScamBlockerConfig.java
index 3881600250..275d8032ff 100644
--- a/application/src/main/java/org/togetherjava/tjbot/config/ScamBlockerConfig.java
+++ b/application/src/main/java/org/togetherjava/tjbot/config/ScamBlockerConfig.java
@@ -17,6 +17,7 @@
public final class ScamBlockerConfig {
private final Mode mode;
private final String reportChannelPattern;
+ private final Set suspiciousKeywords;
private final Set hostWhitelist;
private final Set hostBlacklist;
private final Set suspiciousHostKeywords;
@@ -26,6 +27,8 @@ public final class ScamBlockerConfig {
private ScamBlockerConfig(@JsonProperty(value = "mode", required = true) Mode mode,
@JsonProperty(value = "reportChannelPattern",
required = true) String reportChannelPattern,
+ @JsonProperty(value = "suspiciousKeywords",
+ required = true) Set suspiciousKeywords,
@JsonProperty(value = "hostWhitelist", required = true) Set hostWhitelist,
@JsonProperty(value = "hostBlacklist", required = true) Set hostBlacklist,
@JsonProperty(value = "suspiciousHostKeywords",
@@ -34,6 +37,7 @@ private ScamBlockerConfig(@JsonProperty(value = "mode", required = true) Mode mo
required = true) int isHostSimilarToKeywordDistanceThreshold) {
this.mode = Objects.requireNonNull(mode);
this.reportChannelPattern = Objects.requireNonNull(reportChannelPattern);
+ this.suspiciousKeywords = new HashSet<>(Objects.requireNonNull(suspiciousKeywords));
this.hostWhitelist = new HashSet<>(Objects.requireNonNull(hostWhitelist));
this.hostBlacklist = new HashSet<>(Objects.requireNonNull(hostBlacklist));
this.suspiciousHostKeywords = new HashSet<>(Objects.requireNonNull(suspiciousHostKeywords));
@@ -59,6 +63,15 @@ public String getReportChannelPattern() {
return reportChannelPattern;
}
+ /**
+ * Gets the set of keywords that are considered suspicious if they appear in a message.
+ *
+ * @return the set of suspicious keywords
+ */
+ public Set getSuspiciousKeywords() {
+ return Collections.unmodifiableSet(suspiciousKeywords);
+ }
+
/**
* Gets the set of trusted hosts. Urls using those hosts are not considered scam.
*
diff --git a/application/src/test/java/org/togetherjava/tjbot/commands/mediaonly/MediaOnlyChannelListenerTest.java b/application/src/test/java/org/togetherjava/tjbot/commands/mediaonly/MediaOnlyChannelListenerTest.java
index 63f6ef9520..fa5f3476ea 100644
--- a/application/src/test/java/org/togetherjava/tjbot/commands/mediaonly/MediaOnlyChannelListenerTest.java
+++ b/application/src/test/java/org/togetherjava/tjbot/commands/mediaonly/MediaOnlyChannelListenerTest.java
@@ -3,6 +3,7 @@
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.MessageEmbed;
+import net.dv8tion.jda.api.entities.channel.ChannelType;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder;
import net.dv8tion.jda.api.utils.messages.MessageCreateData;
@@ -102,7 +103,8 @@ private MessageReceivedEvent sendMessage(MessageCreateData message) {
private MessageReceivedEvent sendMessage(MessageCreateData message,
List attachments) {
- MessageReceivedEvent event = jdaTester.createMessageReceiveEvent(message, attachments);
+ MessageReceivedEvent event =
+ jdaTester.createMessageReceiveEvent(message, attachments, ChannelType.TEXT);
mediaOnlyChannelListener.onMessageReceived(event);
return event;
}
diff --git a/application/src/test/java/org/togetherjava/tjbot/commands/moderation/scam/ScamDetectorTest.java b/application/src/test/java/org/togetherjava/tjbot/commands/moderation/scam/ScamDetectorTest.java
index 8aaf8e08e8..3208ff8079 100644
--- a/application/src/test/java/org/togetherjava/tjbot/commands/moderation/scam/ScamDetectorTest.java
+++ b/application/src/test/java/org/togetherjava/tjbot/commands/moderation/scam/ScamDetectorTest.java
@@ -26,6 +26,8 @@ void setUp() {
ScamBlockerConfig scamConfig = mock(ScamBlockerConfig.class);
when(config.getScamBlocker()).thenReturn(scamConfig);
+ when(scamConfig.getSuspiciousKeywords())
+ .thenReturn(Set.of("nitro", "boob", "sexi", "esex"));
when(scamConfig.getHostWhitelist()).thenReturn(Set.of("discord.com", "discord.gg",
"discord.media", "discordapp.com", "discordapp.net", "discordstatus.com"));
when(scamConfig.getHostBlacklist()).thenReturn(Set.of("bit.ly"));
@@ -139,6 +141,9 @@ private static List provideRealScamMessages() {
Steam is giving away free discord nitro, have time to pick up at my link https://bit.ly/3nlzmUa before the action is over.""",
"""
@everyone, take nitro faster, it's already running out
- https://discordu.gift/u1CHEX2sjpDuR3T5""");
+ https://discordu.gift/u1CHEX2sjpDuR3T5""",
+ "@everyone join now https://discord.gg/boobise",
+ "@everyone join now https://discord.gg/esexiest",
+ "@everyone Join Now | Free All 12-18 y.o. https://discord.gg/eesexe");
}
}
diff --git a/application/src/test/java/org/togetherjava/tjbot/commands/reminder/RemindCommandTest.java b/application/src/test/java/org/togetherjava/tjbot/commands/reminder/ReminderCommandTest.java
similarity index 90%
rename from application/src/test/java/org/togetherjava/tjbot/commands/reminder/RemindCommandTest.java
rename to application/src/test/java/org/togetherjava/tjbot/commands/reminder/ReminderCommandTest.java
index 9867efb6b0..a628b1042a 100644
--- a/application/src/test/java/org/togetherjava/tjbot/commands/reminder/RemindCommandTest.java
+++ b/application/src/test/java/org/togetherjava/tjbot/commands/reminder/ReminderCommandTest.java
@@ -22,7 +22,7 @@
import static org.mockito.Mockito.verify;
import static org.togetherjava.tjbot.db.generated.tables.PendingReminders.PENDING_REMINDERS;
-final class RemindCommandTest {
+final class ReminderCommandTest {
private SlashCommand command;
private JdaTester jdaTester;
private RawReminderTestHelper rawReminders;
@@ -30,7 +30,7 @@ final class RemindCommandTest {
@BeforeEach
void setUp() {
Database database = Database.createMemoryDatabase(PENDING_REMINDERS);
- command = new RemindCommand(database);
+ command = new ReminderCommand(database);
jdaTester = new JdaTester();
rawReminders = new RawReminderTestHelper(database, jdaTester);
}
@@ -43,9 +43,10 @@ private SlashCommandInteractionEvent triggerSlashCommand(int timeAmount, String
private SlashCommandInteractionEvent triggerSlashCommand(int timeAmount, String timeUnit,
String content, Member author) {
SlashCommandInteractionEvent event = jdaTester.createSlashCommandInteractionEvent(command)
- .setOption(RemindCommand.TIME_AMOUNT_OPTION, timeAmount)
- .setOption(RemindCommand.TIME_UNIT_OPTION, timeUnit)
- .setOption(RemindCommand.CONTENT_OPTION, content)
+ .setSubcommand(ReminderCommand.CREATE_SUBCOMMAND)
+ .setOption(ReminderCommand.TIME_AMOUNT_OPTION, timeAmount)
+ .setOption(ReminderCommand.TIME_UNIT_OPTION, timeUnit)
+ .setOption(ReminderCommand.CONTENT_OPTION, content)
.setUserWhoTriggered(author)
.build();
@@ -82,7 +83,7 @@ void doesNotSupportDatesTooFarInFuture() {
void userIsLimitedIfTooManyPendingReminders() {
// GIVEN a user with too many reminders still pending
Instant remindAt = Instant.now().plus(100, ChronoUnit.DAYS);
- for (int i = 0; i < RemindCommand.MAX_PENDING_REMINDERS_PER_USER; i++) {
+ for (int i = 0; i < ReminderCommand.MAX_PENDING_REMINDERS_PER_USER; i++) {
rawReminders.insertReminder("foo " + i, remindAt);
}
@@ -92,7 +93,7 @@ void userIsLimitedIfTooManyPendingReminders() {
// THEN rejects and responds accordingly, no new reminder was created
verify(event)
.reply(startsWith("You have reached the maximum amount of pending reminders per user"));
- assertEquals(RemindCommand.MAX_PENDING_REMINDERS_PER_USER,
+ assertEquals(ReminderCommand.MAX_PENDING_REMINDERS_PER_USER,
rawReminders.readReminders().size());
}
@@ -103,7 +104,7 @@ void userIsNotLimitedIfOtherUserHasTooManyPendingReminders() {
// and a second user with no reminders yet
Member firstUser = jdaTester.createMemberSpy(1);
Instant remindAt = Instant.now().plus(100, ChronoUnit.DAYS);
- for (int i = 0; i < RemindCommand.MAX_PENDING_REMINDERS_PER_USER; i++) {
+ for (int i = 0; i < ReminderCommand.MAX_PENDING_REMINDERS_PER_USER; i++) {
rawReminders.insertReminder("foo " + i, remindAt, firstUser);
}
diff --git a/application/src/test/java/org/togetherjava/tjbot/commands/tophelper/TopHelperMessageListenerTest.java b/application/src/test/java/org/togetherjava/tjbot/commands/tophelper/TopHelperMessageListenerTest.java
new file mode 100644
index 0000000000..f58fbb20a4
--- /dev/null
+++ b/application/src/test/java/org/togetherjava/tjbot/commands/tophelper/TopHelperMessageListenerTest.java
@@ -0,0 +1,177 @@
+package org.togetherjava.tjbot.commands.tophelper;
+
+import net.dv8tion.jda.api.entities.channel.ChannelType;
+import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
+import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder;
+import net.dv8tion.jda.api.utils.messages.MessageCreateData;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import org.togetherjava.tjbot.config.Config;
+import org.togetherjava.tjbot.config.HelpSystemConfig;
+import org.togetherjava.tjbot.db.Database;
+import org.togetherjava.tjbot.jda.JdaTester;
+
+import java.util.List;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.togetherjava.tjbot.db.generated.tables.HelpChannelMessages.HELP_CHANNEL_MESSAGES;
+
+final class TopHelperMessageListenerTest {
+
+ private static final String STAGING_CHANNEL_PATTERN = "ask_here";
+ private static final String OVERVIEW_CHANNEL_PATTERN = "active_questions";
+
+ private static JdaTester jdaTester;
+ private static TopHelpersMessageListener topHelpersListener;
+
+ @BeforeAll
+ static void setUp() {
+ Database database = Database.createMemoryDatabase(HELP_CHANNEL_MESSAGES);
+ Config config = mock(Config.class);
+ HelpSystemConfig helpSystemConfig = mock(HelpSystemConfig.class);
+
+ when(helpSystemConfig.getStagingChannelPattern()).thenReturn(STAGING_CHANNEL_PATTERN);
+ when(helpSystemConfig.getOverviewChannelPattern()).thenReturn(OVERVIEW_CHANNEL_PATTERN);
+
+ when(config.getHelpSystem()).thenReturn(helpSystemConfig);
+
+ jdaTester = new JdaTester();
+ topHelpersListener = new TopHelpersMessageListener(database, config);
+ }
+
+ @Test
+ void recognizesValidMessages() {
+ // GIVEN a message by a human in a help channel
+ MessageReceivedEvent event =
+ createMessageReceivedEvent(false, false, true, OVERVIEW_CHANNEL_PATTERN);
+
+ // WHEN checking if the message should be ignored
+ boolean shouldBeIgnored = topHelpersListener.shouldIgnoreMessage(event);
+
+ // THEN the message is not ignored
+ assertFalse(shouldBeIgnored);
+ }
+
+ @Test
+ void ignoresBots() {
+ // GIVEN a message from a bot
+ MessageReceivedEvent event =
+ createMessageReceivedEvent(true, false, true, OVERVIEW_CHANNEL_PATTERN);
+
+ // WHEN checking if the message should be ignored
+ boolean shouldBeIgnored = topHelpersListener.shouldIgnoreMessage(event);
+
+ // THEN the message is ignored
+ assertTrue(shouldBeIgnored);
+ }
+
+ @Test
+ void ignoresWebhooks() {
+ // GIVEN a message from a webhook
+ MessageReceivedEvent event =
+ createMessageReceivedEvent(false, true, true, OVERVIEW_CHANNEL_PATTERN);
+
+ // WHEN checking if the message should be ignored
+ boolean shouldBeIgnored = topHelpersListener.shouldIgnoreMessage(event);
+
+ // THEN the message is ignored
+ assertTrue(shouldBeIgnored);
+ }
+
+ @Test
+ void ignoresWrongChannels() {
+ // GIVEN a message outside a help thread
+ MessageReceivedEvent eventNotAThread =
+ createMessageReceivedEvent(false, false, false, OVERVIEW_CHANNEL_PATTERN);
+ MessageReceivedEvent eventWrongParentName =
+ createMessageReceivedEvent(false, false, true, "memes");
+
+ // WHEN checking if the message should be ignored
+ boolean ignoresNonThreadChannels = topHelpersListener.shouldIgnoreMessage(eventNotAThread);
+ boolean ignoresWrongParentNames =
+ topHelpersListener.shouldIgnoreMessage(eventWrongParentName);
+
+ // THEN the message is ignored
+ assertTrue(ignoresNonThreadChannels, "Failed to ignore non-thread channels");
+ assertTrue(ignoresWrongParentNames, "Failed to ignore wrong parent channel names");
+ }
+
+
+ MessageReceivedEvent createMessageReceivedEvent(boolean isBot, boolean isWebhook,
+ boolean isThread, String parentChannelName) {
+ try (MessageCreateData message = new MessageCreateBuilder().setContent("Any").build()) {
+ MessageReceivedEvent event = jdaTester.createMessageReceiveEvent(message, List.of(),
+ isThread ? ChannelType.GUILD_PUBLIC_THREAD : ChannelType.TEXT);
+
+ when(jdaTester.getMemberSpy().getUser().isBot()).thenReturn(isBot);
+ when(event.getMessage().isWebhookMessage()).thenReturn(isWebhook);
+ when(jdaTester.getTextChannelSpy().getName()).thenReturn(parentChannelName);
+
+ return event;
+ }
+ }
+
+
+ @ParameterizedTest
+ @MethodSource("provideInvalidCharactersWithDescription")
+ void excludesInvalidCharacters(String invalidChars, String description) {
+ // GIVEN a string of invalid characters
+
+ // WHEN counting the amount of valid characters
+ long validCharacterCount = TopHelpersMessageListener.countValidCharacters(invalidChars);
+
+ // THEN no characters are counted
+ assertEquals(0, validCharacterCount,
+ "Characters [%s] were not fully ignored".formatted(description));
+ }
+
+
+ @ParameterizedTest
+ @MethodSource("provideValidCharacters")
+ void countsValidCharacters(String validChars) {
+ // GIVEN a string of valid characters
+
+ // WHEN counting the amount of valid characters
+ long validCharCount = TopHelpersMessageListener.countValidCharacters(validChars);
+
+ // THEN all characters are counted
+ assertEquals(validChars.length(), validCharCount,
+ "Characters [%s] were not fully ignored".formatted(validChars));
+ }
+
+
+ private static Stream provideInvalidCharactersWithDescription() {
+ return Stream.of( // Invalid characters
+ Arguments.of("\u061C", "Arabic Letter Mark"),
+ Arguments.of("\u0600", "Arabic Number Sign"),
+ Arguments.of("\u180E", "Mongolian Vowel Separator"),
+ Arguments.of("\u200B", "Zero Width Space"),
+ Arguments.of("\u200C", "Zero Width Non-Joiner"),
+ Arguments.of("\u200D", "Zero Width Joiner"),
+ Arguments.of("\u200E", "Left-to-Right Mark"),
+ Arguments.of("\u200F", "Right-to-Left Mark"));
+ }
+
+
+ private static List provideValidCharacters() {
+ return List.of( // Valid characters
+ "a", "A", "b", "B", "c", "C", "x", "X,", "y", "Y", "z", "Z", // Latin alphabet
+ "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", // Numbers
+ "°", "!", "§", "§", "$", "%", "&", "/", "(", ")", "{", "}", "[", "]", "=", // Other
+ "+", "*", "~", "-", "_", ".", ",", "?", ":", ";", "|", "<", ">", "@", "€", "µ", // Other
+ "α", "Α", "β", "Β", "γ", "Γ", "χ", "Χ", "ψ", "Ψ", "ω", "Ω", // Greek alphabet
+ "ä", "ö", "ü", "ß", // German
+ "á", "è", "î", // French
+ "天", "四", "永", // Chinese
+ "😀", "😛", "❤️", "💚", "⛔" // Emojis
+ );
+ }
+
+}
diff --git a/application/src/test/java/org/togetherjava/tjbot/commands/utils/MessageUtilsTest.java b/application/src/test/java/org/togetherjava/tjbot/commands/utils/MessageUtilsTest.java
index c97a948387..3c7bf9edfb 100644
--- a/application/src/test/java/org/togetherjava/tjbot/commands/utils/MessageUtilsTest.java
+++ b/application/src/test/java/org/togetherjava/tjbot/commands/utils/MessageUtilsTest.java
@@ -1,7 +1,13 @@
package org.togetherjava.tjbot.commands.utils;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import javax.annotation.Nullable;
+
+import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -188,4 +194,78 @@ void abbreviate() {
private record TestCaseAbbreviate(String testName, String abbreviatedMessage,
String originalMessage, int limit) {
}
+
+ private static List provideExtractCodeTests() {
+ List tests = new ArrayList<>();
+ tests.add(createExtractCodeArgumentsFor("basic", """
+ Foo
+ %s
+ Bar""", "java", """
+ public class Foo {
+ public static void main(String[] args) {
+ System.out.println("Hello");
+ }
+ }"""));
+
+ tests.add(createExtractCodeArgumentsFor("code only", "%s", "java", """
+ int x = 5;"""));
+
+ tests.add(Arguments.of("fence ends on code line", """
+ ```java
+ int x = 5;```""", new CodeFence("java", "int x = 5;")));
+
+ tests.add(createExtractCodeArgumentsFor("other language", "Foo %s Bar", "kotlin", """
+ fun main() {
+ println("Hello, World!")
+ }"""));
+
+ tests.add(createExtractCodeArgumentsFor("no language", "Foo %s Bar", null, "foo=bar"));
+
+ tests.add(Arguments.of("no language single line no spaces", "```int```",
+ new CodeFence(null, "int")));
+
+ tests.add(createExtractCodeArgumentsFor("multiple fences", """
+ Foo
+ %s
+ Bar
+ ```java
+ int x = 5;
+ ```""", "java", "System.out.println(10);"));
+
+ tests.add(Arguments.of("no code", "foo", null));
+ tests.add(Arguments.of("empty", "", null));
+
+ tests.add(Arguments.of("unclosed code block", """
+ Foo
+ ```java
+ int x = 5;""", null));
+
+ tests.add(Arguments.of("almost closed code block", """
+ ```java
+ int x = 5;
+ ``""", null));
+
+ tests.add(Arguments.of("small code fence", "Foo `int x = 5` Bar", null));
+
+ return tests;
+ }
+
+ private static Arguments createExtractCodeArgumentsFor(String testName, String textTemplate,
+ @Nullable String language, String code) {
+ String codeInFence = """
+ ```%s
+ %s
+ ```""".formatted(language == null ? "" : language, code);
+
+ String text = textTemplate.formatted(codeInFence);
+ return Arguments.of(testName, text, new CodeFence(language, code));
+ }
+
+ @ParameterizedTest
+ @MethodSource("provideExtractCodeTests")
+ void extractCode(String testName, String text, @Nullable CodeFence expectedCodeFence) {
+ CodeFence actualCodeFence = MessageUtils.extractCode(text).orElse(null);
+
+ assertEquals(expectedCodeFence, actualCodeFence, testName);
+ }
}
diff --git a/application/src/test/java/org/togetherjava/tjbot/jda/JdaTester.java b/application/src/test/java/org/togetherjava/tjbot/jda/JdaTester.java
index 3ab89df2f2..66734c2c64 100644
--- a/application/src/test/java/org/togetherjava/tjbot/jda/JdaTester.java
+++ b/application/src/test/java/org/togetherjava/tjbot/jda/JdaTester.java
@@ -4,10 +4,13 @@
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.*;
+import net.dv8tion.jda.api.entities.channel.ChannelType;
import net.dv8tion.jda.api.entities.channel.concrete.PrivateChannel;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
+import net.dv8tion.jda.api.entities.channel.concrete.ThreadChannel;
import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel;
import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel;
+import net.dv8tion.jda.api.entities.channel.unions.MessageChannelUnion;
import net.dv8tion.jda.api.entities.emoji.Emoji;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent;
@@ -32,6 +35,7 @@
import net.dv8tion.jda.internal.entities.*;
import net.dv8tion.jda.internal.entities.channel.concrete.PrivateChannelImpl;
import net.dv8tion.jda.internal.entities.channel.concrete.TextChannelImpl;
+import net.dv8tion.jda.internal.entities.channel.concrete.ThreadChannelImpl;
import net.dv8tion.jda.internal.requests.Requester;
import net.dv8tion.jda.internal.requests.restaction.AuditableRestActionImpl;
import net.dv8tion.jda.internal.requests.restaction.MessageCreateActionImpl;
@@ -98,6 +102,7 @@ public final class JdaTester {
private static final long PRIVATE_CHANNEL_ID = 1;
private static final long GUILD_ID = 1;
private static final long TEXT_CHANNEL_ID = 1;
+ private static final long THREAD_CHANNEL_ID = 2;
private final JDAImpl jda;
private final MemberImpl member;
private final GuildImpl guild;
@@ -106,6 +111,7 @@ public final class JdaTester {
private final MessageCreateActionImpl messageCreateAction;
private final WebhookMessageEditActionImpl webhookMessageEditAction;
private final TextChannelImpl textChannel;
+ private final ThreadChannelImpl threadChannel;
private final PrivateChannelImpl privateChannel;
private final InteractionHook interactionHook;
private final ReplyCallbackAction replyCallbackAction;
@@ -131,6 +137,8 @@ public JdaTester() {
Member selfMember = spy(new MemberImpl(guild, selfUser));
member = spy(new MemberImpl(guild, user));
textChannel = spy(new TextChannelImpl(TEXT_CHANNEL_ID, guild));
+ threadChannel = spy(
+ new ThreadChannelImpl(THREAD_CHANNEL_ID, guild, ChannelType.GUILD_PUBLIC_THREAD));
privateChannel = spy(new PrivateChannelImpl(jda, PRIVATE_CHANNEL_ID, user));
messageCreateAction = mock(MessageCreateActionImpl.class);
webhookMessageEditAction = mock(WebhookMessageEditActionImpl.class);
@@ -151,6 +159,7 @@ public JdaTester() {
doReturn(selfUser).when(jda).getSelfUser();
when(jda.getGuildChannelById(anyLong())).thenReturn(textChannel);
when(jda.getTextChannelById(anyLong())).thenReturn(textChannel);
+ when(jda.getThreadChannelById(anyLong())).thenReturn(threadChannel);
when(jda.getChannelById(ArgumentMatchers.>any(), anyLong()))
.thenReturn(textChannel);
when(jda.getPrivateChannelById(anyLong())).thenReturn(privateChannel);
@@ -188,6 +197,7 @@ public JdaTester() {
when(jda.retrieveUserById(anyLong())).thenReturn(userAction);
doReturn(null).when(textChannel).retrieveMessageById(any());
+ doReturn(null).when(threadChannel).retrieveMessageById(any());
interactionHook = mock(InteractionHook.class);
when(interactionHook.editOriginal(anyString())).thenReturn(webhookMessageEditAction);
@@ -197,8 +207,11 @@ public JdaTester() {
.thenReturn(webhookMessageEditAction);
doReturn(messageCreateAction).when(textChannel).sendMessageEmbeds(any(), any());
+ doReturn(messageCreateAction).when(threadChannel).sendMessageEmbeds(any(), any());
doReturn(messageCreateAction).when(textChannel).sendMessageEmbeds(any());
+ doReturn(messageCreateAction).when(threadChannel).sendMessageEmbeds(any());
doReturn(privateChannel).when(textChannel).asPrivateChannel();
+ doReturn(textChannel).when(threadChannel).getParentChannel();
doNothing().when(messageCreateAction).queue();
when(messageCreateAction.setContent(any())).thenReturn(messageCreateAction);
@@ -265,7 +278,7 @@ public ButtonClickEventBuilder createButtonInteractionEvent() {
Message message =
mockingDetails.isMock() || mockingDetails.isSpy() ? event : spy(event);
- mockMessage(message);
+ mockMessage(message, ChannelType.TEXT);
return message;
};
@@ -354,6 +367,20 @@ public TextChannel getTextChannelSpy() {
return textChannel;
}
+ /**
+ * Gets the thread channel spy used as universal thread channel by all mocks created by this
+ * tester instance.
+ *
+ * For example the events created by
+ * {@link #createMessageReceiveEvent(MessageCreateData, List, ChannelType)} can return this
+ * channel spy
+ *
+ * @return the thread channel spy used by this tester
+ */
+ public ThreadChannel getThreadChannelSpy() {
+ return threadChannel;
+ }
+
/**
* Gets the private channel spy used as universal private channel by all mocks created by this
* tester instance.
@@ -554,12 +581,14 @@ public ErrorResponseException createErrorResponseException(ErrorResponse reason)
*
* @param message the message that has been received
* @param attachments attachments of the message, empty if none
+ * @param channelType the type of the channel the message was sent in. See
+ * {@link #mockMessage(Message, ChannelType)} for supported channel types
* @return the event of receiving the given message
*/
public MessageReceivedEvent createMessageReceiveEvent(MessageCreateData message,
- List attachments) {
+ List attachments, ChannelType channelType) {
Message receivedMessage = clientMessageToReceivedMessageMock(message);
- mockMessage(receivedMessage);
+ mockMessage(receivedMessage, channelType);
doReturn(attachments).when(receivedMessage).getAttachments();
return new MessageReceivedEvent(jda, responseNumber.getAndIncrement(), receivedMessage);
@@ -638,7 +667,14 @@ private void mockButtonClickEvent(ButtonInteractionEvent event) {
doReturn(replyAction).when(event).editButton(any());
}
- private void mockMessage(Message message) {
+ private void mockMessage(Message message, ChannelType channelType) {
+ MessageChannelUnion channel = switch (channelType) {
+ case TEXT -> textChannel;
+ case GUILD_PUBLIC_THREAD -> threadChannel;
+ default -> throw new IllegalArgumentException(
+ "Unsupported channel type: " + channelType);
+ };
+
doReturn(messageCreateAction).when(message).reply(anyString());
doReturn(messageCreateAction).when(message)
.replyEmbeds(ArgumentMatchers.any());
@@ -651,7 +687,7 @@ private void mockMessage(Message message) {
doReturn(member).when(message).getMember();
doReturn(member.getUser()).when(message).getAuthor();
- doReturn(textChannel).when(message).getChannel();
+ doReturn(channel).when(message).getChannel();
doReturn(1L).when(message).getIdLong();
doReturn(false).when(message).isWebhookMessage();
diff --git a/build.gradle b/build.gradle
index e04ada7d0d..a452e25d5d 100644
--- a/build.gradle
+++ b/build.gradle
@@ -1,13 +1,17 @@
plugins {
id 'java'
id "com.diffplug.spotless" version "6.11.0"
- id "org.sonarqube" version "3.4.0.2513"
+ id "org.sonarqube" version "3.5.0.2730"
id "name.remal.sonarlint" version "1.5.0"
}
group 'org.togetherjava'
version '1.0-SNAPSHOT'
+ext {
+ jooqVersion = '3.17.2'
+}
+
// Skips sonarlint during the build, useful for testing purposes.
Boolean skipSonarlint = false
diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle
index dbfc204b7a..30898ce55d 100644
--- a/buildSrc/build.gradle
+++ b/buildSrc/build.gradle
@@ -7,6 +7,6 @@ repositories {
}
dependencies {
- implementation "gradle.plugin.org.flywaydb:gradle-plugin-publishing:9.4.0"
- implementation 'nu.studer:gradle-jooq-plugin:7.1.1'
+ implementation "gradle.plugin.org.flywaydb:gradle-plugin-publishing:9.7.0"
+ implementation 'nu.studer:gradle-jooq-plugin:8.0'
}
diff --git a/buildSrc/src/main/groovy/database-settings.gradle b/buildSrc/src/main/groovy/database-settings.gradle
index 37927aea20..8d931179d6 100644
--- a/buildSrc/src/main/groovy/database-settings.gradle
+++ b/buildSrc/src/main/groovy/database-settings.gradle
@@ -28,7 +28,7 @@ tasks.flywayMigrate {
}
jooq {
- version = "3.15.2"
+ version = jooqVersion
configurations {
main {
@@ -73,7 +73,7 @@ var sqliteVersion = "3.36.0.3"
dependencies {
implementation "org.xerial:sqlite-jdbc:${sqliteVersion}"
implementation 'org.flywaydb:flyway-core:8.0.0'
- implementation 'org.jooq:jooq:3.15.3'
+ implementation "org.jooq:jooq:$jooqVersion"
jooqGenerator "org.xerial:sqlite-jdbc:${sqliteVersion}"
}
diff --git a/database/build.gradle b/database/build.gradle
index a1c6261320..4b7902eced 100644
--- a/database/build.gradle
+++ b/database/build.gradle
@@ -7,8 +7,8 @@ var sqliteVersion = "3.39.2.0"
dependencies {
implementation 'com.google.code.findbugs:jsr305:3.0.2'
implementation "org.xerial:sqlite-jdbc:${sqliteVersion}"
- implementation 'org.flywaydb:flyway-core:9.4.0'
- implementation 'org.jooq:jooq:3.17.2'
+ implementation 'org.flywaydb:flyway-core:9.7.0'
+ implementation "org.jooq:jooq:$jooqVersion"
implementation project(':utils')
}
diff --git a/formatter/build.gradle b/formatter/build.gradle
index 9cfe849017..e05ddb18dd 100644
--- a/formatter/build.gradle
+++ b/formatter/build.gradle
@@ -7,6 +7,7 @@ dependencies {
implementation project(':utils')
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.0'
+ testImplementation 'org.junit.jupiter:junit-jupiter-params:5.9.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.0'
}
diff --git a/formatter/src/main/java/org/togetherjava/tjbot/formatter/CodeSectionFormatter.java b/formatter/src/main/java/org/togetherjava/tjbot/formatter/CodeSectionFormatter.java
deleted file mode 100644
index 4ea0f1c367..0000000000
--- a/formatter/src/main/java/org/togetherjava/tjbot/formatter/CodeSectionFormatter.java
+++ /dev/null
@@ -1,348 +0,0 @@
-package org.togetherjava.tjbot.formatter;
-
-import org.togetherjava.tjbot.formatter.tokenizer.Token;
-import org.togetherjava.tjbot.formatter.tokenizer.TokenType;
-import org.togetherjava.tjbot.formatter.util.LookaheadQueue;
-import org.togetherjava.tjbot.formatter.util.SkippableLookaheadArrayDeque;
-import org.togetherjava.tjbot.formatter.util.SkippableLookaheadQueue;
-
-import java.util.*;
-import java.util.function.Predicate;
-
-/**
- * Formatter which specifically formats code tokens (that are part of a section)
- */
-class CodeSectionFormatter {
- private final StringBuilder result = new StringBuilder();
- private final SkippableLookaheadQueue queue;
-
- private int indentation;
- private boolean applyIndentation;
- private int forLevel;
- private int genericDepth;
-
- CodeSectionFormatter(List tokens) {
- this(new SkippableLookaheadArrayDeque<>(tokens));
- }
-
- CodeSectionFormatter(SkippableLookaheadQueue queue) {
- this.queue = queue;
-
- purgeWhitespaces(this.queue);
- }
-
- /**
- * Removes all whitespaces from the given queue
- *
- * @param queue the queue to remove whitespaces from
- */
- private static void purgeWhitespaces(Queue queue) {
- queue.removeIf(t -> t.type() == TokenType.WHITESPACE);
- }
-
- /**
- * Starts the formatting process
- */
- void format() {
- Token next;
-
- while (!queue.isEmpty() && (next = queue.remove()) != null) {
- updateIndentation(next.type());
- applyIndentation();
- consume(next);
- }
- }
-
- /**
- * Consumes the next token
- *
- * @param token token to consume
- */
- private void consume(Token token) {
- TokenType type = token.type();
-
- if (checkGeneric(type)) {
- result.append(token.content());
-
- return;
- }
-
- if (genericDepth != 0) {
- handleGeneric(token);
-
- return;
- }
-
- checkFor(type);
- put(token);
- }
-
- /**
- * Puts the next token into the result
- *
- * @param token token to put
- */
- private void put(Token token) {
- TokenType type = token.type();
-
- if (isOperator(token)) { // apply space before an operator (like +, - and *)
- result.append(' ');
- }
-
- result.append(token.content());
-
- if (shouldPutSpaceAfter(token)) {
- result.append(' ');
- } else if (shouldPutNewLineAfter(type)) { // put a new line after { and ; and } and comments
- // and annotations
- appendNewLine();
-
- if (type == TokenType.SEMICOLON) {
- forLevel--;
- }
-
- applyIndentation = true;
- }
- }
-
- /**
- * Checks if a space should be put after a given token
- *
- * @param token token to check
- * @return whether a space should be put after that token
- */
- private boolean shouldPutSpaceAfter(Token token) {
- TokenType type = token.type();
-
- return isKeyword(token) || isOperator(token) || isParenthesisRule(token)
- || type == TokenType.CLOSE_BRACKETS // put a space after e.g. 'try' or 'else' and
- // ] or if it's an operator
- || type == TokenType.COMMA // for e.g. multi-arg method calls or method parameters
- || (type == TokenType.IDENTIFIER && !queue.isEmpty()
- && queue.peek().type() == TokenType.IDENTIFIER); // for double identifier
- // in e.g. method
- // declaration or enhanced
- // for loops
- }
-
- /**
- * Checks if a given token type belongs to a for loop (uses
- * {@link SkippableLookaheadQueue#peek(int, Predicate)}
- *
- * @param type current token type
- */
- private void checkFor(TokenType type) {
- if (isIndexedForLoop(type)) { // if it's a for int loop then set the forLevel to 2
- forLevel = 2;
- }
- }
-
- /**
- * Handles the case of being inside a generic type declaration
- *
- * @param token current token
- */
- private void handleGeneric(Token token) {
- TokenType type = token.type();
-
- if (type == TokenType.EXTENDS || type == TokenType.SUPER) {
- result.append(' ');
- }
-
- result.append(token.content());
-
- if (type == TokenType.COMMA || type == TokenType.WILDCARD || type == TokenType.EXTENDS
- || type == TokenType.SUPER) {
- result.append(' ');
- }
-
- // ------------------------------------------------
-
- if (type == TokenType.LESS_THAN) {
- genericDepth++;
- } else if (type == TokenType.GREATER_THAN) {
- genericDepth--;
- }
-
- if (genericDepth == 0 && !queue.isEmpty()
- && queue.peek().type() != TokenType.OPEN_PARENTHESIS) { // last closing except if
- // there's an opening
- // parenthesis after it
- result.append(' ');
- }
- }
-
- /**
- * Checks if a given token type belongs to a generic type declaration (uses
- * {@link LookaheadQueue#peek(int)}
- *
- * @param type current token type
- * @return whether the token type belongs to a generic type declaration
- */
- private boolean checkGeneric(TokenType type) {
- if (type == TokenType.LESS_THAN) {
- int depth = 1;
-
- for (int i = 0;; i++) {
- Token next = queue.peek(i);
-
- if (next == null || depth == 0) {
- break;
- }
-
- TokenType nextType = next.type();
-
- if (!isValidGeneric(nextType)) {
- return false;
- }
-
- if (nextType == TokenType.LESS_THAN) {
- depth++;
- } else if (nextType == TokenType.GREATER_THAN) {
- depth--;
- }
- }
-
- genericDepth = 1;
-
- return true;
- }
-
- return false;
- }
-
- /**
- * Checks if a given token type would be valid inside a generic type declaration
- *
- * @param type token type to check
- * @return whether it's valid inside a generic type declaration
- */
- private boolean isValidGeneric(TokenType type) {
- return type == TokenType.WILDCARD || type == TokenType.LESS_THAN
- || type == TokenType.GREATER_THAN || type == TokenType.COMMA
- || type == TokenType.DOT || type == TokenType.EXTENDS || type == TokenType.SUPER
- || type == TokenType.IDENTIFIER;
- }
-
- /**
- * Checks if a new line should be put after a given token type
- *
- * @param type token type to check
- * @return whether a new line should be put after that token
- */
- private boolean shouldPutNewLineAfter(TokenType type) {
- if (type == TokenType.OPEN_BRACES || type == TokenType.SEMICOLON
- || type == TokenType.COMMENT || type == TokenType.ANNOTATION) {
- return true;
- }
-
- // don't put new lines after braces if they're part of a lambda:
- // () -> {}; // NOSONAR
- return type == TokenType.CLOSE_BRACES && !queue.isEmpty()
- && queue.peek().type() != TokenType.SEMICOLON;
- }
-
- /**
- * Checks if there's an indexed for loop ahead (uses
- * {@link SkippableLookaheadQueue#peek(int, Predicate)})
- *
- * @param type current token type
- * @return whether there's an indexed for loop or not
- */
- private boolean isIndexedForLoop(TokenType type) {
- return type == TokenType.FOR && !internalEnhancedFor();
- }
-
- /**
- * Checks if there's an enhanced for loop ahead without checking the current token type
- *
- * @return whether there's an enhanced for loop ahead
- */
- private boolean internalEnhancedFor() {
- return queue.peek(3, t -> {
- TokenType tokenType = t.type();
-
- return tokenType == TokenType.ANNOTATION || tokenType == TokenType.FINAL;
- }).type() == TokenType.COLON;
- }
-
- /**
- * Parenthesis rule: append a space after a closing parenthesis if the next token isn't another
- * closing parenthesis, an operator or a semicolon
- *
- * @return whether a space should be put after the parenthesis
- */
- private boolean isParenthesisRule(Token token) {
- if (queue.isEmpty()) {
- return false;
- }
-
- Token next = queue.peek();
- TokenType nextType = next.type();
-
- return token.type() == TokenType.CLOSE_PARENTHESIS
- && nextType != TokenType.CLOSE_PARENTHESIS && nextType != TokenType.SEMICOLON
- && !isOperator(next);
- }
-
- /**
- * Appends a new line if there's more in the token queue
- */
- private void appendNewLine() {
- if (!queue.isEmpty()) {
- if (forLevel <= 0) {
- result.append('\n');
- } else {
- result.append(' '); // put a space after a ; in a for loop
- }
- }
- }
-
- /**
- * Checks if a given token is a keyword using {@link TokenType#isKeyword()}
- *
- * @param token token to check
- * @return whether the given token is a keyword
- */
- private boolean isKeyword(Token token) {
- return token.type().isKeyword();
- }
-
- /**
- * Checks if a given token is an operator using {@link TokenType#isOperator()}
- *
- * @param token token to check
- * @return whether the given token is an operator
- */
- private boolean isOperator(Token token) {
- return token.type().isOperator();
- }
-
- /**
- * Updates the indentation based on the current token type
- *
- * @param type current token type
- */
- private void updateIndentation(TokenType type) {
- if (type == TokenType.OPEN_BRACES) {
- indentation++;
- } else if (type == TokenType.CLOSE_BRACES) {
- indentation--;
- }
- }
-
- /**
- * Applies the current indentation
- */
- private void applyIndentation() {
- if (applyIndentation) {
- result.append(" ".repeat(Math.max(0, indentation)));
-
- applyIndentation = false;
- }
- }
-
- StringBuilder result() {
- return result;
- }
-}
diff --git a/formatter/src/main/java/org/togetherjava/tjbot/formatter/Formatter.java b/formatter/src/main/java/org/togetherjava/tjbot/formatter/Formatter.java
index 48b9f2ca25..1288a45158 100644
--- a/formatter/src/main/java/org/togetherjava/tjbot/formatter/Formatter.java
+++ b/formatter/src/main/java/org/togetherjava/tjbot/formatter/Formatter.java
@@ -1,138 +1,31 @@
package org.togetherjava.tjbot.formatter;
+import org.togetherjava.tjbot.formatter.formatting.CodeSectionFormatter;
import org.togetherjava.tjbot.formatter.tokenizer.Lexer;
import org.togetherjava.tjbot.formatter.tokenizer.Token;
-import org.togetherjava.tjbot.formatter.tokenizer.TokenType;
-import java.util.ArrayList;
import java.util.List;
-import java.util.stream.Collectors;
/**
- * Formatter which can format a given string into a string which contains code blocks etc
+ * Formats code given as string. See {@link #format(CharSequence)}.
+ *
+ * Best results are achieved for Java code.
*/
-public class Formatter {
- /**
- * Formats the given tokens
- *
- * @param tokens tokens to format
- * @return resulting code
- */
- public String format(List tokens) {
- List sections = sectionize(indexTokens(tokens));
- StringBuilder result = new StringBuilder();
-
- for (Section section : sections) {
- if (section.isCodeSection()) {
- result.append("```java\n")
- .append(writeCodeSection(section.tokens()))
- .append("\n```");
- } else {
- result.append(joinTokens(section.tokens()));
- }
- }
-
- return result.toString();
- }
-
- /**
- * Formats the given string using a given lexer
- *
- * @param input input to format
- * @param lexer lexer to use
- * @return resulting code
- */
- public String format(String input, Lexer lexer) {
- return format(lexer.tokenize(input));
- }
-
- /**
- * Joins given tokens together and normalizes whitespaces
- *
- * @param tokens tokens to join
- * @return joined form of the tokens
- */
- private String joinTokens(List tokens) {
- return tokens.stream().map(Token::content).collect(Collectors.joining());
- }
-
- /**
- * Writes and formats a given code section (in form of a list of tokens) into a StringBuilder
- * using a {@link CodeSectionFormatter}
- *
- * @param tokens tokens to write
- * @return written code sections
- */
- private StringBuilder writeCodeSection(List tokens) {
- CodeSectionFormatter formatter = new CodeSectionFormatter(tokens);
-
- formatter.format();
-
- return formatter.result();
- }
+public final class Formatter {
+ private final Lexer lexer = new Lexer();
/**
- * Indexes tokens to contain information about whether they are code tokens or not
+ * Formats the given string.
+ *
+ * Best results are achieved for Java code.
*
- * @param tokens not-indexed tokens
- * @return indexed tokens
+ * @param code the code to format
+ * @return the formatted code
*/
- private List indexTokens(List tokens) {
- return tokens.stream()
- .map(token -> new CheckedToken(token, isTokenPartOfCode(token)))
- .toList();
- }
+ public String format(CharSequence code) {
+ List tokens = lexer.tokenize(code);
+ CodeSectionFormatter codeFormatter = new CodeSectionFormatter(tokens);
- /**
- * Checks if a given token could be part of code
- *
- * @param token token to check
- * @return true if it's a code token, false if not
- */
- private boolean isTokenPartOfCode(Token token) {
- return token.type() != TokenType.UNKNOWN;
- }
-
- /**
- * Sectionizes a given list of tokens into sections who are either code sections or non-code
- * sections. It decides so by using the internal {@code isTokenPartOfCode} method.
- *
- * @param checkedTokens checked tokens
- * @return list of sections
- */
- private List sectionize(List checkedTokens) {
- CheckedToken first = checkedTokens.get(0);
- Section currentSection = new Section(new ArrayList<>(), first.isCode());
- List result = new ArrayList<>();
-
- currentSection.tokens().add(first.token());
-
- for (int i = 1; i < checkedTokens.size(); i++) {
- CheckedToken next = checkedTokens.get(i);
-
- if (currentSection.isCodeSection() != next.isCode()) {
- result.add(currentSection);
-
- currentSection = new Section(new ArrayList<>(), next.isCode());
- }
-
- currentSection.tokens().add(next.token());
- }
-
- result.add(currentSection);
-
- return result;
- }
-
- /**
- * Section POJR
- */
- private static record Section(List tokens, boolean isCodeSection) {
- }
-
- /**
- * CheckedToken POJR
- */
- private static record CheckedToken(Token token, boolean isCode) {
+ return codeFormatter.format();
}
}
diff --git a/formatter/src/main/java/org/togetherjava/tjbot/formatter/formatting/CodeSectionFormatter.java b/formatter/src/main/java/org/togetherjava/tjbot/formatter/formatting/CodeSectionFormatter.java
new file mode 100644
index 0000000000..ebc9eaf834
--- /dev/null
+++ b/formatter/src/main/java/org/togetherjava/tjbot/formatter/formatting/CodeSectionFormatter.java
@@ -0,0 +1,252 @@
+package org.togetherjava.tjbot.formatter.formatting;
+
+import org.togetherjava.tjbot.formatter.tokenizer.Token;
+import org.togetherjava.tjbot.formatter.tokenizer.TokenType;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Pretty-formats a given list of code tokens.
+ *
+ * After creation, use {@link #format()}. This is a one-time method.
+ */
+// Sonar complains about commented out code on multiple methods.
+// A false-positive, this is intentional explanation.
+@SuppressWarnings("squid:S125")
+public final class CodeSectionFormatter {
+ private static final String INDENT = " ".repeat(2);
+
+ private final TokenQueue tokens;
+ /**
+ * The actual set of rules to apply. For example, it decides when to put a space around a token.
+ */
+ private final FormatterRules rules;
+ private final StringBuilder result;
+
+ /**
+ * The current level of indentation, which is applied at the start of each new line.
+ */
+ private int currentIndentLevel;
+ /**
+ * The current level of generic nesting. For example {@code List>} has a level of 2 at
+ * token {@code Foo}.
+ */
+ private int currentGenericLevel;
+ /**
+ * Whether the current token is at the start of a new line.
+ */
+ private boolean isStartOfLine;
+ /**
+ * Whether the current line is expected to have multiple semicolons before a line-break is
+ * applied. For example in indexed for-loops {@code for (A(); B(); C())}.
+ */
+ private int expectedSemicolonsInLine;
+ private boolean isInPackageDeclaration;
+ private boolean isInImportDeclaration;
+
+ private boolean alreadyUsed;
+
+ private static List patchTokens(List tokens) {
+ // We rebuild the whitespaces ourselves and ignore existing
+ List patchedTokens = new ArrayList<>(tokens);
+ patchedTokens.removeIf(token -> token.type() == TokenType.WHITESPACE);
+
+ return patchedTokens;
+ }
+
+ /**
+ * Creates an instance for formatting the given tokens.
+ *
+ * The formatter is not backed by the list.
+ *
+ * @param tokens to format
+ */
+ public CodeSectionFormatter(List tokens) {
+ this.tokens = new TokenQueue(patchTokens(tokens));
+ result = new StringBuilder(this.tokens.remainingSize());
+ rules = new FormatterRules(this.tokens);
+ }
+
+ /**
+ * Pretty-formats the code tokens of this formatter.
+ *
+ * This method must only be used once per instance.
+ *
+ * @return the formatted code
+ */
+ public String format() {
+ if (alreadyUsed) {
+ throw new IllegalStateException(
+ "This method must only be used once, create a new instance instead.");
+ }
+
+ while (!tokens.isEmpty()) {
+ Token token = tokens.consume();
+ process(token);
+ }
+
+ String resultText = result.toString();
+
+ // Clear the builder to prevent memory leaks
+ result.setLength(0);
+ alreadyUsed = true;
+
+ return resultText;
+ }
+
+ private void process(Token token) {
+ preProcess(token.type());
+ putToken(token);
+ postProcess(token.type());
+ }
+
+ private void preProcess(TokenType tokenType) {
+ handleIndents(tokenType);
+ preHandleGenericLevel(tokenType);
+ handleSpacePrefix(tokenType);
+ }
+
+ private void handleIndents(TokenType tokenType) {
+ if (tokenType == TokenType.OPEN_BRACES) {
+ currentIndentLevel++;
+ } else if (tokenType == TokenType.CLOSE_BRACES) {
+ currentIndentLevel--;
+ }
+
+ if (isStartOfLine) {
+ result.append(createIndent());
+ isStartOfLine = false;
+ }
+ }
+
+ private String createIndent() {
+ return INDENT.repeat(Math.max(0, currentIndentLevel));
+ }
+
+ private void preHandleGenericLevel(TokenType tokenType) {
+ // Already inside generics
+ if (currentGenericLevel > 0) {
+ // List>
+ if (tokenType == TokenType.LESS_THAN) {
+ currentGenericLevel++;
+ }
+
+ return;
+ }
+
+ // Start of generic
+ if (rules.isStartOfGeneric(tokenType)) {
+ currentGenericLevel = 1;
+ }
+ }
+
+ private void handleSpacePrefix(TokenType tokenType) {
+ if (currentGenericLevel > 0) {
+ if (rules.shouldPutSpaceBeforeGeneric(tokenType)) {
+ result.append(' ');
+ }
+ return;
+ }
+
+ if (rules.shouldPutSpaceBefore(tokenType)) {
+ result.append(' ');
+ }
+ }
+
+ private void putToken(Token token) {
+ String content = token.content();
+
+ if (token.type() == TokenType.MULTI_LINE_COMMENT) {
+ content = FormatterRules.patchMultiLineComment(content, createIndent());
+ }
+
+ result.append(content);
+ }
+
+ private void postProcess(TokenType tokenType) {
+ if (tokens.isEmpty()) {
+ // Last character needs no post-processing
+ return;
+ }
+
+ handleSpaceSuffix(tokenType);
+ handleNewLineSuffix(tokenType);
+ handleExpectedSemicolonsInLine(tokenType);
+ postHandleGenericLevel(tokenType);
+ handlePackageDeclaration(tokenType);
+ handleImportDeclaration(tokenType);
+ }
+
+ private void handleSpaceSuffix(TokenType tokenType) {
+ if (currentGenericLevel > 0) {
+ if (rules.shouldPutSpaceAfterGeneric(tokenType, currentGenericLevel)) {
+ result.append(' ');
+ }
+ return;
+ }
+
+ if (rules.shouldPutSpaceAfter(tokenType, expectedSemicolonsInLine)) {
+ result.append(' ');
+ }
+ }
+
+ private void handleNewLineSuffix(TokenType tokenType) {
+ if (rules.shouldPutNewlineAfter(tokenType, expectedSemicolonsInLine)) {
+ result.append('\n');
+ isStartOfLine = true;
+ }
+ }
+
+ private void handleExpectedSemicolonsInLine(TokenType tokenType) {
+ if (expectedSemicolonsInLine > 0 && tokenType == TokenType.SEMICOLON) {
+ expectedSemicolonsInLine--;
+ } else if (rules.isStartOfIndexedForLoop(tokenType)) {
+ expectedSemicolonsInLine = 2;
+ }
+ }
+
+ private void postHandleGenericLevel(TokenType tokenType) {
+ if (currentGenericLevel > 0 && tokenType == TokenType.GREATER_THAN) {
+ currentGenericLevel--;
+ }
+ }
+
+ private void handlePackageDeclaration(TokenType tokenType) {
+ if (tokenType == TokenType.PACKAGE) {
+ isInPackageDeclaration = true;
+ return;
+ }
+
+ if (!isInPackageDeclaration) {
+ return;
+ }
+
+ // package foo.bar.Baz;
+ if (tokenType == TokenType.SEMICOLON) {
+ // End of package needs an extra empty line
+ isInPackageDeclaration = false;
+ result.append('\n');
+ }
+ }
+
+ private void handleImportDeclaration(TokenType tokenType) {
+ if (tokenType == TokenType.IMPORT) {
+ isInImportDeclaration = true;
+ return;
+ }
+
+ if (!isInImportDeclaration) {
+ return;
+ }
+
+ // import foo.bar.Baz;
+ if (tokenType == TokenType.SEMICOLON) {
+ isInImportDeclaration = false;
+ if (rules.isEndOfLastImportDeclaration()) {
+ // End of last import needs an extra empty line
+ result.append('\n');
+ }
+ }
+ }
+}
diff --git a/formatter/src/main/java/org/togetherjava/tjbot/formatter/formatting/FormatterRules.java b/formatter/src/main/java/org/togetherjava/tjbot/formatter/formatting/FormatterRules.java
new file mode 100644
index 0000000000..3f6b31b422
--- /dev/null
+++ b/formatter/src/main/java/org/togetherjava/tjbot/formatter/formatting/FormatterRules.java
@@ -0,0 +1,242 @@
+package org.togetherjava.tjbot.formatter.formatting;
+
+import org.togetherjava.tjbot.formatter.tokenizer.TokenType;
+
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
+
+/**
+ * Rules used by {@link CodeSectionFormatter} to format code.
+ */
+// Sonar complains about commented out code on multiple methods.
+// A false-positive, this is intentional explanation.
+@SuppressWarnings("squid:S125")
+final class FormatterRules {
+ private final TokenQueue tokens;
+
+ /**
+ * Creates a set of rules for the given tokens.
+ *
+ * @param tokens to format with rules of this instance, read-only
+ */
+ FormatterRules(TokenQueue tokens) {
+ this.tokens = tokens;
+ }
+
+ private static boolean matchesAnyRule(TokenType tokenType,
+ Collection extends Predicate> rules) {
+ return rules.stream().anyMatch(rule -> rule.test(tokenType));
+ }
+
+ boolean shouldPutSpaceBeforeGeneric(TokenType tokenType) {
+ return Set.of(TokenType.EXTENDS, TokenType.SUPER).contains(tokenType);
+ }
+
+ boolean shouldPutSpaceBefore(TokenType tokenType) {
+ // 5 + 3
+ List> rules = List.of(
+ // 5 + 3, but not inside x >> 1
+ type -> type.getAttribute() == TokenType.Attribute.BINARY_OPERATOR
+ && isRightShiftStartOrNone(tokenType),
+ TokenType.IMPLEMENTS::equals, TokenType.EXTENDS::equals);
+ return matchesAnyRule(tokenType, rules);
+ }
+
+ private boolean isRightShiftStartOrNone(TokenType tokenType) {
+ if (tokenType != TokenType.GREATER_THAN) {
+ return true;
+ }
+
+ // The start of a >> has no > to the left
+ return tokens.peekTypeBackStream()
+ .skip(1)
+ .limit(1)
+ .findFirst()
+ .orElseThrow() != TokenType.GREATER_THAN;
+ }
+
+ boolean shouldPutSpaceAfterGeneric(TokenType tokenType, int currentGenericLevel) {
+ if (currentGenericLevel <= 0) {
+ return false;
+ }
+
+ if (currentGenericLevel == 1 && tokenType == TokenType.GREATER_THAN) {
+ // End of generics
+ // With space: List values
+ // No space: new ArrayList<>()
+ return tokens.peekType() != TokenType.OPEN_PARENTHESIS;
+ }
+
+ return Set.of(TokenType.COMMA, // Map
+ TokenType.QUESTION_MARK, // List super Foo>
+ TokenType.EXTENDS, // List extends Foo>
+ TokenType.SUPER) // List super Foo>
+ .contains(tokenType);
+ }
+
+ boolean shouldPutSpaceAfter(TokenType tokenType, int expectedSemicolonsInLine) {
+ List> rules = List.of(
+ type -> type.getAttribute() == TokenType.Attribute.KEYWORD, // class Foo
+ // 5 + 3, but not inside x >> 1
+ type -> type.getAttribute() == TokenType.Attribute.BINARY_OPERATOR
+ && isRightShiftEndOrNone(tokenType),
+ this::shouldPutSpaceAfterClosingParenthesis, // foo() {
+ TokenType.CLOSE_BRACKETS::equals, // foo[i] = 3
+ TokenType.COMMA::equals, // foo(x, y)
+ // String toString()
+ type -> type == TokenType.IDENTIFIER && tokens.peekType() == TokenType.IDENTIFIER,
+ // class Foo {
+ type -> type == TokenType.IDENTIFIER && tokens.peekType() == TokenType.OPEN_BRACES,
+ // for (a(); b(); c())
+ type -> type == TokenType.SEMICOLON && expectedSemicolonsInLine > 0,
+ // } catch, } finally
+ type -> type == TokenType.CLOSE_BRACES
+ && Set.of(TokenType.CATCH, TokenType.FINALLY).contains(tokens.peekType()));
+
+ return matchesAnyRule(tokenType, rules);
+ }
+
+ private boolean isRightShiftEndOrNone(TokenType tokenType) {
+ if (tokenType != TokenType.GREATER_THAN) {
+ return true;
+ }
+
+ // The end of a >> has no > to the right
+ return tokens.peekType() != TokenType.GREATER_THAN;
+ }
+
+ private boolean shouldPutSpaceAfterClosingParenthesis(TokenType tokenType) {
+ if (tokenType != TokenType.CLOSE_PARENTHESIS) {
+ return false;
+ }
+
+ TokenType nextType = tokens.peekType();
+ if (nextType == TokenType.CLOSE_PARENTHESIS) {
+ return false; // foo(bar())
+ }
+ if (nextType == TokenType.SEMICOLON) {
+ return false; // foo();
+ }
+ if (nextType == TokenType.COMMA) {
+ return false; // foo(a, bar(), c);
+ }
+ if (nextType.getAttribute() == TokenType.Attribute.BINARY_OPERATOR) {
+ // The space is added before the operator already
+ return false; // foo() + 3
+ }
+ // foo { and not foo().bar()
+ return nextType != TokenType.DOT;
+ }
+
+ boolean shouldPutNewlineAfter(TokenType tokenType, int expectedSemicolonsInLine) {
+ List> rules = List.of(TokenType.OPEN_BRACES::equals, // foo() {
+ TokenType.SINGLE_LINE_COMMENT::equals, // // Foo
+ TokenType.MULTI_LINE_COMMENT::equals, // /* Foo */
+ // @Foo but not @Foo(bar)
+ type -> type == TokenType.ANNOTATION
+ && tokens.peekType() != TokenType.OPEN_PARENTHESIS,
+ // } but not };
+ type -> type == TokenType.CLOSE_BRACES && tokens.peekType() != TokenType.SEMICOLON
+ && tokens.peekType() != TokenType.CATCH
+ && tokens.peekType() != TokenType.FINALLY,
+ // int x = 5; but not for (;;), } catch, } finally
+ type -> type == TokenType.SEMICOLON && expectedSemicolonsInLine == 0);
+
+ return matchesAnyRule(tokenType, rules);
+ }
+
+ boolean isStartOfGeneric(TokenType tokenType) {
+ if (tokenType != TokenType.LESS_THAN) {
+ return false;
+ }
+
+ Set typesAllowedInGenerics = Set.of(TokenType.LESS_THAN, TokenType.GREATER_THAN,
+ TokenType.QUESTION_MARK, TokenType.EXTENDS, TokenType.SUPER, TokenType.COMMA,
+ TokenType.DOT, TokenType.IDENTIFIER);
+ int genericLevel = 1;
+
+ // Search the matching closing > as challenge to reduce the level back to 0
+ // All encountered types must be allowed inside generics
+ Iterator previewIter = tokens.peekTypeStream().iterator();
+ while (previewIter.hasNext()) {
+ TokenType previewTokenType = previewIter.next();
+
+ // Parenthesis not allowed in 5 < Foo.<>foo()
+ if (!typesAllowedInGenerics.contains(previewTokenType)) {
+ break;
+ }
+
+ if (previewTokenType == TokenType.LESS_THAN) {
+ genericLevel++;
+ } else if (previewTokenType == TokenType.GREATER_THAN) {
+ genericLevel--;
+ }
+
+ if (genericLevel <= 0) {
+ // Managed to reduce the level back to 0 without
+ // visiting a forbidden type
+ return true;
+ }
+ }
+
+ // End of code or encountered bad type
+ return false;
+ }
+
+ boolean isStartOfIndexedForLoop(TokenType tokenType) {
+ if (tokenType != TokenType.FOR) {
+ return false;
+ }
+
+ // Either indexed or enhanced for loop
+ // Check the next significant tokens, none must be a colon
+ // for (int x : values)
+ // 1 -> (
+ // 2 -> int
+ // 3 -> x
+ // 4 -> :
+ Set ignoreTypes =
+ Set.of(TokenType.ANNOTATION, TokenType.FINAL, TokenType.MULTI_LINE_COMMENT,
+ TokenType.SINGLE_LINE_COMMENT, TokenType.WHITESPACE, TokenType.DOT);
+ return tokens.peekTypeStream()
+ .filter(Predicate.not(ignoreTypes::contains))
+ .limit(6)
+ .noneMatch(TokenType.COLON::equals);
+ }
+
+ boolean isEndOfLastImportDeclaration() {
+ // After the last import statement, no further import follows
+ Set ignoreTypes = Set.of(TokenType.MULTI_LINE_COMMENT,
+ TokenType.SINGLE_LINE_COMMENT, TokenType.WHITESPACE);
+ return tokens.peekTypeStream()
+ .filter(Predicate.not(ignoreTypes::contains))
+ .limit(1)
+ .noneMatch(TokenType.IMPORT::equals);
+ }
+
+ static String patchMultiLineComment(String content, String indent) {
+ List lines = content.lines().toList();
+ if (lines.size() <= 1) {
+ // Nothing to patch for one-line multi-line comments, such as /* foo */
+ return content;
+ }
+
+ // All other lines need indent, and an extra space
+ /*
+ * Example multi-line comment
+ */
+ String firstLine = lines.get(0);
+ List otherLines = lines.subList(1, lines.size());
+
+ String otherLinesText = otherLines.stream()
+ .map(String::strip)
+ .map(otherLine -> indent + " " + otherLine)
+ .collect(Collectors.joining("\n"));
+
+ return firstLine + "\n" + otherLinesText;
+ }
+}
diff --git a/formatter/src/main/java/org/togetherjava/tjbot/formatter/formatting/TokenQueue.java b/formatter/src/main/java/org/togetherjava/tjbot/formatter/formatting/TokenQueue.java
new file mode 100644
index 0000000000..5d21f43e4e
--- /dev/null
+++ b/formatter/src/main/java/org/togetherjava/tjbot/formatter/formatting/TokenQueue.java
@@ -0,0 +1,141 @@
+package org.togetherjava.tjbot.formatter.formatting;
+
+import org.togetherjava.tjbot.formatter.tokenizer.Token;
+import org.togetherjava.tjbot.formatter.tokenizer.TokenType;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+/**
+ * Queue that holds {@link Token}s to be consumed. Generally, this holds the result of lexing code
+ * (see {@link org.togetherjava.tjbot.formatter.tokenizer.Lexer}), then processed by the actual
+ * formatter (see {@link CodeSectionFormatter}).
+ *
+ * The core methods are {@link #consume()} and {@link #isEmpty()}. Further, the queue allows peeking
+ * in both directions.
+ *
+ * The queue does not release tokens upon consumption. To prevent memory leaks, the queue should not
+ * be kept alive longer than necessary.
+ *
+ * The class is not thread-safe.
+ */
+final class TokenQueue {
+ private final List tokens;
+ private int nextTokenIndex;
+
+ /**
+ * Creates a new queue that consumes the given tokens. Consumption starts at the beginning of
+ * the given collection.
+ *
+ * The queue is not backed by the collection.
+ *
+ * @param tokens to consume by the queue
+ */
+ TokenQueue(Collection tokens) {
+ this.tokens = new ArrayList<>(tokens);
+ }
+
+ /**
+ * Whether there are still tokens to be consumed.
+ *
+ * @return Whether there are still tokens to be consumed
+ */
+ boolean isEmpty() {
+ return nextTokenIndex >= tokens.size();
+ }
+
+ /**
+ * The remaining amount of tokens that can still be consumed, i.e. how often {@link #consume()}
+ * can still be called.
+ *
+ * @return the remaining amount of tokens
+ */
+ int remainingSize() {
+ return tokens.size() - nextTokenIndex;
+ }
+
+ /**
+ * Consumes the next token. Must only be invoked if {@link #isEmpty()} returns {@code false}.
+ *
+ * @return the consumed token
+ * @throws NoSuchElementException if the queue is empty
+ */
+ Token consume() {
+ if (isEmpty()) {
+ throw new NoSuchElementException("The queue is empty, can not consume another token");
+ }
+ Token token = tokens.get(nextTokenIndex);
+ nextTokenIndex++;
+ return token;
+ }
+
+ /**
+ * Peeks at type of the next token, without consuming it. Must only be used if
+ * {@link #isEmpty()} returns {@code false}.
+ *
+ * That is the type of the token, which would be returned by using {@link #consume()}.
+ *
+ * @return the next tokens type
+ * @throws NoSuchElementException if the queue is empty
+ */
+ TokenType peekType() {
+ if (isEmpty()) {
+ throw new NoSuchElementException("The queue is empty, can not peek another token");
+ }
+ return tokens.get(nextTokenIndex).type();
+ }
+
+ /**
+ * Peeks at the type of the previous token, without changing the queue. Must only be used after
+ * {@link #consume()} ()} has been used at least once.
+ *
+ * That is the type of the token, which has been returned by the previous usage of
+ * {@link #consume()}.
+ *
+ * @return the previous tokens type
+ * @throws NoSuchElementException if no token was consumed yet
+ */
+ TokenType peekTypeBack() {
+ if (nextTokenIndex == 0) {
+ throw new NoSuchElementException("No token has been consumed yet, can not peek back");
+ }
+ return tokens.get(nextTokenIndex - 1).type();
+ }
+
+ /**
+ * Peeks at the type of the next tokens, without consuming them.
+ *
+ * This essentially gives a stream for all remaining tokens in the queue.
+ *
+ * @return the next tokens types, an empty stream if the queue is empty
+ */
+ Stream peekTypeStream() {
+ if (isEmpty()) {
+ return Stream.of();
+ }
+ return tokens.subList(nextTokenIndex, tokens.size()).stream().map(Token::type);
+ }
+
+ /**
+ * Peeks at the type of the previous tokens, without changing the queue.
+ *
+ * This essentially gives a stream for all already consumed tokens in the queue. The stream is
+ * ordered from the most recently consumed token to the first consumed token.
+ *
+ * @return the previous tokens types, an empty stream if no token has been consumed yet
+ */
+ Stream peekTypeBackStream() {
+ if (nextTokenIndex == 0) {
+ return Stream.of();
+ }
+
+ return IntStream.range(0, nextTokenIndex)
+ .map(i -> nextTokenIndex - i - 1)
+ .mapToObj(tokens::get)
+ .map(Token::type);
+ }
+}
diff --git a/formatter/src/main/java/org/togetherjava/tjbot/formatter/formatting/package-info.java b/formatter/src/main/java/org/togetherjava/tjbot/formatter/formatting/package-info.java
new file mode 100644
index 0000000000..091cfbbadb
--- /dev/null
+++ b/formatter/src/main/java/org/togetherjava/tjbot/formatter/formatting/package-info.java
@@ -0,0 +1,11 @@
+/**
+ * Deals with formatting code snippets. See
+ * {@link org.togetherjava.tjbot.formatter.formatting.CodeSectionFormatter} as entry point.
+ */
+@MethodsReturnNonnullByDefault
+@ParametersAreNonnullByDefault
+package org.togetherjava.tjbot.formatter.formatting;
+
+import org.togetherjava.tjbot.annotations.MethodsReturnNonnullByDefault;
+
+import javax.annotation.ParametersAreNonnullByDefault;
diff --git a/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/Lexer.java b/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/Lexer.java
index 9838f1dc29..117cf3da7d 100644
--- a/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/Lexer.java
+++ b/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/Lexer.java
@@ -1,90 +1,49 @@
package org.togetherjava.tjbot.formatter.tokenizer;
+import java.nio.CharBuffer;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.List;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
+import java.util.Optional;
+import java.util.stream.Stream;
/**
- * Tokenizer that can turn a list of strings (or a string) into a list of tokens
+ * Tokenizer that turns code into a list of tokens.
*/
-public class Lexer {
+public final class Lexer {
/**
- * Regex to match multi-line Java comments (including Javadoc)
- */
- private static final Pattern commentPatcherRegex =
- Pattern.compile("(/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*/)");
-
- /**
- * Tokenizes the given input by tokenizing each line individually (splitting by \n)
+ * Tokenizes the given code into its individual tokens.
*
- * @param input input to tokenize
- * @return resulting tokens
+ * @param code code to tokenize
+ * @return the tokens the code consists of
*/
- public List tokenize(String input) {
- return tokenize(Arrays.asList(patchComments(input).split("\n")));
- }
-
- /**
- * Tokenizes the given input line by line
- *
- * @param lines input to tokenize
- * @return resulting tokens
- */
- public List tokenize(List lines) {
- return lines.stream().map(this::tokenizeLine).flatMap(List::stream).toList();
- }
+ public List tokenize(CharSequence code) {
+ if (code.isEmpty()) {
+ return List.of();
+ }
- /**
- * Tokenizes a single line using regex
- *
- * @param line input to tokenize
- * @return resulting tokens
- */
- private List tokenizeLine(String line) {
List tokens = new ArrayList<>();
- int index = 0;
- String content;
-
- while (!(content = line.substring(index)).isEmpty()) {
- Token token = findToken(content);
-
- index += token.content().length();
+ CharBuffer remainingCode = CharBuffer.wrap(code);
+ while (!remainingCode.isEmpty()) {
+ Token token = nextToken(remainingCode);
tokens.add(token);
+
+ advancePosition(remainingCode, token.content().length());
}
return tokens;
}
- private Token findToken(String content) {
- for (TokenType type : TokenType.values()) {
- Matcher matcher = type.getRegex().matcher(content);
-
- if (matcher.find()) {
- return new Token(matcher.group(1), type);
- }
- }
-
- throw new TokenizationException("Token not found for '" + content + "'");
+ private Token nextToken(CharSequence content) {
+ // Try all token types in order, take the first match
+ return Stream.of(TokenType.getAllInMatchOrder())
+ .map(tokenType -> tokenType.matches(content))
+ .flatMap(Optional::stream)
+ .findFirst()
+ .orElseThrow();
}
- /**
- * Replaces multi-line comments in a given string by single-line comments
- *
- * @param input input to patch
- * @return resulting string
- */
- private String patchComments(String input) { // fix this, you shouldn't need this!
- Matcher matcher = commentPatcherRegex.matcher(input);
-
- while (matcher.find()) {
- String s = matcher.group();
-
- input = input.replace(s, s.replace("\n", " "));
- }
-
- return input;
+ private static void advancePosition(CharBuffer charBuffer, int advanceBy) {
+ charBuffer.position(charBuffer.position() + advanceBy);
}
}
diff --git a/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/Matching.java b/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/Matching.java
new file mode 100644
index 0000000000..b6eaa87983
--- /dev/null
+++ b/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/Matching.java
@@ -0,0 +1,122 @@
+package org.togetherjava.tjbot.formatter.tokenizer;
+
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Utilities to match tokens.
+ */
+final class Matching {
+ private static final String CONTENT_GROUP = "content";
+
+ private Matching() {
+ throw new UnsupportedOperationException("Utility class, no implementation");
+ }
+
+ /**
+ * Checks whether the given text starts with a string matching the pattern.
+ *
+ * For example {@code matchesPattern(Pattern.compile("\\d+"), "12 foo")} would match and return
+ * {@code "12"}.
+ *
+ * @param pattern the pattern to match with
+ * @param text the text to match against
+ * @return the text matched by the pattern, if any
+ */
+ static Optional matchesPattern(Pattern pattern, CharSequence text) {
+ Matcher matcher = patchPattern(pattern).matcher(text);
+ if (!matcher.find()) {
+ return Optional.empty();
+ }
+
+ String content = matcher.group(CONTENT_GROUP);
+ return Optional.of(content);
+ }
+
+ private static Pattern patchPattern(Pattern pattern) {
+ // ^ to prevent matching somewhere in the middle of the given text, e.g.,
+ // "int x" should match for "int", not for "x".
+ // Patterns need the named group to retrieve the content
+ String patternText = "^(?<%s>%s)".formatted(CONTENT_GROUP, pattern.pattern());
+
+ return Pattern.compile(patternText, pattern.flags());
+ }
+
+ /**
+ * Checks whether the given text starts with the given symbol. Depending on the attribute, more
+ * rules might apply.
+ *
+ * For example {@code matchesSymbol("int", "int x = 5", KEYWORD)} would match and return
+ * {@code "int"}.
+ *
+ * @param symbol the symbol to match with
+ * @param text the text to match against
+ * @param attribute the attribute of the symbol to match, for example {@code "class"} would be a
+ * {@link TokenType.Attribute#KEYWORD}
+ * @return the given symbol, if it matches
+ */
+ static Optional matchesSymbol(String symbol, CharSequence text,
+ TokenType.Attribute attribute) {
+ if (!startsWith(text, symbol)) {
+ return Optional.empty();
+ }
+
+ if (attribute == TokenType.Attribute.KEYWORD && text.length() > symbol.length()) {
+ // Must not be followed by letter
+ char nextChar = text.charAt(symbol.length());
+ if (Character.isLetter(nextChar)) {
+ return Optional.empty();
+ }
+ }
+
+ return Optional.of(symbol);
+ }
+
+ private static boolean startsWith(CharSequence text, String other) {
+ // CharSequence unfortunately has no startsWith method, so we roll our own
+ if (other.length() > text.length()) {
+ return false;
+ }
+
+ // subSequence is only efficient on view-implementations, such as CharBuffer or Segment
+ CharSequence candidate = text.subSequence(0, other.length());
+ return other.contentEquals(candidate);
+ }
+
+ /**
+ * Checks whether the given text starts with string, i.e. text contained in quotes
+ * {@code "foo"}. Correctly handles escaped quotes, such as {@code "foo \"bar\" baz"}.
+ *
+ * For example {@code matchesString("\"foo\"; int x = 5;")} would match and return
+ * {@code "\"foo\""}.
+ *
+ * @param text the text to match against
+ * @return the matched string, including starting and ending quotes, if any
+ */
+ static Optional matchesString(CharSequence text) {
+ if (text.length() < 2) {
+ return Optional.empty();
+ }
+ if (text.charAt(0) != '"') {
+ return Optional.empty();
+ }
+
+ for (int i = 1; i < text.length(); i++) {
+ char c = text.charAt(i);
+
+ // Strings end on unescaped ", i.e. not \"
+ if (c == '"') {
+ char previous = text.charAt(i - 1);
+ if (previous != '\\') {
+ // Found the end of the string
+ String match = text.subSequence(0, i + 1).toString();
+ return Optional.of(match);
+ }
+ }
+ }
+
+ // String never ended
+ return Optional.empty();
+ }
+}
diff --git a/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/Token.java b/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/Token.java
index c43d2e80a6..e6e5569cde 100644
--- a/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/Token.java
+++ b/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/Token.java
@@ -1,29 +1,23 @@
package org.togetherjava.tjbot.formatter.tokenizer;
-import java.util.Set;
-
/**
- * Class representing a Token with a given content and a type
+ * Single token of a code, for example an opening-brace.
+ *
+ * As example, the code {@code int x = "foo";} is split into tokens:
+ *
+ * ("int", INT)
+ * ("x", IDENTIFIER)
+ * ("=", ASSIGN)
+ * ("\"foo\"", STRING)
+ * (";", SEMICOLON)
+ *
+ *
+ * @param content the actual text contained in the token, e.g., an identifier like {@code x}
+ * @param type the type of the token, e.g., IDENTIFIER
*/
public record Token(String content, TokenType type) {
- private static final Set displayTypes =
- Set.of(TokenType.IDENTIFIER, TokenType.UNKNOWN, TokenType.STRING, TokenType.COMMENT);
-
@Override
public String toString() {
- return type().name() + formatForDisplay();
- }
-
- /**
- * Returns a non-empty string if this token has something to display
- *
- * @return the displayed value
- */
- private String formatForDisplay() {
- if (displayTypes.contains(type())) {
- return "(" + content() + ")";
- }
-
- return "";
+ return "%s(%s)".formatted(type.name(), content);
}
}
diff --git a/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/TokenType.java b/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/TokenType.java
index 5aebce63c1..a72acc54fd 100644
--- a/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/TokenType.java
+++ b/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/TokenType.java
@@ -1,137 +1,273 @@
package org.togetherjava.tjbot.formatter.tokenizer;
+import java.nio.CharBuffer;
+import java.util.Optional;
+import java.util.function.Function;
import java.util.regex.Pattern;
/**
- * Represents every possible token that can be parsed by the lexer
+ * All types of tokens recognized by {@link Lexer}.
+ *
+ * Token types can be used to find the next matching token (see {@link #matches(CharSequence)}). For
+ * example, for the code {@code int x = "foo"}, only {@link #INT} would match. Other participating
+ * tokens, such as {@link #IDENTIFIER} or {@link #STRING} do not match yet.
*/
+// Sonar wants Javadoc on all tokens, but they are self-explanatory based
+// on the enum description and context.
+@SuppressWarnings("squid:S1176")
public enum TokenType {
- // keywords
- CLASS("class", true, false),
- ENUM("enum", true, false),
- RECORD("record", true, false),
- INTERFACE("interface", true, false),
- IMPORT("import", true, false),
- IF("if", true, false),
- FOR("for", true, false),
- WHILE("while", true, false),
- NULL("null", true, false),
- EXTENDS("extends", true, false),
- IMPLEMENTS("implements", true, false),
- NEW("new", true, false),
- RETURN("return", true, false),
- PACKAGE("package", true, false),
- THIS("this", true, false),
- YIELD("yield", true, false),
- CATCH("catch", true, false),
- TRY("try", true, false),
- ELSE_IF("else if", true, false), // not really a keyword but required for formatting
- ELSE("else", true, false),
- SUPER("super", true, false),
- // access modifiers
- PUBLIC("public", true, false),
- PRIVATE("private", true, false),
- PROTECTED("protected", true, false),
- STATIC("static", true, false),
- SEALED("sealed", true, false),
- NON_SEALED("non-sealed", true, false),
- FINAL("final", true, false),
- ABSTRACT("abstract", true, false),
- // primitive types
- VOID("void", true, false),
- INT("int", true, false),
- LONG("long", true, false),
- SHORT("short", true, false),
- BYTE("byte", true, false),
- BOOLEAN("boolean", true, false),
- FLOAT("float", true, false),
- DOUBLE("double", true, false),
- CHAR("char", true, false),
- // general tokens
+ // NOTE The entries have an order-dependency by design.
+ // Their patterns are applied from top to bottom. So entries that are not prefix-free
+ // like "--" and "-" must be ordered with "--" before "-" to correctly match.
+
+ // Keywords
+ CLASS("class", Attribute.KEYWORD),
+ ENUM("enum", Attribute.KEYWORD),
+ RECORD("record", Attribute.KEYWORD),
+ INTERFACE("interface", Attribute.KEYWORD),
+ IMPORT("import", Attribute.KEYWORD),
+ NULL("null", Attribute.KEYWORD),
+ EXTENDS("extends", Attribute.KEYWORD),
+ IMPLEMENTS("implements", Attribute.KEYWORD),
+ NEW("new", Attribute.KEYWORD),
+ RETURN("return", Attribute.KEYWORD),
+ PACKAGE("package", Attribute.KEYWORD),
+ THIS("this", Attribute.KEYWORD),
+ YIELD("yield", Attribute.KEYWORD),
+ SUPER("super", Attribute.KEYWORD),
+ ASSERT("assert", Attribute.KEYWORD),
+ CONST("const", Attribute.KEYWORD),
+ DEFAULT("default", Attribute.KEYWORD),
+ FINALLY("finally", Attribute.KEYWORD),
+ THROWS("throws", Attribute.KEYWORD),
+ THROW("throw", Attribute.KEYWORD),
+
+ // Access modifiers
+ PUBLIC("public", Attribute.KEYWORD),
+ PRIVATE("private", Attribute.KEYWORD),
+ PROTECTED("protected", Attribute.KEYWORD),
+ STATIC("static", Attribute.KEYWORD),
+ SEALED("sealed", Attribute.KEYWORD),
+ NON_SEALED("non-sealed", Attribute.KEYWORD),
+ FINAL("final", Attribute.KEYWORD),
+ ABSTRACT("abstract", Attribute.KEYWORD),
+ NATIVE("native", Attribute.KEYWORD),
+ STRICTFP("strictfp", Attribute.KEYWORD),
+ SYNCHRONIZED("synchronized", Attribute.KEYWORD),
+ TRANSIENT("transient", Attribute.KEYWORD),
+ VOLATILE("volatile", Attribute.KEYWORD),
+
+ // Primitives
+ VOID("void", Attribute.KEYWORD),
+ INT("int", Attribute.KEYWORD),
+ LONG("long", Attribute.KEYWORD),
+ SHORT("short", Attribute.KEYWORD),
+ BYTE("byte", Attribute.KEYWORD),
+ BOOLEAN("boolean", Attribute.KEYWORD),
+ FLOAT("float", Attribute.KEYWORD),
+ DOUBLE("double", Attribute.KEYWORD),
+ CHAR("char", Attribute.KEYWORD),
+
+ // Flow control
+ IF("if", Attribute.KEYWORD),
+ // Technically two keywords, but we want it to stick together when formatting
+ ELSE_IF("else if", Attribute.KEYWORD),
+ ELSE("else", Attribute.KEYWORD),
+ FOR("for", Attribute.KEYWORD),
+ WHILE("while", Attribute.KEYWORD),
+ DO("do", Attribute.KEYWORD),
+ BREAK("break", Attribute.KEYWORD),
+ CONTINUE("continue", Attribute.KEYWORD),
+ SWITCH("switch", Attribute.KEYWORD),
+ CASE("case", Attribute.KEYWORD),
+ TRY("try", Attribute.KEYWORD),
+ CATCH("catch", Attribute.KEYWORD),
+ GOTO("goto", Attribute.KEYWORD),
+
+ // Braces
OPEN_PARENTHESIS("("),
CLOSE_PARENTHESIS(")"),
OPEN_BRACES("{"),
CLOSE_BRACES("}"),
OPEN_BRACKETS("["),
CLOSE_BRACKETS("]"),
+
+ // General
+ DOT("."),
SEMICOLON(";"),
METHOD_REFERENCE("::"),
- COLON(":", false, true), // technically not a "real" operator but used in an enhanced for loop
COMMA(","),
- ARROW("->", false, true), // used in lambdas
- // I also wouldn't count this as an operator but again, it's required
- // for formatting
- PLUS_EQUALS("+=", false, true),
- MINUS_EQUALS("-=", false, true),
- MULTIPLY_EQUALS("*=", false, true),
- DIVIDE_EQUALS("/=", false, true),
- MODULO_EQUALS("%=", false, true),
- AND_EQUALS("&=", false, true),
- OR_EQUALS("|=", false, true),
- EQUALS("==", false, true),
- NOT_EQUALS("!=", false, true),
- GREATER_THAN_OR_EQUALS(">=", false, true),
- GREATER_THAN(">", false, true),
- LESS_THAN_OR_EQUALS("<=", false, true),
- LESS_THAN("<", false, true),
+ QUESTION_MARK("?", Attribute.BINARY_OPERATOR),
+
+ // Comments
+ SINGLE_LINE_COMMENT(Pattern.compile("//.*(?=\n|$)"), "// Foo"),
+ MULTI_LINE_COMMENT(Pattern.compile("""
+ /\\* #Start
+ .* #Content
+ \\*/ #End
+ """, Pattern.DOTALL | Pattern.COMMENTS), "/* Foo */"),
+
+ // Operators
+ // NOTE right shifts (<<, >>, >>>) are intentionally left out
+ // they conflict with nested generics like List>
+ SMART_AND("&&", Attribute.BINARY_OPERATOR),
+ SMART_OR("||", Attribute.BINARY_OPERATOR),
+ PLUS_EQUALS("+=", Attribute.BINARY_OPERATOR),
+ MINUS_EQUALS("-=", Attribute.BINARY_OPERATOR),
+ MULTIPLY_EQUALS("*=", Attribute.BINARY_OPERATOR),
+ DIVIDE_EQUALS("/=", Attribute.BINARY_OPERATOR),
+ MODULO_EQUALS("%=", Attribute.BINARY_OPERATOR),
+ AND_EQUALS("&=", Attribute.BINARY_OPERATOR),
+ XOR_EQUALS("^=", Attribute.BINARY_OPERATOR),
+ OR_EQUALS("|=", Attribute.BINARY_OPERATOR),
+ LEFT_SHIFT_EQUALS("<<=", Attribute.BINARY_OPERATOR),
+ LOGICAL_RIGHT_SHIFT_EQUALS(">>>=", Attribute.BINARY_OPERATOR),
+ ARITHMETIC_RIGHT_SHIFT_EQUALS(">>=", Attribute.BINARY_OPERATOR),
+ EQUALS("==", Attribute.BINARY_OPERATOR),
+ NOT_EQUALS("!=", Attribute.BINARY_OPERATOR),
NOT("!"),
- ASSIGN("=", false, true),
- PLUSPLUS("++"),
- PLUS("+", false, true),
- MINUSMINUS("--"),
- MINUS("-", false, true),
- BOOL_AND("&&", false, true),
- BOOL_OR("||", false, true),
-
- // this has to be over DIVIDE or else it'll be seen as 2x DIVIDE
- COMMENT(Pattern.compile("^(//.*|/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*/)")),
-
- DIVIDE("/", false, true),
- MULTIPLY("*", false, true),
- DOT("."),
- // other
- WILDCARD("?"),
- ANNOTATION(Pattern.compile("^(@[a-zA-Z][a-zA-Z0-9_]*)")),
- NUMBER(Pattern.compile("^((0[xb])?([0-9_]+|[0-9_]*(\\.\\d*))[dDfFlL]?)")),
- STRING(Pattern.compile("^(\"[^\"]*\")")),
- IDENTIFIER(Pattern.compile("^([a-zA-Z][a-zA-Z0-9_]*)")),
- WHITESPACE(Pattern.compile("^(\s+)")),
- UNKNOWN(Pattern.compile("^(.)"));
-
- private final Pattern regex;
- private final boolean isKeyword;
- private final boolean isOperator;
-
- TokenType(String pattern, boolean isKeyword, boolean isOperator) {
- if (!isKeyword) {
- this.regex = Pattern.compile("^(" + Pattern.quote(pattern) + ")");
- } else {
- this.regex = Pattern.compile("^(" + Pattern.quote(pattern) + ")(?![a-zA-Z])");
+ GREATER_THAN_OR_EQUALS(">=", Attribute.BINARY_OPERATOR),
+ GREATER_THAN(">", Attribute.BINARY_OPERATOR),
+ LESS_THAN_OR_EQUALS("<=", Attribute.BINARY_OPERATOR),
+ LEFT_SHIFT("<<", Attribute.BINARY_OPERATOR),
+ LESS_THAN("<", Attribute.BINARY_OPERATOR),
+ SINGLE_OR("|", Attribute.BINARY_OPERATOR),
+ SINGLE_AND("&", Attribute.BINARY_OPERATOR),
+ XOR("^", Attribute.BINARY_OPERATOR),
+ ASSIGN("=", Attribute.BINARY_OPERATOR),
+ // Technically not an operator, but used like one in lambdas and switch expressions
+ ARROW("->", Attribute.BINARY_OPERATOR),
+ PLUS_PLUS("++", Attribute.UNARY_OPERATOR),
+ PLUS("+", Attribute.BINARY_OPERATOR),
+ MINUS_MINUS("--", Attribute.UNARY_OPERATOR),
+ MINUS("-", Attribute.BINARY_OPERATOR),
+ DIVIDE("/", Attribute.BINARY_OPERATOR),
+ MULTIPLY("*", Attribute.BINARY_OPERATOR),
+ // Technically not an operator, but used like one in enhanced-for
+ COLON(":", Attribute.BINARY_OPERATOR),
+ COMPLEMENT("~", Attribute.UNARY_OPERATOR),
+ MODULO("%", Attribute.BINARY_OPERATOR),
+ INSTANCE_OF("instanceof", Attribute.BINARY_OPERATOR),
+
+ // Other
+ ANNOTATION(Pattern.compile("@[a-zA-Z]\\w*"), "@Foo"),
+ NUMBER(Pattern.compile("""
+ (0[xb])? #Different base
+ ([\\d_]+ #Integers
+ | [\\d_]+\\.[\\d_]+ #Float with both, 1.3
+ | [\\d_]+\\. #Float only left, 1.
+ | \\.[\\d_]+ #Float only right, .1
+ )
+ [dDfFlL]? #Type suffix
+ """, Pattern.COMMENTS), "1_23.4_56F"),
+ STRING(Matching::matchesString, Attribute.NONE, "\"foo\""),
+ IDENTIFIER(Pattern.compile("[a-zA-Z]\\w*"), "foo"),
+ WHITESPACE(Pattern.compile("\\s+"), " "),
+
+ // Fallback for everything that has not been matched yet
+ UNKNOWN(Pattern.compile(".", Pattern.DOTALL), "°");
+
+ private final Function> matcher;
+ private final Attribute attribute;
+ private final String contentExample;
+
+ /**
+ * Gets all token types in the order they should be used for matching.
+ *
+ * This is important, since not all types match prefix-free. For example, {@link #DIVIDE} hides
+ * {@link #SINGLE_LINE_COMMENT} if matched before.
+ *
+ * @return all token types in match order
+ */
+ public static TokenType[] getAllInMatchOrder() {
+ // We have an order-dependency by design here
+ return TokenType.values();
+ }
+
+ TokenType(Function> matcher, Attribute attribute,
+ String contentExample) {
+ this.matcher = matcher;
+ this.attribute = attribute;
+ this.contentExample = contentExample;
+
+ requireMatchesExample();
+ }
+
+ private void requireMatchesExample() {
+ if (matcher.apply(contentExample).isEmpty()) {
+ throw new AssertionError(
+ "The given content example (%s) is not matched by the token type (%s)"
+ .formatted(contentExample, this));
}
+ }
+
+ TokenType(Pattern pattern, String contentExample) {
+ this(text -> Matching.matchesPattern(pattern, text), Attribute.NONE, contentExample);
+ }
- this.isKeyword = isKeyword;
- this.isOperator = isOperator;
+ TokenType(String symbol, Attribute attribute) {
+ this(text -> Matching.matchesSymbol(symbol, text, attribute), attribute, symbol);
}
- TokenType(Pattern regex) {
- this.regex = regex;
- this.isKeyword = false;
- this.isOperator = false;
+ TokenType(String symbol) {
+ this(symbol, Attribute.NONE);
}
- TokenType(String pattern) {
- this(pattern, false, false);
+ /**
+ * Attempts to match this token type against the given text and returns the matched token.
+ *
+ * For example, {@code INT.matches("int x = 5")} matches and returns {@code Token("int", INT)}.
+ *
+ * For performance reasons, this method should ideally be called with an instance of
+ * {@link CharSequence} that creates views only, such as {@link CharBuffer}.
+ *
+ * @param text the text to match against
+ * @return the token matched by this type, if any
+ */
+ public Optional matches(CharSequence text) {
+ return matcher.apply(text).map(content -> new Token(content, this));
}
- public Pattern getRegex() {
- return regex;
+ /**
+ * The attribute of the type, if it can be further specified.
+ *
+ * @return the attribute of the type
+ */
+ public Attribute getAttribute() {
+ return attribute;
}
- public boolean isKeyword() {
- return isKeyword;
+ /**
+ * An example token content this type would match.
+ *
+ * @return example match
+ */
+ String getContentExample() {
+ return contentExample;
}
- public boolean isOperator() {
- return isOperator;
+ /**
+ * Attributes of token types.
+ *
+ * For example, a token like {@code +} is a {@link #BINARY_OPERATOR}.
+ */
+ public enum Attribute {
+ /**
+ * A keyword in the language, has to stand alone, for example with a space left and right.
+ * Such as in {@code public final class}.
+ */
+ KEYWORD,
+ /**
+ * An operator with two arguments, one left and one right. For example {@code 5 + 3}.
+ */
+ BINARY_OPERATOR,
+ /**
+ * An operator with a single argument, for example {@code x++}.
+ */
+ UNARY_OPERATOR,
+ /**
+ * No further specification of the type.
+ */
+ NONE
}
}
diff --git a/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/TokenizationException.java b/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/TokenizationException.java
deleted file mode 100644
index a233ed127e..0000000000
--- a/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/TokenizationException.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package org.togetherjava.tjbot.formatter.tokenizer;
-
-/**
- * Exception that can occur when lexing
- */
-public class TokenizationException extends RuntimeException {
- public TokenizationException(String message) {
- super(message);
- }
-}
diff --git a/formatter/src/main/java/org/togetherjava/tjbot/formatter/util/LookaheadArrayDeque.java b/formatter/src/main/java/org/togetherjava/tjbot/formatter/util/LookaheadArrayDeque.java
deleted file mode 100644
index 5361cbcbdc..0000000000
--- a/formatter/src/main/java/org/togetherjava/tjbot/formatter/util/LookaheadArrayDeque.java
+++ /dev/null
@@ -1,40 +0,0 @@
-package org.togetherjava.tjbot.formatter.util;
-
-import java.util.ArrayDeque;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-/**
- * A {@link LookaheadQueue} implementation that is based on an {@link ArrayDeque}
- */
-public class LookaheadArrayDeque extends ArrayDeque implements LookaheadQueue {
- public LookaheadArrayDeque() {}
-
- public LookaheadArrayDeque(int numElements) {
- super(numElements);
- }
-
- public LookaheadArrayDeque(Collection extends E> c) {
- super(c);
- }
-
- @Override
- public E peek(int n) {
- List tmp = new ArrayList<>();
-
- while (n != 0 && !isEmpty()) {
- tmp.add(0, remove());
-
- n--;
- }
-
- E result = peek();
-
- for (E element : tmp) {
- addFirst(element);
- }
-
- return result;
- }
-}
diff --git a/formatter/src/main/java/org/togetherjava/tjbot/formatter/util/LookaheadQueue.java b/formatter/src/main/java/org/togetherjava/tjbot/formatter/util/LookaheadQueue.java
deleted file mode 100644
index ec45dd0408..0000000000
--- a/formatter/src/main/java/org/togetherjava/tjbot/formatter/util/LookaheadQueue.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package org.togetherjava.tjbot.formatter.util;
-
-import java.util.Queue;
-
-public interface LookaheadQueue extends Queue {
- /**
- * Peeks into the "future", peek(0) would be the equivalent to peek()
- */
- E peek(int n);
-}
diff --git a/formatter/src/main/java/org/togetherjava/tjbot/formatter/util/SkippableLookaheadArrayDeque.java b/formatter/src/main/java/org/togetherjava/tjbot/formatter/util/SkippableLookaheadArrayDeque.java
deleted file mode 100644
index 662cdd3033..0000000000
--- a/formatter/src/main/java/org/togetherjava/tjbot/formatter/util/SkippableLookaheadArrayDeque.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package org.togetherjava.tjbot.formatter.util;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.function.Predicate;
-
-public class SkippableLookaheadArrayDeque extends LookaheadArrayDeque
- implements SkippableLookaheadQueue {
- public SkippableLookaheadArrayDeque() {}
-
- public SkippableLookaheadArrayDeque(int numElements) {
- super(numElements);
- }
-
- public SkippableLookaheadArrayDeque(Collection extends E> c) {
- super(c);
- }
-
- @Override
- public E peek(int n, Predicate skip) {
- List tmp = new ArrayList<>();
-
- while (n != 0 && !isEmpty()) {
- E current = remove();
-
- tmp.add(0, current);
-
- if (!skip.test(current)) {
- n--;
- }
- }
-
- E result = peek();
-
- for (E element : tmp) {
- addFirst(element);
- }
-
- return result;
- }
-}
diff --git a/formatter/src/main/java/org/togetherjava/tjbot/formatter/util/SkippableLookaheadQueue.java b/formatter/src/main/java/org/togetherjava/tjbot/formatter/util/SkippableLookaheadQueue.java
deleted file mode 100644
index b7991ac2d4..0000000000
--- a/formatter/src/main/java/org/togetherjava/tjbot/formatter/util/SkippableLookaheadQueue.java
+++ /dev/null
@@ -1,7 +0,0 @@
-package org.togetherjava.tjbot.formatter.util;
-
-import java.util.function.Predicate;
-
-public interface SkippableLookaheadQueue extends LookaheadQueue {
- E peek(int n, Predicate skip);
-}
diff --git a/formatter/src/test/java/org/togetherjava/tjbot/formatter/FormatterTest.java b/formatter/src/test/java/org/togetherjava/tjbot/formatter/FormatterTest.java
index 3d0f7893b2..5c78480270 100644
--- a/formatter/src/test/java/org/togetherjava/tjbot/formatter/FormatterTest.java
+++ b/formatter/src/test/java/org/togetherjava/tjbot/formatter/FormatterTest.java
@@ -1,203 +1,295 @@
package org.togetherjava.tjbot.formatter;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.DisplayName;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.TestInstance;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
-import org.togetherjava.tjbot.formatter.tokenizer.Lexer;
+import java.util.stream.Stream;
-import static org.junit.jupiter.api.Assertions.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-@TestInstance(TestInstance.Lifecycle.PER_CLASS)
-class FormatterTest {
- Lexer lexer;
- Formatter formatter;
+final class FormatterTest {
+ private Formatter formatter;
- @BeforeAll
- void init() {
- lexer = new Lexer();
+ @BeforeEach
+ void setUp() {
formatter = new Formatter();
}
- @Test
- @DisplayName("Format Test #1")
- void formatTest1() {
- assertEquals("""
- ```java
+ private static Stream provideFormatTests() {
+ return Stream.of(Arguments.of("basic", """
+ public static
+ void main ( String [ ]args){ System.out. println( "Hello World!" );}""", """
public static void main(String[] args) {
- System.out.println("Hello World!");
- }
- ```""", formatter.format(
- "public static\nvoid main ( String [ ]args){ System.out. println( \"Hello World!\" );}",
- lexer));
- }
+ System.out.println("Hello World!");
+ }"""), Arguments.of("basic with comment", """
+ // Your First Program
- @Test
- @DisplayName("Format Test #2")
- void formatTest2() {
- assertEquals("""
- ```java
- List input = new ArrayList<>();
- List result = new ArrayList<>();
- for (String s : input) {
- result.add(s.trim());
- }
- return result;
- ```""", formatter.format(
+ class HelloWorld { public static void main(String[] args) {
+ System.out.println( "Hello, World!" ) ;
+ }}""", """
+ // Your First Program
+ class HelloWorld {
+ public static void main(String[] args) {
+ System.out.println("Hello, World!");
+ }
+ }"""), Arguments.of("compact",
"Listinput=new ArrayList<>();List result=new ArrayList<>();for(String s:input){result.add(s.trim());}return result;",
- lexer));
- }
-
- @Test
- @DisplayName("Format Test #3")
- void formatTest3() {
- assertEquals("""
- ```java
- if () {
- if () {
+ """
+ List input = new ArrayList<>();
+ List result = new ArrayList<>();
+ for (String s : input) {
+ result.add(s.trim());
+ }
+ return result;"""),
+ Arguments.of("nested unclosed ifs", "if(){if(){if(){if(){", """
if () {
+ if () {
if () {
- ```""", formatter.format("if(){if(){if(){if(){", lexer));
- }
+ if () {"""),
+ Arguments.of("while with too many closed braces", "while(if()e){}}", """
+ while (if () e) {
+ }
+ }"""), Arguments.of("else if", "if(1){}else if(2){}else{}", """
+ if (1) {
+ }
+ else if (2) {
+ }
+ else {
+ }"""),
+ Arguments.of("multi-arg method", "foo(1,2,3,b);", "foo(1, 2, 3, b);"),
+ Arguments.of("method declaration", "void foo(int a, int b, Object c){}", """
+ void foo(int a, int b, Object c) {
+ }"""), Arguments.of("index for loop", "for(int i=0;i<3;i++){}", """
+ for (int i = 0; i < 3; i++) {
+ }"""),
+ Arguments.of("diamond operator", "Listlist=new ArrayList < > ( ) ;",
+ "List list = new ArrayList<>();"),
+ Arguments.of("greater and less", "3<2&&2>3", "3 < 2 && 2 > 3"),
+ Arguments.of("single line comment", """
+ // this is a comment
+ void foo() {}""", """
+ // this is a comment
+ void foo() {
+ }"""), Arguments.of("annotations", """
+ @MyAnnotation
+ void foo() {}""", """
+ @MyAnnotation
+ void foo() {
+ }"""), Arguments.of("lambdas", "()->{System.out.println(5);};", """
+ () -> {
+ System.out.println(5);
+ };"""),
+ Arguments.of("lambda with params", "(s,e,d)->{System.out.println(5);};", """
+ (s, e, d) -> {
+ System.out.println(5);
+ };"""),
+ Arguments.of("lambda single param", "s->{System.out.println(5);};", """
+ s -> {
+ System.out.println(5);
+ };"""),
+ Arguments.of("lambda typed params",
+ "(String s,Object b)->{System.out.println(5);};", """
+ (String s, Object b) -> {
+ System.out.println(5);
+ };"""),
+ Arguments.of("ternary", "foo?bar:baz", "foo ? bar : baz"),
+ Arguments.of("adjusts existing whitespaces", """
+ int i3 = 4;
+ int i_3 = 5;""", """
+ int i3 = 4;
+ int i_3 = 5;"""),
+ Arguments.of("nested generics", "Map, Integer>>",
+ "Map, Integer>>"),
+ Arguments.of("right shifts", "x >> 1, y >>> 1", "x >> 1, y >>> 1"),
+ Arguments.of("minimized real code",
+ """
+ package org.togetherjava.tjbot.commands.code;import com.google.common.collect.Range; \
+ import com.google.googlejavaformat.java.FormatterException; \
+ import com.google.googlejavaformat.java.JavaOutput;import com.google.googlejavaformat.java.Replacement; \
+ import com.google.googlejavaformat.java.SnippetFormatter;import net.dv8tion.jda.api.EmbedBuilder; \
+ import net.dv8tion.jda.api.entities.MessageEmbed;import org.togetherjava.tjbot.commands.utils.CodeFence; \
+ import java.util.List;final class FormatCodeCommand implements CodeAction{private final SnippetFormatter formatter \
+ =new SnippetFormatter();@Override
+ public String getLabel(){return"Format";}@Override
+ public MessageEmbed apply(CodeFence codeFence){String formattedCode=formatCode(codeFence.code()); \
+ CodeFence formattedCodeFence=new CodeFence(codeFence.language(),formattedCode); \
+ return new EmbedBuilder().setTitle("Formatted code").setDescription(formattedCodeFence.toMarkdown()) \
+ .setColor(CodeMessageHandler.AMBIENT_COLOR).build();}
+ private String formatCode(String code){for(SnippetFormatter.SnippetKind snippetKind: \
+ SnippetFormatter.SnippetKind.values()){try{Listreplacements= \
+ formatter.format(snippetKind,code,List.of(Range.closedOpen(0,code.length())),2,false); \
+ return JavaOutput.applyReplacements(code,replacements);}catch(FormatterException e){}}
+ return"nope...";}}""",
+ """
+ package org.togetherjava.tjbot.commands.code;
- @Test
- @DisplayName("Format Test #4")
- void formatTest4() {
- assertEquals("""
- ```java
- while (if () e) {
- }
- }
- ```""", formatter.format("while(if()e){}}", lexer));
- }
+ import com.google.common.collect.Range;
+ import com.google.googlejavaformat.java.FormatterException;
+ import com.google.googlejavaformat.java.JavaOutput;
+ import com.google.googlejavaformat.java.Replacement;
+ import com.google.googlejavaformat.java.SnippetFormatter;
+ import net.dv8tion.jda.api.EmbedBuilder;
+ import net.dv8tion.jda.api.entities.MessageEmbed;
+ import org.togetherjava.tjbot.commands.utils.CodeFence;
+ import java.util.List;
- @Test
- @DisplayName("Format Test #5")
- void formatTest5() {
- assertEquals("""
- ```java
- if (1) {
- }
- else if (2) {
- }
- else {
- }
- ```""", formatter.format("if(1){}else if(2){}else{}", lexer));
- }
+ final class FormatCodeCommand implements CodeAction {
+ private final SnippetFormatter formatter = new SnippetFormatter();
+ @Override
+ public String getLabel() {
+ return "Format";
+ }
+ @Override
+ public MessageEmbed apply(CodeFence codeFence) {
+ String formattedCode = formatCode(codeFence.code());
+ CodeFence formattedCodeFence = new CodeFence(codeFence.language(), formattedCode);
+ return new EmbedBuilder().setTitle("Formatted code").setDescription(formattedCodeFence.toMarkdown()).setColor(CodeMessageHandler.AMBIENT_COLOR).build();
+ }
+ private String formatCode(String code) {
+ for (SnippetFormatter.SnippetKind snippetKind : SnippetFormatter.SnippetKind.values()) {
+ try {
+ List replacements = formatter.format(snippetKind, code, List.of(Range.closedOpen(0, code.length())), 2, false);
+ return JavaOutput.applyReplacements(code, replacements);
+ } catch (FormatterException e) {
+ }
+ }
+ return "nope...";
+ }
+ }"""),
+ Arguments.of("real code with javadoc and generics",
+ """
+ package org.togetherjava.tjbot.formatter.tokenizer;
+ import java.util.Set;
+ /**
+ * Single token of a code, for example an opening-brace.
+ *
+ * As example, the code {@code int x = "foo";} is split into tokens:
+ *
+ * ("int", INT)
+ * ("x", IDENTIFIER)
+ * ("=", ASSIGN)
+ ("\\"foo\\"", STRING)
+ (";", SEMICOLON)
+
+ *
+ * @param content the actual text contained in the token, e.g., an identifier like {@code x}
+ * @param type the type of the token, e.g., IDENTIFIER
+ */
+ public record Token(String content, TokenType type) {
+ private static final Set DEBUG_SHOW_CONTENT_TYPES = Set.of(TokenType.IDENTIFIER, TokenType.UNKNOWN, TokenType.STRING, TokenType.SINGLE_LINE_COMMENT, TokenType.MULTI_LINE_COMMENT);
+ @Override
+ public String toString() {
+ // For some types it helps debugging to also show the content
+ String contentText = DEBUG_SHOW_CONTENT_TYPES.contains(type) ?"(%s)".formatted(content) : "";
+ return type.name() + contentText;
+ }
+ }""",
+ """
+ package org.togetherjava.tjbot.formatter.tokenizer;
- @Test
- @DisplayName("Multi-argument method invocation renders correctly")
- void testMultiArgMethodInvocation() {
- assertEquals("""
- ```java
- foo(1, 2, 3, b);
- ```""", formatter.format("foo(1,2,3,b);", lexer));
- }
+ import java.util.Set;
- @Test
- @DisplayName("Method declaration renders correctly")
- void testMethodDeclaration() {
- assertEquals("""
- ```java
- void foo(int a, int b, Object c) {
- }
- ```""", formatter.format("void foo(int a, int b, Object c){}", lexer));
- }
+ /**
+ * Single token of a code, for example an opening-brace.
+ *
+ * As example, the code {@code int x = "foo";} is split into tokens:
+ *
+ * ("int", INT)
+ * ("x", IDENTIFIER)
+ * ("=", ASSIGN)
+ ("\\"foo\\"", STRING)
+ (";", SEMICOLON)
+
+ *
+ * @param content the actual text contained in the token, e.g., an identifier like {@code x}
+ * @param type the type of the token, e.g., IDENTIFIER
+ */
+ public record Token(String content, TokenType type) {
+ private static final Set DEBUG_SHOW_CONTENT_TYPES = Set.of(TokenType.IDENTIFIER, TokenType.UNKNOWN, TokenType.STRING, TokenType.SINGLE_LINE_COMMENT, TokenType.MULTI_LINE_COMMENT);
+ @Override
+ public String toString() {
+ // For some types it helps debugging to also show the content
+ String contentText = DEBUG_SHOW_CONTENT_TYPES.contains(type) ? "(%s)".formatted(content) : "";
+ return type.name() + contentText;
+ }
+ }"""),
+ Arguments.of("real code with annotations arguments",
+ """
+ @StreamListener()
+ @SendTo(EnrichmentKStreamProcessor.OUTPUT)
+ public KStream process(
+ @Input(KStreamProcessor.INPUT) KStream X,
+ @Input(KStreamProcessor.INPUT_ENRICH_TABLE) KTable> Y) {
- @Test
- @DisplayName("For int loop working correctly")
- void testForInt() {
- assertEquals("""
- ```java
- for (int i = 0; i < 3; i++) {
- }
- ```""", formatter.format("for(int i=0;i<3;i++){}", lexer));
- }
+ return X
+ .filter((s, x1) -> checkProductClassFilter(x1))
+ .map((k, v) -> new KeyValue<>(v.getId(), v))
+ .leftJoin(Y,
+ (x, y) -> enrichData(x, y),
+ Joined.with(Serdes.String(), XDataJsonSerde,jdbcMapJsonSerde ));
+ }""",
+ """
+ @StreamListener() @SendTo(EnrichmentKStreamProcessor.OUTPUT) public KStream \
+ process(@Input(KStreamProcessor.INPUT) KStream X, \
+ @Input(KStreamProcessor.INPUT_ENRICH_TABLE) KTable> Y) {
+ return X.filter((s, x1) -> checkProductClassFilter(x1)).map((k, v) -> new KeyValue<>(v.getId(), v))\
+ .leftJoin(Y, (x, y) -> enrichData(x, y), Joined.with(Serdes.String(), XDataJsonSerde, jdbcMapJsonSerde));
+ }"""),
+ Arguments.of("c++", """
+ using namespace std;
- @Test
- @DisplayName("Diamond operator rendering correctly")
- void testDiamondOperator() {
- assertEquals("""
- ```java
- List list = new ArrayList<>();
- ```""", formatter.format("Listlist=new ArrayList < > ( ) ;", lexer));
- }
+ int main()
+ { \s
+ int divisor, dividend, quotient, remainder;
- @Test
- @DisplayName("BIGGER and SMALLER rendering correctly")
- void testBiggerAndSmaller() {
- assertEquals("""
- ```java
- 3 < 2 && 2 > 3
- ```""", formatter.format("3<2&&2>3", lexer));
- }
+ cout << "Enter dividend: ";
+ cin >> dividend;
- @Test
- @DisplayName("Comment renders correctly")
- void testComment() {
- assertEquals("""
- ```java
- // this is a comment
- void foo() {
- }
- ```""", formatter.format("// this is a comment\nvoid foo() {}", lexer));
- }
+ cout << "Enter divisor: ";
+ cin >> divisor;
- @Test
- @DisplayName("Annotation renders correctly")
- void testAnnotation() {
- assertEquals("""
- ```java
- @MyAnnotation
- void foo() {
- }
- ```""", formatter.format("@MyAnnotation\nvoid foo() {}", lexer));
- }
+ quotient = dividend / divisor;
+ remainder = dividend % divisor;
- @Test
- @DisplayName("Lambda renders correctly")
- void testLambda() {
- assertEquals("""
- ```java
- () -> {
- System.out.println("Hello World");
- };
- ```""", formatter.format("()->{System.out.println(\"Hello World\");};", lexer));
- }
+ cout << "Quotient = " << quotient << endl;
+ cout << "Remainder = " << remainder;
- @Test
- @DisplayName("Lambda with parameters renders correctly")
- void testLambdaParams() {
- assertEquals("""
- ```java
- (s, e, d) -> {
- System.out.println("Hello World");
- };
- ```""",
- formatter.format("(s,e,d)->{System.out.println(\"Hello World\");};", lexer));
- }
+ return 0;
+ }""", """
+ using namespace std;
+ int main() {
+ int divisor, dividend, quotient, remainder;
+ cout << "Enter dividend: ";
+ cin >> dividend;
+ cout << "Enter divisor: ";
+ cin >> divisor;
+ quotient = dividend / divisor;
+ remainder = dividend % divisor;
+ cout << "Quotient = " << quotient << endl;
+ cout << "Remainder = " << remainder;
+ return 0;
+ }"""), Arguments.of("kotlin", """
+ fun main(args: Array) {
+
+ val first = 1.5f
+ val second = 2.0f
- @Test
- @DisplayName("Lambda with parenthesis parameter renders correctly")
- void testLambdaNoParenParams() {
- assertEquals("""
- ```java
- s -> {
- System.out.println("Hello World");
- };
- ```""", formatter.format("s->{System.out.println(\"Hello World\");};", lexer));
+ val product = first * second
+
+ println("The product is: $product")
+ }""",
+ """
+ fun main(args : Array ) {
+ val first = 1.5fval second = 2.0fval product = first * second println("The product is: $product") }"""));
}
- @Test
- @DisplayName("Lambda with typed parameters renders correctly")
- void testLambdaTypeParams() {
- assertEquals("""
- ```java
- (String s, Object b) -> {
- System.out.println("Hello World");
- };
- ```""", formatter
- .format("(String s,Object b)->{System.out.println(\"Hello World\");};", lexer));
+ @ParameterizedTest
+ @MethodSource("provideFormatTests")
+ void format(String testName, String code, String expectedFormattedCode) {
+ String actualFormattedCode = formatter.format(code);
+
+ assertEquals(expectedFormattedCode, actualFormattedCode, testName);
}
}
diff --git a/formatter/src/test/java/org/togetherjava/tjbot/formatter/formatting/FormatterRulesTest.java b/formatter/src/test/java/org/togetherjava/tjbot/formatter/formatting/FormatterRulesTest.java
new file mode 100644
index 0000000000..698520c638
--- /dev/null
+++ b/formatter/src/test/java/org/togetherjava/tjbot/formatter/formatting/FormatterRulesTest.java
@@ -0,0 +1,48 @@
+package org.togetherjava.tjbot.formatter.formatting;
+
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+final class FormatterRulesTest {
+
+ private static Stream providePatchMultiLineCommentTests() {
+ return Stream.of(Arguments.of("basic", """
+ /*
+ * Foo
+ * Bar
+ */""", "", """
+ /*
+ * Foo
+ * Bar
+ */"""), Arguments.of("single line", "/* Foo */", "", "/* Foo */"),
+ Arguments.of("empty", "", "", ""),
+ Arguments.of("empty comment", "/**/", "", "/**/"),
+ Arguments.of("compact two lines", """
+ /*Foo
+ Bar*/""", "", """
+ /*Foo
+ Bar*/"""), Arguments.of("with indents", """
+ /*
+ * Foo
+ * Bar
+ */""", " ", """
+ /*
+ * Foo
+ * Bar
+ */"""));
+ }
+
+ @ParameterizedTest
+ @MethodSource("providePatchMultiLineCommentTests")
+ void patchMultiLineComment(String testName, String comment, String indent,
+ String expectedPatchedComment) {
+ String actualPatchedComment = FormatterRules.patchMultiLineComment(comment, indent);
+
+ assertEquals(expectedPatchedComment, actualPatchedComment, testName);
+ }
+}
diff --git a/formatter/src/test/java/org/togetherjava/tjbot/formatter/formatting/TokenQueueTest.java b/formatter/src/test/java/org/togetherjava/tjbot/formatter/formatting/TokenQueueTest.java
new file mode 100644
index 0000000000..04b0aa4146
--- /dev/null
+++ b/formatter/src/test/java/org/togetherjava/tjbot/formatter/formatting/TokenQueueTest.java
@@ -0,0 +1,137 @@
+package org.togetherjava.tjbot.formatter.formatting;
+
+import org.junit.jupiter.api.Test;
+
+import org.togetherjava.tjbot.formatter.tokenizer.Token;
+import org.togetherjava.tjbot.formatter.tokenizer.TokenType;
+
+import java.util.List;
+import java.util.NoSuchElementException;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+final class TokenQueueTest {
+
+ @Test
+ void isEmpty() {
+ TokenQueue queue = provideEmptyTokenQueue();
+ assertTrue(queue.isEmpty());
+
+ queue = provide2TokenQueue();
+ assertFalse(queue.isEmpty());
+
+ queue.consume();
+ assertFalse(queue.isEmpty());
+
+ queue.consume();
+ assertTrue(queue.isEmpty());
+ }
+
+ @Test
+ void remainingSize() {
+ TokenQueue queue = provideEmptyTokenQueue();
+ assertEquals(0, queue.remainingSize());
+
+ queue = provide2TokenQueue();
+ assertEquals(2, queue.remainingSize());
+
+ queue.consume();
+ assertEquals(1, queue.remainingSize());
+ queue.consume();
+ assertEquals(0, queue.remainingSize());
+ }
+
+ @Test
+ void consume() {
+ TokenQueue queue = provideEmptyTokenQueue();
+ assertThrows(NoSuchElementException.class, queue::consume);
+
+ queue = provide2TokenQueue();
+ assertEquals("class", queue.consume().content());
+
+ assertEquals("Foo", queue.consume().content());
+
+ assertThrows(NoSuchElementException.class, queue::consume);
+ }
+
+ @Test
+ void peekType() {
+ TokenQueue queue = provideEmptyTokenQueue();
+ assertThrows(NoSuchElementException.class, queue::peekType);
+
+ queue = provide2TokenQueue();
+ assertEquals(TokenType.CLASS, queue.peekType());
+ // Does not consume tokens, still the same
+ assertEquals(TokenType.CLASS, queue.peekType());
+
+ queue.consume();
+ assertEquals(TokenType.IDENTIFIER, queue.peekType());
+
+ queue.consume();
+ assertThrows(NoSuchElementException.class, queue::peekType);
+ }
+
+ @Test
+ void peekTypeBack() {
+ TokenQueue queue = provideEmptyTokenQueue();
+ assertThrows(NoSuchElementException.class, queue::peekTypeBack);
+
+ queue = provide2TokenQueue();
+ assertThrows(NoSuchElementException.class, queue::peekTypeBack);
+
+ queue.consume();
+ assertEquals(TokenType.CLASS, queue.peekTypeBack());
+ // Does not consume tokens, still the same
+ assertEquals(TokenType.CLASS, queue.peekTypeBack());
+
+ queue.consume();
+ assertEquals(TokenType.IDENTIFIER, queue.peekTypeBack());
+ }
+
+ @Test
+ void peekTypeStream() {
+ TokenQueue queue = provideEmptyTokenQueue();
+ assertTrue(queue.peekTypeStream().toList().isEmpty());
+
+ queue = provide2TokenQueue();
+ List expectedTypes = List.of(TokenType.CLASS, TokenType.IDENTIFIER);
+ assertEquals(expectedTypes, queue.peekTypeStream().toList());
+ // Does not consume tokens, still the same
+ assertEquals(expectedTypes, queue.peekTypeStream().toList());
+
+ queue.consume();
+ expectedTypes = List.of(TokenType.IDENTIFIER);
+ assertEquals(expectedTypes, queue.peekTypeStream().toList());
+
+ queue.consume();
+ assertTrue(queue.peekTypeStream().toList().isEmpty());
+ }
+
+ @Test
+ void peekTypeBackStream() {
+ TokenQueue queue = provideEmptyTokenQueue();
+ assertTrue(queue.peekTypeBackStream().toList().isEmpty());
+
+ queue = provide2TokenQueue();
+ assertTrue(queue.peekTypeBackStream().toList().isEmpty());
+
+ queue.consume();
+ List expectedTypes = List.of(TokenType.CLASS);
+ assertEquals(expectedTypes, queue.peekTypeBackStream().toList());
+ // Does not consume tokens, still the same
+ assertEquals(expectedTypes, queue.peekTypeBackStream().toList());
+
+ queue.consume();
+ expectedTypes = List.of(TokenType.IDENTIFIER, TokenType.CLASS);
+ assertEquals(expectedTypes, queue.peekTypeBackStream().toList());
+ }
+
+ private static TokenQueue provide2TokenQueue() {
+ return new TokenQueue(List.of(new Token("class", TokenType.CLASS),
+ new Token("Foo", TokenType.IDENTIFIER)));
+ }
+
+ private static TokenQueue provideEmptyTokenQueue() {
+ return new TokenQueue(List.of());
+ }
+}
diff --git a/formatter/src/test/java/org/togetherjava/tjbot/formatter/tokenizer/LexerTest.java b/formatter/src/test/java/org/togetherjava/tjbot/formatter/tokenizer/LexerTest.java
index c306827e7b..45824e946d 100644
--- a/formatter/src/test/java/org/togetherjava/tjbot/formatter/tokenizer/LexerTest.java
+++ b/formatter/src/test/java/org/togetherjava/tjbot/formatter/tokenizer/LexerTest.java
@@ -1,63 +1,87 @@
package org.togetherjava.tjbot.formatter.tokenizer;
-import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.TestInstance;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
-import java.util.ArrayList;
import java.util.List;
-import static org.junit.jupiter.api.Assertions.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-@TestInstance(TestInstance.Lifecycle.PER_CLASS)
-class LexerTest {
- Lexer lexer;
+final class LexerTest {
+ private Lexer lexer;
- @BeforeAll
- void init() {
+ @BeforeEach
+ void setUp() {
lexer = new Lexer();
}
- @Test
- @DisplayName("Invalid input does throw an exception")
- void testInvalidInput() {
- assertThrows(TokenizationException.class, () -> lexer.tokenize("\r"));
+ private List tokenize(String code) {
+ return lexer.tokenize(code).stream().map(Token::type).toList();
}
@Test
- @DisplayName("Valid input does not throw an exception")
- void testValidInput() {
- assertDoesNotThrow(() -> lexer.tokenize("\n"));
+ void basic() {
+ String realCode = """
+ int x=5;
+ String y =foo("bar");""";
+
+ List expectedTypes = List.of(TokenType.INT, TokenType.WHITESPACE,
+ TokenType.IDENTIFIER, TokenType.ASSIGN, TokenType.NUMBER, TokenType.SEMICOLON,
+ TokenType.WHITESPACE, TokenType.IDENTIFIER, TokenType.WHITESPACE,
+ TokenType.IDENTIFIER, TokenType.WHITESPACE, TokenType.ASSIGN, TokenType.IDENTIFIER,
+ TokenType.OPEN_PARENTHESIS, TokenType.STRING, TokenType.CLOSE_PARENTHESIS,
+ TokenType.SEMICOLON);
+
+ List actualTypes = tokenize(realCode);
+
+ assertEquals(expectedTypes, actualTypes);
}
@Test
- @DisplayName("Empty input does not throw an exception")
- void testEmptyInput() {
- assertDoesNotThrow(() -> lexer.tokenize(""));
+ void emptyCode() {
+ String emptyCode = "";
+
+ List tokens = lexer.tokenize(emptyCode);
+
+ assertTrue(tokens.isEmpty());
}
@Test
- @DisplayName("All tokens get tokenized correctly")
- void testInput() {
- String testString =
- "class enum record interface import if for while null extends implements new return package this yield catch try else if else super public private protected static sealed non-sealed final abstract void int long short byte boolean float double char ( ) { } [ ] ; :: : , -> += -= *= /= %= &= |= == != >= > <= < ! = ++ + -- - && || /* a */ / * . ? @annotation 0 \"string\" identifier ` ";
- List tokens = lexer.tokenize(testString).stream().map(Token::type).toList(),
- expected = new ArrayList<>();
-
- for (TokenType type : TokenType.values()) {
- if (type != TokenType.WHITESPACE) {
- expected.add(type);
- expected.add(TokenType.WHITESPACE);
- }
- }
-
- assertEquals(expected, tokens);
+ @DisplayName("Keywords can be used as identifier if a letter follows them, such as new vs newText")
+ void keywordVersusIdentifier() {
+ String code = "new newText";
+ List expectedTypes =
+ List.of(TokenType.NEW, TokenType.WHITESPACE, TokenType.IDENTIFIER);
+
+ List