Skip to content

Commit

Permalink
fix and cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
twonirwana committed Nov 20, 2024
1 parent 7e23f7e commit f5c2fd3
Show file tree
Hide file tree
Showing 13 changed files with 152 additions and 52 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,6 @@ protected boolean shouldKeepExistingButtonMessage(@NonNull ButtonEventAdaptor ev
public @NonNull Optional<String> getCurrentMessageContentChange(C config, State<S> state, boolean keepExistingButtonMessage) {
return AbstractCommand.this.getCurrentMessageContentChange(config, state, keepExistingButtonMessage);
}

@Override
public @NonNull MessageDataDTO createEmptyMessageData(@NonNull UUID configUUID, @Nullable Long guildId, long channelId, long messageId) {
return AbstractCommand.this.createEmptyMessageData(configUUID, guildId, channelId, messageId);
}
};
slashCommand = new SlashCommandImpl<>(persistenceManager) {
@Override
Expand Down Expand Up @@ -151,11 +146,6 @@ protected Collection<CommandDefinitionOption> additionalCommandOptions() {
protected @NonNull Optional<String> getStartOptionsValidationMessage(@NonNull CommandInteractionOption options, long channelId, long userId, @NonNull Locale userLocale) {
return AbstractCommand.this.getStartOptionsValidationMessage(options, channelId, userId, userLocale);
}

@Override
public @NonNull MessageDataDTO createEmptyMessageData(@NonNull UUID configUUID, @Nullable Long guildId, long channelId, long messageId) {
return AbstractCommand.this.createEmptyMessageData(configUUID, guildId, channelId, messageId);
}
};
}

Expand Down Expand Up @@ -199,16 +189,6 @@ protected abstract ConfigAndState<C, S> getMessageDataAndUpdateWithButtonValue(@
@NonNull String invokingUserName);


/**
* On the creation of a message an empty state need to be saved so we know the message exists and we can remove it later, even on concurrent actions
*/
@VisibleForTesting
public @NonNull MessageDataDTO createEmptyMessageData(@NonNull UUID configUUID,
@Nullable Long guildId,
long channelId,
long messageId) {
return BaseCommandUtils.createCleanupAndSaveEmptyMessageData(configUUID, guildId, channelId, messageId, getCommandId(), persistenceManager);
}

//visible for welcome command
public abstract Optional<MessageConfigDTO> createMessageConfig(@NonNull UUID configUUID,
Expand Down
11 changes: 6 additions & 5 deletions bot/src/main/java/de/janno/discord/bot/command/ClearCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,9 @@ public ClearCommand(PersistenceManager persistenceManager) {
return List.of();
}

return persistenceManager.getNamedCommandsForChannel(userId, null).stream()
.filter(nc -> Strings.isNullOrEmpty(autoCompleteRequest.getFocusedOptionValue()) || nc.name().toLowerCase().contains(autoCompleteRequest.getFocusedOptionValue().toLowerCase()))
.map(n -> new AutoCompleteAnswer(n.name(), n.name()))
return persistenceManager.getNamedCommandsChannel(channelId).stream()
.filter(nc -> Strings.isNullOrEmpty(autoCompleteRequest.getFocusedOptionValue()) || nc.toLowerCase().contains(autoCompleteRequest.getFocusedOptionValue().toLowerCase()))
.map(n -> new AutoCompleteAnswer(n, n))
.distinct()
.sorted(Comparator.comparing(AutoCompleteAnswer::getName))
.limit(5)
Expand All @@ -77,7 +77,6 @@ public ClearCommand(PersistenceManager persistenceManager) {

final String name = event.getOption(NAME_OPTION).map(CommandInteractionOption::getStringValue).orElse(null);


return event.reply(I18n.getMessage("clear.reply", userLocal), false)
.then(Mono.just(persistenceManager.deleteMessageDataForChannel(event.getChannelId(), name))
.flux()
Expand All @@ -87,7 +86,9 @@ public ClearCommand(PersistenceManager persistenceManager) {
.doOnTerminate(() -> log.info("Finish delete"))
.then())
.doOnSuccess(v -> {
persistenceManager.deleteAllChannelConfig(event.getChannelId());
if (Strings.isNullOrEmpty(name)) {
persistenceManager.deleteAllChannelConfig(event.getChannelId());
}
persistenceManager.deleteAllMessageConfigForChannel(event.getChannelId(), name);
});
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package de.janno.discord.bot.command;

import de.janno.discord.bot.BaseCommandUtils;
import de.janno.discord.bot.BotMetrics;
import de.janno.discord.bot.I18n;
import de.janno.discord.bot.command.customDice.CustomDiceCommand;
Expand Down Expand Up @@ -80,7 +81,7 @@ private <C extends RollConfig> Mono<Void> moveButtonMessage(C config, AbstractCo
List<Mono<Void>> actions = List.of(
Mono.defer(() -> event.reply(I18n.getMessage("fetch.reply", event.getRequester().getUserLocal()), true)),
Mono.defer(() -> event.sendMessage(buttonMessage)
.doOnNext(messageId -> command.createEmptyMessageData(configUUID, event.getGuildId(), event.getChannelId(), messageId)))
.doOnNext(messageId -> BaseCommandUtils.createCleanupAndSaveEmptyMessageData(configUUID, event.getGuildId(), event.getChannelId(), messageId, getCommandId(), persistenceManager)))
.flatMap(newMessageId -> MessageDeletionHelper.deleteOldMessageAndData(persistenceManager, newMessageId, null, configUUID, event.getChannelId(), event))
.then());
return Flux.merge(1, actions.toArray(new Mono<?>[0]))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ protected Collection<CommandDefinitionOption> additionalCommandOptions() {
/**
* On the creation of a message an empty state need to be saved so we know the message exists and we can remove it later, even on concurrent actions
*/

protected @NonNull MessageDataDTO createEmptyMessageData(@NonNull UUID configUUID,
@Nullable Long guildId,
long channelId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.google.common.base.Stopwatch;
import com.google.common.base.Strings;
import de.janno.discord.bot.BaseCommandUtils;
import de.janno.discord.bot.BotMetrics;
import de.janno.discord.bot.I18n;
import de.janno.discord.bot.command.Config;
Expand Down Expand Up @@ -58,7 +59,7 @@ public class QuickstartCommand implements SlashCommand {
return List.of();
}

final List<AutoCompleteAnswer> savedNamedAnswers = persistenceManager.getNamedCommandsForChannel(userId, guildId).stream()
final List<AutoCompleteAnswer> savedNamedAnswers = persistenceManager.getLastUsedNamedCommandsOfUserAndGuild(userId, guildId).stream()
.filter(nc -> Strings.isNullOrEmpty(autoCompleteRequest.getFocusedOptionValue()) || nc.name().toLowerCase().contains(autoCompleteRequest.getFocusedOptionValue().toLowerCase()))
.filter(nc -> SUPPORTED_COMMANDS.contains(nc.commandId()))
.map(n -> new AutoCompleteAnswer(n.name(), n.name()))
Expand Down Expand Up @@ -172,6 +173,7 @@ private Optional<EmbedOrMessageDefinition> getMessage(Config genericConfig, UUID
}
if (commandAndMessageDefinition.isPresent()) {
return Mono.defer(() -> event.sendMessage(commandAndMessageDefinition.get()))
.doOnNext(messageId -> BaseCommandUtils.createCleanupAndSaveEmptyMessageData(newConfigUUID, guildId, channelId, messageId, getCommandId(), persistenceManager))
.doOnSuccess(v -> BotMetrics.timerNewButtonMessageMetricCounter(getCommandId(), stopwatch.elapsed()))
.then(event.reply(commandString, false))
.doOnSuccess(v ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
public final class NamedCommandHelper {

public static Optional<NamedConfig> getConfigForName(PersistenceManager persistenceManager, String name, Locale locale, @Nullable Long guildId, long userId) {
Optional<NamedConfig> savedNamedCommandConfig = persistenceManager.getNamedCommandsForChannel(userId, guildId).stream()
Optional<NamedConfig> savedNamedCommandConfig = persistenceManager.getLastUsedNamedCommandsOfUserAndGuild(userId, guildId).stream()
.filter(nc -> Objects.equals(nc.name(), name))
.flatMap(nc -> getConfigForNamedCommand(persistenceManager, nc.id()).map(snc -> new NamedConfig(snc.namedConfig().name(), snc.namedConfig().commandId(), snc.namedConfig().configClassId(), snc.namedConfig().config())).stream())
.findFirst();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet;
import de.janno.discord.bot.BaseCommandUtils;
import de.janno.discord.bot.BotEmojiUtil;
import de.janno.discord.bot.BotMetrics;
import de.janno.discord.bot.I18n;
Expand All @@ -21,7 +22,6 @@
import de.janno.discord.bot.dice.DiceEvaluatorAdapter;
import de.janno.discord.bot.persistance.Mapper;
import de.janno.discord.bot.persistance.MessageConfigDTO;
import de.janno.discord.bot.persistance.MessageDataDTO;
import de.janno.discord.bot.persistance.PersistenceManager;
import de.janno.discord.connector.api.*;
import de.janno.discord.connector.api.message.EmbedOrMessageDefinition;
Expand Down Expand Up @@ -325,7 +325,7 @@ private SavedNamedConfig saveConfigToStart(Config genericConfig, UUID starterCon
}

private void createEmptyMessageData(@NonNull UUID configUUID, @Nullable Long guildId, long channelId, long messageId) {
persistenceManager.saveMessageData(new MessageDataDTO(configUUID, guildId, channelId, messageId, getCommandId(), Mapper.NO_PERSISTED_STATE, null));
BaseCommandUtils.createCleanupAndSaveEmptyMessageData(configUUID, guildId, channelId, messageId, getCommandId(), persistenceManager);
}

public WelcomeMessageCreator getWelcomeMessage() {
Expand Down Expand Up @@ -423,7 +423,7 @@ private StarterConfig createStartConfigFromCreateOption(CommandInteractionOption
.filter(n -> !Strings.isNullOrEmpty(n))
.collect(Collectors.toSet());

final List<AutoCompleteAnswer> savedNamedAnswers = persistenceManager.getNamedCommandsForChannel(userId, guildId).stream()
final List<AutoCompleteAnswer> savedNamedAnswers = persistenceManager.getLastUsedNamedCommandsOfUserAndGuild(userId, guildId).stream()
.filter(nc -> Strings.isNullOrEmpty(autoCompleteRequest.getFocusedOptionValue()) || nc.name().toLowerCase().contains(autoCompleteRequest.getFocusedOptionValue().toLowerCase()))
.filter(nc -> SUPPORTED_COMMANDS.contains(nc.commandId()))
.map(n -> new AutoCompleteAnswer(n.name(), n.name()))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,5 +53,10 @@ public interface PersistenceManager {

void deleteMessageConfig(UUID configUUID);

List<SavedNamedConfigId> getNamedCommandsForChannel(long userId, Long guildId);
/**
* If there are commands with the same name, the last used one will be returned
*/
List<SavedNamedConfigId> getLastUsedNamedCommandsOfUserAndGuild(long userId, Long guildId);

List<String> getNamedCommandsChannel(long channelId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -558,7 +558,7 @@ AND MD.COMMAND_ID in ("""
}

@Override
public List<SavedNamedConfigId> getNamedCommandsForChannel(long userId, Long guildId) {
public List<SavedNamedConfigId> getLastUsedNamedCommandsOfUserAndGuild(long userId, Long guildId) {
Stopwatch stopwatch = Stopwatch.createStarted();
try (Connection con = databaseConnector.getConnection()) {
final String sql;
Expand All @@ -577,7 +577,8 @@ public List<SavedNamedConfigId> getNamedCommandsForChannel(long userId, Long gui
AND MC.CREATION_DATE = Latest.LatestDate
where (MC.CREATION_USER_ID = ?
OR MC.GUILD_ID = ?)
and MC.CONFIG_NAME is not null;
and MC.CONFIG_NAME is not null
order by MC.CONFIG_NAME;
""";
} else {
sql = """
Expand All @@ -592,7 +593,8 @@ public List<SavedNamedConfigId> getNamedCommandsForChannel(long userId, Long gui
and mc.CONFIG_NAME = Latest.CONFIG_NAME
AND MC.CREATION_DATE = Latest.LatestDate
where MC.CREATION_USER_ID = ?
and MC.CONFIG_NAME is not null;
and MC.CONFIG_NAME is not null
order by MC.CONFIG_NAME;
""";
}
try (PreparedStatement preparedStatement = con.prepareStatement(sql)) {
Expand All @@ -615,7 +617,35 @@ public List<SavedNamedConfigId> getNamedCommandsForChannel(long userId, Long gui
resultSet.getString("CONFIG_NAME")
));
}
BotMetrics.databaseTimer("getNamedCommandsForChannel", stopwatch.elapsed());
BotMetrics.databaseTimer("getNamedCommandsOfUserAndGuild", stopwatch.elapsed());
return result;

}
} catch (Exception e) {
throw new IllegalStateException(e);
}
}

@Override
public List<String> getNamedCommandsChannel(long channelId) {
Stopwatch stopwatch = Stopwatch.createStarted();
try (Connection con = databaseConnector.getConnection()) {
try (PreparedStatement preparedStatement = con.prepareStatement("""
SELECT DISTINCT MC.CONFIG_NAME
FROM MESSAGE_CONFIG MC
where MC.CHANNEL_ID = ?
and MC.CONFIG_NAME is not null
order by MC.CONFIG_NAME;
""")) {

preparedStatement.setLong(1, channelId);

ResultSet resultSet = preparedStatement.executeQuery();
List<String> result = new ArrayList<>();
while (resultSet.next()) {
result.add(resultSet.getString("CONFIG_NAME"));
}
BotMetrics.databaseTimer("getNamedCommandsChannel", stopwatch.elapsed());
return result;

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public ButtonEventAdaptorMockFactory(String commandId, AbstractCommand<C, S> com
this.messageIdCounter = new AtomicLong(0);
this.pinnedMessageIds = firstMessagePinned ? Sets.newHashSet(messageIdCounter.get()) : Collections.emptySet();
command.createMessageConfig(configUUID, GUILD_ID, CHANNEL_ID, USER_ID, config).ifPresent(persistenceManager::saveMessageConfig);
command.createEmptyMessageData(configUUID, GUILD_ID, CHANNEL_ID, messageIdCounter.get());
BaseCommandUtils.createCleanupAndSaveEmptyMessageData(configUUID, GUILD_ID, CHANNEL_ID, messageIdCounter.get(), command.getCommandId(), persistenceManager);
}

public ButtonEventAdaptorMock getButtonClickOnLastButtonMessage(String buttonValue) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import com.google.common.collect.ImmutableSet;
import de.janno.discord.bot.SlashEventAdaptorMock;
import de.janno.discord.bot.persistance.*;
import de.janno.discord.connector.api.AutoCompleteAnswer;
import de.janno.discord.connector.api.AutoCompleteRequest;
import de.janno.discord.connector.api.SlashEventAdaptor;
import de.janno.discord.connector.api.slash.CommandInteractionOption;
import org.junit.jupiter.api.AfterEach;
Expand Down Expand Up @@ -150,9 +152,34 @@ public void mockTest_name() throws InterruptedException {
assertThat(persistenceManager.getMessageData(otherChannelId, otherMessageId)).isPresent();
assertThat(persistenceManager.getMessageData(channelId, message2Id)).isPresent();

assertThat(persistenceManager.getChannelConfig(channelId, configClassId)).isEmpty();
assertThat(persistenceManager.getChannelConfig(channelId, configClassId)).isPresent();
assertThat(persistenceManager.getChannelConfig(otherChannelId, configClassId)).isPresent();

}

@Test
void getAutoCompleteAnswer_empty() {
persistenceManager = new PersistenceManagerImpl("jdbc:h2:mem:" + UUID.randomUUID(), null, null);
underTest = new ClearCommand(persistenceManager);

List<AutoCompleteAnswer> res = underTest.getAutoCompleteAnswer(new AutoCompleteRequest("name", "", List.of()), Locale.ENGLISH, 1L, 2L, 3L);

assertThat(res).isEmpty();
}

@Test
void getAutoCompleteAnswer_hit() {
persistenceManager = new PersistenceManagerImpl("jdbc:h2:mem:" + UUID.randomUUID(), null, null);
underTest = new ClearCommand(persistenceManager);
persistenceManager.saveMessageConfig(new MessageConfigDTO(UUID.randomUUID(), 2L, 1L, "testCommand", "testConfigClass", "configClass", "name1", 0L));
persistenceManager.saveMessageConfig(new MessageConfigDTO(UUID.randomUUID(), 2L, 1L, "testCommand", "testConfigClass", "configClass", "name1", 0L));
persistenceManager.saveMessageConfig(new MessageConfigDTO(UUID.randomUUID(), 2L, 1L, "testCommand", "testConfigClass", "configClass", "name2", 0L));
persistenceManager.saveMessageConfig(new MessageConfigDTO(UUID.randomUUID(), 2L, 2L, "testCommand", "testConfigClass", "configClass", "name3", 0L));
persistenceManager.saveMessageConfig(new MessageConfigDTO(UUID.randomUUID(), 1L, 3L, "testCommand", "testConfigClass", "configClass", "name4", null));

List<AutoCompleteAnswer> res = underTest.getAutoCompleteAnswer(new AutoCompleteRequest("name", "", List.of()), Locale.ENGLISH, 1L, 2L, 3L);

assertThat(res.stream().map(AutoCompleteAnswer::getName)).containsExactly("name1", "name2");
}

}
Loading

0 comments on commit f5c2fd3

Please sign in to comment.