From 82e5609be3468e1105cc69e22b26f077c4fb14c8 Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Sat, 16 Oct 2021 00:31:14 +0200 Subject: [PATCH 01/10] Change org.togetherjava.formatter to org.togetherjava.tjbot.formatter and org.togetherjava.logwatcher to org.togetherjava.tjbot.logwatcher to keep consistency --- .../formatter/CodeSectionFormatter.java | 13 +++++++------ .../{ => tjbot}/formatter/Formatter.java | 8 ++++---- .../{ => tjbot}/formatter/tokenizer/Lexer.java | 2 +- .../{ => tjbot}/formatter/tokenizer/Token.java | 2 +- .../{ => tjbot}/formatter/tokenizer/TokenType.java | 2 +- .../formatter/tokenizer/TokenizationException.java | 2 +- .../formatter/util/LookaheadArrayDeque.java | 2 +- .../{ => tjbot}/formatter/util/LookaheadQueue.java | 2 +- .../util/SkippableLookaheadArrayDeque.java | 2 +- .../formatter/util/SkippableLookaheadQueue.java | 2 +- .../{ => tjbot}/formatter/FormatterTest.java | 4 ++-- .../{ => tjbot}/formatter/tokenizer/LexerTest.java | 2 +- .../{ => tjbot}/logwatcher/Application.java | 12 +++++++----- .../{ => tjbot}/logwatcher/DatabaseProvider.java | 4 ++-- .../logwatcher/accesscontrol/AllowedRoles.java | 2 +- .../{ => tjbot}/logwatcher/accesscontrol/Role.java | 2 +- .../{ => tjbot}/logwatcher/config/Config.java | 2 +- .../logwatcher/constants/LogEventsConstants.java | 2 +- .../logwatcher/constants/UserConstants.java | 2 +- .../logwatcher/entities/InstantWrapper.java | 2 +- .../{ => tjbot}/logwatcher/entities/LogEvent.java | 2 +- .../logwatcher/entities/UserWrapper.java | 4 ++-- .../{ => tjbot}/logwatcher/logs/LogREST.java | 6 +++--- .../{ => tjbot}/logwatcher/logs/LogRepository.java | 2 +- .../logwatcher/logs/LogRepositoryImpl.java | 2 +- .../logwatcher/oauth/OAuth2LoginConfig.java | 4 ++-- .../logwatcher/users/AuthenticatedUser.java | 4 ++-- .../logwatcher/users/UserDetailsServiceImpl.java | 6 +++--- .../logwatcher/users/UserRepository.java | 4 ++-- .../logwatcher/users/UserRepositoryImpl.java | 4 ++-- .../{ => tjbot}/logwatcher/util/LogReader.java | 4 ++-- .../logwatcher/util/NotificationUtils.java | 2 +- .../{ => tjbot}/logwatcher/views/MainLayout.java | 14 +++++++------- .../logwatcher/views/logs/LogsView.java | 12 ++++++------ .../logwatcher/views/logs/StreamedView.java | 14 +++++++------- .../views/usermanagement/UserManagement.java | 14 +++++++------- .../logwatcher/watcher/StreamWatcher.java | 2 +- 37 files changed, 87 insertions(+), 84 deletions(-) rename formatter/src/main/java/org/togetherjava/{ => tjbot}/formatter/CodeSectionFormatter.java (96%) rename formatter/src/main/java/org/togetherjava/{ => tjbot}/formatter/Formatter.java (95%) rename formatter/src/main/java/org/togetherjava/{ => tjbot}/formatter/tokenizer/Lexer.java (98%) rename formatter/src/main/java/org/togetherjava/{ => tjbot}/formatter/tokenizer/Token.java (93%) rename formatter/src/main/java/org/togetherjava/{ => tjbot}/formatter/tokenizer/TokenType.java (98%) rename formatter/src/main/java/org/togetherjava/{ => tjbot}/formatter/tokenizer/TokenizationException.java (80%) rename formatter/src/main/java/org/togetherjava/{ => tjbot}/formatter/util/LookaheadArrayDeque.java (94%) rename formatter/src/main/java/org/togetherjava/{ => tjbot}/formatter/util/LookaheadQueue.java (82%) rename formatter/src/main/java/org/togetherjava/{ => tjbot}/formatter/util/SkippableLookaheadArrayDeque.java (95%) rename formatter/src/main/java/org/togetherjava/{ => tjbot}/formatter/util/SkippableLookaheadQueue.java (76%) rename formatter/src/test/java/org/togetherjava/{ => tjbot}/formatter/FormatterTest.java (98%) rename formatter/src/test/java/org/togetherjava/{ => tjbot}/formatter/tokenizer/LexerTest.java (97%) rename logviewer/src/main/java/org/togetherjava/{ => tjbot}/logwatcher/Application.java (80%) rename logviewer/src/main/java/org/togetherjava/{ => tjbot}/logwatcher/DatabaseProvider.java (94%) rename logviewer/src/main/java/org/togetherjava/{ => tjbot}/logwatcher/accesscontrol/AllowedRoles.java (87%) rename logviewer/src/main/java/org/togetherjava/{ => tjbot}/logwatcher/accesscontrol/Role.java (94%) rename logviewer/src/main/java/org/togetherjava/{ => tjbot}/logwatcher/config/Config.java (98%) rename logviewer/src/main/java/org/togetherjava/{ => tjbot}/logwatcher/constants/LogEventsConstants.java (93%) rename logviewer/src/main/java/org/togetherjava/{ => tjbot}/logwatcher/constants/UserConstants.java (82%) rename logviewer/src/main/java/org/togetherjava/{ => tjbot}/logwatcher/entities/InstantWrapper.java (97%) rename logviewer/src/main/java/org/togetherjava/{ => tjbot}/logwatcher/entities/LogEvent.java (98%) rename logviewer/src/main/java/org/togetherjava/{ => tjbot}/logwatcher/entities/UserWrapper.java (93%) rename logviewer/src/main/java/org/togetherjava/{ => tjbot}/logwatcher/logs/LogREST.java (87%) rename logviewer/src/main/java/org/togetherjava/{ => tjbot}/logwatcher/logs/LogRepository.java (89%) rename logviewer/src/main/java/org/togetherjava/{ => tjbot}/logwatcher/logs/LogRepositoryImpl.java (97%) rename logviewer/src/main/java/org/togetherjava/{ => tjbot}/logwatcher/oauth/OAuth2LoginConfig.java (97%) rename logviewer/src/main/java/org/togetherjava/{ => tjbot}/logwatcher/users/AuthenticatedUser.java (97%) rename logviewer/src/main/java/org/togetherjava/{ => tjbot}/logwatcher/users/UserDetailsServiceImpl.java (93%) rename logviewer/src/main/java/org/togetherjava/{ => tjbot}/logwatcher/users/UserRepository.java (93%) rename logviewer/src/main/java/org/togetherjava/{ => tjbot}/logwatcher/users/UserRepositoryImpl.java (96%) rename logviewer/src/main/java/org/togetherjava/{ => tjbot}/logwatcher/util/LogReader.java (92%) rename logviewer/src/main/java/org/togetherjava/{ => tjbot}/logwatcher/util/NotificationUtils.java (95%) rename logviewer/src/main/java/org/togetherjava/{ => tjbot}/logwatcher/views/MainLayout.java (92%) rename logviewer/src/main/java/org/togetherjava/{ => tjbot}/logwatcher/views/logs/LogsView.java (91%) rename logviewer/src/main/java/org/togetherjava/{ => tjbot}/logwatcher/views/logs/StreamedView.java (92%) rename logviewer/src/main/java/org/togetherjava/{ => tjbot}/logwatcher/views/usermanagement/UserManagement.java (94%) rename logviewer/src/main/java/org/togetherjava/{ => tjbot}/logwatcher/watcher/StreamWatcher.java (96%) diff --git a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java b/formatter/src/main/java/org/togetherjava/tjbot/formatter/CodeSectionFormatter.java similarity index 96% rename from formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java rename to formatter/src/main/java/org/togetherjava/tjbot/formatter/CodeSectionFormatter.java index 635aca8161..801bcf4f00 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/CodeSectionFormatter.java +++ b/formatter/src/main/java/org/togetherjava/tjbot/formatter/CodeSectionFormatter.java @@ -1,9 +1,10 @@ -package org.togetherjava.formatter; +package org.togetherjava.tjbot.formatter; -import org.togetherjava.formatter.tokenizer.Token; -import org.togetherjava.formatter.tokenizer.TokenType; -import org.togetherjava.formatter.util.SkippableLookaheadArrayDeque; -import org.togetherjava.formatter.util.SkippableLookaheadQueue; +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; @@ -183,7 +184,7 @@ private void handleGeneric(Token token) { /** * Checks if a given token type belongs to a generic type declaration (uses - * {@link org.togetherjava.formatter.util.LookaheadQueue#peek(int)} + * {@link LookaheadQueue#peek(int)} * * @param type current token type * @return whether the token type belongs to a generic type declaration diff --git a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java b/formatter/src/main/java/org/togetherjava/tjbot/formatter/Formatter.java similarity index 95% rename from formatter/src/main/java/org/togetherjava/formatter/Formatter.java rename to formatter/src/main/java/org/togetherjava/tjbot/formatter/Formatter.java index 4085b88dc8..624aec1b7f 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/Formatter.java +++ b/formatter/src/main/java/org/togetherjava/tjbot/formatter/Formatter.java @@ -1,8 +1,8 @@ -package org.togetherjava.formatter; +package org.togetherjava.tjbot.formatter; -import org.togetherjava.formatter.tokenizer.Lexer; -import org.togetherjava.formatter.tokenizer.Token; -import org.togetherjava.formatter.tokenizer.TokenType; +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; diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java b/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/Lexer.java similarity index 98% rename from formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java rename to formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/Lexer.java index b066924481..cbea6a7f38 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Lexer.java +++ b/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/Lexer.java @@ -1,4 +1,4 @@ -package org.togetherjava.formatter.tokenizer; +package org.togetherjava.tjbot.formatter.tokenizer; import java.util.ArrayList; import java.util.Arrays; diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Token.java b/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/Token.java similarity index 93% rename from formatter/src/main/java/org/togetherjava/formatter/tokenizer/Token.java rename to formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/Token.java index e924af3985..9d4d751256 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/Token.java +++ b/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/Token.java @@ -1,4 +1,4 @@ -package org.togetherjava.formatter.tokenizer; +package org.togetherjava.tjbot.formatter.tokenizer; import java.util.Set; diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java b/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/TokenType.java similarity index 98% rename from formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java rename to formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/TokenType.java index d24e2b9d72..3a125fea74 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenType.java +++ b/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/TokenType.java @@ -1,4 +1,4 @@ -package org.togetherjava.formatter.tokenizer; +package org.togetherjava.tjbot.formatter.tokenizer; import java.util.regex.Pattern; diff --git a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenizationException.java b/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/TokenizationException.java similarity index 80% rename from formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenizationException.java rename to formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/TokenizationException.java index 25a822ba97..1ae6c3790b 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/tokenizer/TokenizationException.java +++ b/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/TokenizationException.java @@ -1,4 +1,4 @@ -package org.togetherjava.formatter.tokenizer; +package org.togetherjava.tjbot.formatter.tokenizer; /** * Exception that can occur when lexing diff --git a/formatter/src/main/java/org/togetherjava/formatter/util/LookaheadArrayDeque.java b/formatter/src/main/java/org/togetherjava/tjbot/formatter/util/LookaheadArrayDeque.java similarity index 94% rename from formatter/src/main/java/org/togetherjava/formatter/util/LookaheadArrayDeque.java rename to formatter/src/main/java/org/togetherjava/tjbot/formatter/util/LookaheadArrayDeque.java index 63afe2aa90..9ed1cfdf6d 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/util/LookaheadArrayDeque.java +++ b/formatter/src/main/java/org/togetherjava/tjbot/formatter/util/LookaheadArrayDeque.java @@ -1,4 +1,4 @@ -package org.togetherjava.formatter.util; +package org.togetherjava.tjbot.formatter.util; import java.util.ArrayDeque; import java.util.ArrayList; diff --git a/formatter/src/main/java/org/togetherjava/formatter/util/LookaheadQueue.java b/formatter/src/main/java/org/togetherjava/tjbot/formatter/util/LookaheadQueue.java similarity index 82% rename from formatter/src/main/java/org/togetherjava/formatter/util/LookaheadQueue.java rename to formatter/src/main/java/org/togetherjava/tjbot/formatter/util/LookaheadQueue.java index 4ff34ced98..d72a4df9d7 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/util/LookaheadQueue.java +++ b/formatter/src/main/java/org/togetherjava/tjbot/formatter/util/LookaheadQueue.java @@ -1,4 +1,4 @@ -package org.togetherjava.formatter.util; +package org.togetherjava.tjbot.formatter.util; import java.util.Queue; diff --git a/formatter/src/main/java/org/togetherjava/formatter/util/SkippableLookaheadArrayDeque.java b/formatter/src/main/java/org/togetherjava/tjbot/formatter/util/SkippableLookaheadArrayDeque.java similarity index 95% rename from formatter/src/main/java/org/togetherjava/formatter/util/SkippableLookaheadArrayDeque.java rename to formatter/src/main/java/org/togetherjava/tjbot/formatter/util/SkippableLookaheadArrayDeque.java index d4fdd931b9..662cdd3033 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/util/SkippableLookaheadArrayDeque.java +++ b/formatter/src/main/java/org/togetherjava/tjbot/formatter/util/SkippableLookaheadArrayDeque.java @@ -1,4 +1,4 @@ -package org.togetherjava.formatter.util; +package org.togetherjava.tjbot.formatter.util; import java.util.ArrayList; import java.util.Collection; diff --git a/formatter/src/main/java/org/togetherjava/formatter/util/SkippableLookaheadQueue.java b/formatter/src/main/java/org/togetherjava/tjbot/formatter/util/SkippableLookaheadQueue.java similarity index 76% rename from formatter/src/main/java/org/togetherjava/formatter/util/SkippableLookaheadQueue.java rename to formatter/src/main/java/org/togetherjava/tjbot/formatter/util/SkippableLookaheadQueue.java index ba4ed37361..b7991ac2d4 100644 --- a/formatter/src/main/java/org/togetherjava/formatter/util/SkippableLookaheadQueue.java +++ b/formatter/src/main/java/org/togetherjava/tjbot/formatter/util/SkippableLookaheadQueue.java @@ -1,4 +1,4 @@ -package org.togetherjava.formatter.util; +package org.togetherjava.tjbot.formatter.util; import java.util.function.Predicate; diff --git a/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java b/formatter/src/test/java/org/togetherjava/tjbot/formatter/FormatterTest.java similarity index 98% rename from formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java rename to formatter/src/test/java/org/togetherjava/tjbot/formatter/FormatterTest.java index 34be44394a..3366c06edb 100644 --- a/formatter/src/test/java/org/togetherjava/formatter/FormatterTest.java +++ b/formatter/src/test/java/org/togetherjava/tjbot/formatter/FormatterTest.java @@ -1,4 +1,4 @@ -package org.togetherjava.formatter; +package org.togetherjava.tjbot.formatter; import static org.junit.jupiter.api.Assertions.*; @@ -6,7 +6,7 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; -import org.togetherjava.formatter.tokenizer.Lexer; +import org.togetherjava.tjbot.formatter.tokenizer.Lexer; /** * @author illuminator3 diff --git a/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java b/formatter/src/test/java/org/togetherjava/tjbot/formatter/tokenizer/LexerTest.java similarity index 97% rename from formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java rename to formatter/src/test/java/org/togetherjava/tjbot/formatter/tokenizer/LexerTest.java index d525caef24..48c3f89796 100644 --- a/formatter/src/test/java/org/togetherjava/formatter/tokenizer/LexerTest.java +++ b/formatter/src/test/java/org/togetherjava/tjbot/formatter/tokenizer/LexerTest.java @@ -1,4 +1,4 @@ -package org.togetherjava.formatter.tokenizer; +package org.togetherjava.tjbot.formatter.tokenizer; import static org.junit.jupiter.api.Assertions.*; diff --git a/logviewer/src/main/java/org/togetherjava/logwatcher/Application.java b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/Application.java similarity index 80% rename from logviewer/src/main/java/org/togetherjava/logwatcher/Application.java rename to logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/Application.java index 81f34b1bc0..99104def50 100644 --- a/logviewer/src/main/java/org/togetherjava/logwatcher/Application.java +++ b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/Application.java @@ -1,4 +1,4 @@ -package org.togetherjava.logwatcher; +package org.togetherjava.tjbot.logwatcher; import com.vaadin.flow.component.dependency.NpmPackage; import com.vaadin.flow.component.page.AppShellConfigurator; @@ -10,7 +10,9 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; -import org.togetherjava.logwatcher.config.Config; +import org.togetherjava.tjbot.logwatcher.config.Config; +import org.togetherjava.tjbot.logwatcher.logs.LogREST; +import org.togetherjava.tjbot.logwatcher.oauth.OAuth2LoginConfig; import org.vaadin.artur.helpers.LaunchUtil; /** @@ -19,11 +21,11 @@ *

* You can see the Views you can see in your Browser at {@link org.togetherjava.logwatcher.views} *

- * Log-Event's are captured by the REST-API at {@link org.togetherjava.logwatcher.logs.LogREST} + * Log-Event's are captured by the REST-API at {@link LogREST} *

- * Security/OAuth2 Config at {@link org.togetherjava.logwatcher.oauth.OAuth2LoginConfig} + * Security/OAuth2 Config at {@link OAuth2LoginConfig} *

- * And the initial Config at {@link org.togetherjava.logwatcher.config.Config} + * And the initial Config at {@link Config} */ @SpringBootApplication(exclude = {R2dbcAutoConfiguration.class}) @Theme(value = "myapp") diff --git a/logviewer/src/main/java/org/togetherjava/logwatcher/DatabaseProvider.java b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/DatabaseProvider.java similarity index 94% rename from logviewer/src/main/java/org/togetherjava/logwatcher/DatabaseProvider.java rename to logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/DatabaseProvider.java index 3be226037e..87d7469ace 100644 --- a/logviewer/src/main/java/org/togetherjava/logwatcher/DatabaseProvider.java +++ b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/DatabaseProvider.java @@ -1,4 +1,4 @@ -package org.togetherjava.logwatcher; +package org.togetherjava.tjbot.logwatcher; import org.slf4j.LoggerFactory; import org.springframework.beans.FatalBeanException; @@ -6,7 +6,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; -import org.togetherjava.logwatcher.config.Config; +import org.togetherjava.tjbot.logwatcher.config.Config; import org.togetherjava.tjbot.db.Database; import java.io.IOException; diff --git a/logviewer/src/main/java/org/togetherjava/logwatcher/accesscontrol/AllowedRoles.java b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/accesscontrol/AllowedRoles.java similarity index 87% rename from logviewer/src/main/java/org/togetherjava/logwatcher/accesscontrol/AllowedRoles.java rename to logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/accesscontrol/AllowedRoles.java index ab1ec4eccc..4b3ce22ece 100644 --- a/logviewer/src/main/java/org/togetherjava/logwatcher/accesscontrol/AllowedRoles.java +++ b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/accesscontrol/AllowedRoles.java @@ -1,4 +1,4 @@ -package org.togetherjava.logwatcher.accesscontrol; +package org.togetherjava.tjbot.logwatcher.accesscontrol; import java.lang.annotation.Retention; import java.lang.annotation.Target; diff --git a/logviewer/src/main/java/org/togetherjava/logwatcher/accesscontrol/Role.java b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/accesscontrol/Role.java similarity index 94% rename from logviewer/src/main/java/org/togetherjava/logwatcher/accesscontrol/Role.java rename to logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/accesscontrol/Role.java index 29ab843411..364474fbf3 100644 --- a/logviewer/src/main/java/org/togetherjava/logwatcher/accesscontrol/Role.java +++ b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/accesscontrol/Role.java @@ -1,4 +1,4 @@ -package org.togetherjava.logwatcher.accesscontrol; +package org.togetherjava.tjbot.logwatcher.accesscontrol; import java.util.Arrays; import java.util.EnumSet; diff --git a/logviewer/src/main/java/org/togetherjava/logwatcher/config/Config.java b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/config/Config.java similarity index 98% rename from logviewer/src/main/java/org/togetherjava/logwatcher/config/Config.java rename to logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/config/Config.java index 2a4c33b1b0..f19cad897e 100644 --- a/logviewer/src/main/java/org/togetherjava/logwatcher/config/Config.java +++ b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/config/Config.java @@ -1,4 +1,4 @@ -package org.togetherjava.logwatcher.config; +package org.togetherjava.tjbot.logwatcher.config; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/logviewer/src/main/java/org/togetherjava/logwatcher/constants/LogEventsConstants.java b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/constants/LogEventsConstants.java similarity index 93% rename from logviewer/src/main/java/org/togetherjava/logwatcher/constants/LogEventsConstants.java rename to logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/constants/LogEventsConstants.java index b6e5becb9b..45e46e4730 100644 --- a/logviewer/src/main/java/org/togetherjava/logwatcher/constants/LogEventsConstants.java +++ b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/constants/LogEventsConstants.java @@ -1,4 +1,4 @@ -package org.togetherjava.logwatcher.constants; +package org.togetherjava.tjbot.logwatcher.constants; /** * Constant Class for Logevents diff --git a/logviewer/src/main/java/org/togetherjava/logwatcher/constants/UserConstants.java b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/constants/UserConstants.java similarity index 82% rename from logviewer/src/main/java/org/togetherjava/logwatcher/constants/UserConstants.java rename to logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/constants/UserConstants.java index 859a15ae9a..0532c11229 100644 --- a/logviewer/src/main/java/org/togetherjava/logwatcher/constants/UserConstants.java +++ b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/constants/UserConstants.java @@ -1,4 +1,4 @@ -package org.togetherjava.logwatcher.constants; +package org.togetherjava.tjbot.logwatcher.constants; /** * Gathers all static Values regarding Users diff --git a/logviewer/src/main/java/org/togetherjava/logwatcher/entities/InstantWrapper.java b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/entities/InstantWrapper.java similarity index 97% rename from logviewer/src/main/java/org/togetherjava/logwatcher/entities/InstantWrapper.java rename to logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/entities/InstantWrapper.java index 824774e73f..b32b114089 100644 --- a/logviewer/src/main/java/org/togetherjava/logwatcher/entities/InstantWrapper.java +++ b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/entities/InstantWrapper.java @@ -1,4 +1,4 @@ -package org.togetherjava.logwatcher.entities; +package org.togetherjava.tjbot.logwatcher.entities; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/logviewer/src/main/java/org/togetherjava/logwatcher/entities/LogEvent.java b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/entities/LogEvent.java similarity index 98% rename from logviewer/src/main/java/org/togetherjava/logwatcher/entities/LogEvent.java rename to logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/entities/LogEvent.java index 49c7ebb3e0..fcf80c671d 100644 --- a/logviewer/src/main/java/org/togetherjava/logwatcher/entities/LogEvent.java +++ b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/entities/LogEvent.java @@ -1,4 +1,4 @@ -package org.togetherjava.logwatcher.entities; +package org.togetherjava.tjbot.logwatcher.entities; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; diff --git a/logviewer/src/main/java/org/togetherjava/logwatcher/entities/UserWrapper.java b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/entities/UserWrapper.java similarity index 93% rename from logviewer/src/main/java/org/togetherjava/logwatcher/entities/UserWrapper.java rename to logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/entities/UserWrapper.java index e5b6731ba4..8bd55eefda 100644 --- a/logviewer/src/main/java/org/togetherjava/logwatcher/entities/UserWrapper.java +++ b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/entities/UserWrapper.java @@ -1,6 +1,6 @@ -package org.togetherjava.logwatcher.entities; +package org.togetherjava.tjbot.logwatcher.entities; -import org.togetherjava.logwatcher.accesscontrol.Role; +import org.togetherjava.tjbot.logwatcher.accesscontrol.Role; import java.io.Serial; import java.io.Serializable; diff --git a/logviewer/src/main/java/org/togetherjava/logwatcher/logs/LogREST.java b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/logs/LogREST.java similarity index 87% rename from logviewer/src/main/java/org/togetherjava/logwatcher/logs/LogREST.java rename to logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/logs/LogREST.java index e98f1a34b3..6c490c1970 100644 --- a/logviewer/src/main/java/org/togetherjava/logwatcher/logs/LogREST.java +++ b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/logs/LogREST.java @@ -1,11 +1,11 @@ -package org.togetherjava.logwatcher.logs; +package org.togetherjava.tjbot.logwatcher.logs; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; -import org.togetherjava.logwatcher.entities.LogEvent; -import org.togetherjava.logwatcher.watcher.StreamWatcher; +import org.togetherjava.tjbot.logwatcher.entities.LogEvent; +import org.togetherjava.tjbot.logwatcher.watcher.StreamWatcher; import org.togetherjava.tjbot.db.generated.tables.pojos.Logevents; import java.time.LocalDateTime; diff --git a/logviewer/src/main/java/org/togetherjava/logwatcher/logs/LogRepository.java b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/logs/LogRepository.java similarity index 89% rename from logviewer/src/main/java/org/togetherjava/logwatcher/logs/LogRepository.java rename to logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/logs/LogRepository.java index ad1a88a7e6..baea561dad 100644 --- a/logviewer/src/main/java/org/togetherjava/logwatcher/logs/LogRepository.java +++ b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/logs/LogRepository.java @@ -1,4 +1,4 @@ -package org.togetherjava.logwatcher.logs; +package org.togetherjava.tjbot.logwatcher.logs; import org.togetherjava.tjbot.db.generated.tables.pojos.Logevents; diff --git a/logviewer/src/main/java/org/togetherjava/logwatcher/logs/LogRepositoryImpl.java b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/logs/LogRepositoryImpl.java similarity index 97% rename from logviewer/src/main/java/org/togetherjava/logwatcher/logs/LogRepositoryImpl.java rename to logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/logs/LogRepositoryImpl.java index 340266cd25..4e484731f7 100644 --- a/logviewer/src/main/java/org/togetherjava/logwatcher/logs/LogRepositoryImpl.java +++ b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/logs/LogRepositoryImpl.java @@ -1,4 +1,4 @@ -package org.togetherjava.logwatcher.logs; +package org.togetherjava.tjbot.logwatcher.logs; import org.springframework.stereotype.Repository; import org.togetherjava.tjbot.db.Database; diff --git a/logviewer/src/main/java/org/togetherjava/logwatcher/oauth/OAuth2LoginConfig.java b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/oauth/OAuth2LoginConfig.java similarity index 97% rename from logviewer/src/main/java/org/togetherjava/logwatcher/oauth/OAuth2LoginConfig.java rename to logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/oauth/OAuth2LoginConfig.java index 9d9d5a5f33..eb9bfc92a7 100644 --- a/logviewer/src/main/java/org/togetherjava/logwatcher/oauth/OAuth2LoginConfig.java +++ b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/oauth/OAuth2LoginConfig.java @@ -1,4 +1,4 @@ -package org.togetherjava.logwatcher.oauth; +package org.togetherjava.tjbot.logwatcher.oauth; import com.vaadin.flow.spring.security.VaadinWebSecurityConfigurerAdapter; import org.springframework.context.annotation.Bean; @@ -16,7 +16,7 @@ import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.core.ClientAuthenticationMethod; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; -import org.togetherjava.logwatcher.config.Config; +import org.togetherjava.tjbot.logwatcher.config.Config; /** * Configures Spring Security so that we use Discord-OAuth2 as the identity provider diff --git a/logviewer/src/main/java/org/togetherjava/logwatcher/users/AuthenticatedUser.java b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/users/AuthenticatedUser.java similarity index 97% rename from logviewer/src/main/java/org/togetherjava/logwatcher/users/AuthenticatedUser.java rename to logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/users/AuthenticatedUser.java index 472f560b9f..eaf128785d 100644 --- a/logviewer/src/main/java/org/togetherjava/logwatcher/users/AuthenticatedUser.java +++ b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/users/AuthenticatedUser.java @@ -1,4 +1,4 @@ -package org.togetherjava.logwatcher.users; +package org.togetherjava.tjbot.logwatcher.users; import com.vaadin.flow.component.UI; import com.vaadin.flow.server.VaadinServletRequest; @@ -7,7 +7,7 @@ import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; import org.springframework.stereotype.Component; -import org.togetherjava.logwatcher.accesscontrol.Role; +import org.togetherjava.tjbot.logwatcher.accesscontrol.Role; import org.togetherjava.tjbot.db.generated.tables.pojos.Users; import java.util.Objects; diff --git a/logviewer/src/main/java/org/togetherjava/logwatcher/users/UserDetailsServiceImpl.java b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/users/UserDetailsServiceImpl.java similarity index 93% rename from logviewer/src/main/java/org/togetherjava/logwatcher/users/UserDetailsServiceImpl.java rename to logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/users/UserDetailsServiceImpl.java index 2aac79f95c..ad8a7e6b8d 100644 --- a/logviewer/src/main/java/org/togetherjava/logwatcher/users/UserDetailsServiceImpl.java +++ b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/users/UserDetailsServiceImpl.java @@ -1,4 +1,4 @@ -package org.togetherjava.logwatcher.users; +package org.togetherjava.tjbot.logwatcher.users; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; @@ -6,8 +6,8 @@ import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; -import org.togetherjava.logwatcher.accesscontrol.Role; -import org.togetherjava.logwatcher.config.Config; +import org.togetherjava.tjbot.logwatcher.accesscontrol.Role; +import org.togetherjava.tjbot.logwatcher.config.Config; import org.togetherjava.tjbot.db.generated.tables.pojos.Users; import java.util.List; diff --git a/logviewer/src/main/java/org/togetherjava/logwatcher/users/UserRepository.java b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/users/UserRepository.java similarity index 93% rename from logviewer/src/main/java/org/togetherjava/logwatcher/users/UserRepository.java rename to logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/users/UserRepository.java index 7135b4c2c5..de78e71d8a 100644 --- a/logviewer/src/main/java/org/togetherjava/logwatcher/users/UserRepository.java +++ b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/users/UserRepository.java @@ -1,6 +1,6 @@ -package org.togetherjava.logwatcher.users; +package org.togetherjava.tjbot.logwatcher.users; -import org.togetherjava.logwatcher.accesscontrol.Role; +import org.togetherjava.tjbot.logwatcher.accesscontrol.Role; import org.togetherjava.tjbot.db.generated.tables.pojos.Users; import java.util.List; diff --git a/logviewer/src/main/java/org/togetherjava/logwatcher/users/UserRepositoryImpl.java b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/users/UserRepositoryImpl.java similarity index 96% rename from logviewer/src/main/java/org/togetherjava/logwatcher/users/UserRepositoryImpl.java rename to logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/users/UserRepositoryImpl.java index 44b18e4d51..028357f90d 100644 --- a/logviewer/src/main/java/org/togetherjava/logwatcher/users/UserRepositoryImpl.java +++ b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/users/UserRepositoryImpl.java @@ -1,7 +1,7 @@ -package org.togetherjava.logwatcher.users; +package org.togetherjava.tjbot.logwatcher.users; import org.springframework.stereotype.Component; -import org.togetherjava.logwatcher.accesscontrol.Role; +import org.togetherjava.tjbot.logwatcher.accesscontrol.Role; import org.togetherjava.tjbot.db.Database; import org.togetherjava.tjbot.db.generated.tables.Userroles; import org.togetherjava.tjbot.db.generated.tables.pojos.Users; diff --git a/logviewer/src/main/java/org/togetherjava/logwatcher/util/LogReader.java b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/util/LogReader.java similarity index 92% rename from logviewer/src/main/java/org/togetherjava/logwatcher/util/LogReader.java rename to logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/util/LogReader.java index bbc4b2b329..9aadc236af 100644 --- a/logviewer/src/main/java/org/togetherjava/logwatcher/util/LogReader.java +++ b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/util/LogReader.java @@ -1,7 +1,7 @@ -package org.togetherjava.logwatcher.util; +package org.togetherjava.tjbot.logwatcher.util; import org.springframework.stereotype.Component; -import org.togetherjava.logwatcher.config.Config; +import org.togetherjava.tjbot.logwatcher.config.Config; import java.io.IOException; import java.io.UncheckedIOException; diff --git a/logviewer/src/main/java/org/togetherjava/logwatcher/util/NotificationUtils.java b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/util/NotificationUtils.java similarity index 95% rename from logviewer/src/main/java/org/togetherjava/logwatcher/util/NotificationUtils.java rename to logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/util/NotificationUtils.java index aa03e57607..e2968b1165 100644 --- a/logviewer/src/main/java/org/togetherjava/logwatcher/util/NotificationUtils.java +++ b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/util/NotificationUtils.java @@ -1,4 +1,4 @@ -package org.togetherjava.logwatcher.util; +package org.togetherjava.tjbot.logwatcher.util; import com.vaadin.flow.component.notification.Notification; import com.vaadin.flow.component.notification.NotificationVariant; diff --git a/logviewer/src/main/java/org/togetherjava/logwatcher/views/MainLayout.java b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/views/MainLayout.java similarity index 92% rename from logviewer/src/main/java/org/togetherjava/logwatcher/views/MainLayout.java rename to logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/views/MainLayout.java index 03f1e4d1b3..496ee5aad0 100644 --- a/logviewer/src/main/java/org/togetherjava/logwatcher/views/MainLayout.java +++ b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/views/MainLayout.java @@ -1,4 +1,4 @@ -package org.togetherjava.logwatcher.views; +package org.togetherjava.tjbot.logwatcher.views; import com.google.common.collect.Sets; import com.vaadin.flow.component.Component; @@ -11,12 +11,12 @@ import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.RouterLink; import org.slf4j.LoggerFactory; -import org.togetherjava.logwatcher.accesscontrol.AllowedRoles; -import org.togetherjava.logwatcher.accesscontrol.Role; -import org.togetherjava.logwatcher.users.AuthenticatedUser; -import org.togetherjava.logwatcher.views.logs.LogsView; -import org.togetherjava.logwatcher.views.logs.StreamedView; -import org.togetherjava.logwatcher.views.usermanagement.UserManagement; +import org.togetherjava.tjbot.logwatcher.accesscontrol.AllowedRoles; +import org.togetherjava.tjbot.logwatcher.accesscontrol.Role; +import org.togetherjava.tjbot.logwatcher.users.AuthenticatedUser; +import org.togetherjava.tjbot.logwatcher.views.logs.LogsView; +import org.togetherjava.tjbot.logwatcher.views.logs.StreamedView; +import org.togetherjava.tjbot.logwatcher.views.usermanagement.UserManagement; import org.togetherjava.tjbot.db.generated.tables.pojos.Users; import java.util.List; diff --git a/logviewer/src/main/java/org/togetherjava/logwatcher/views/logs/LogsView.java b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/views/logs/LogsView.java similarity index 91% rename from logviewer/src/main/java/org/togetherjava/logwatcher/views/logs/LogsView.java rename to logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/views/logs/LogsView.java index f9931bcd8a..1606b9ae2b 100644 --- a/logviewer/src/main/java/org/togetherjava/logwatcher/views/logs/LogsView.java +++ b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/views/logs/LogsView.java @@ -1,4 +1,4 @@ -package org.togetherjava.logwatcher.views.logs; +package org.togetherjava.tjbot.logwatcher.views.logs; import com.vaadin.flow.component.HasValue; import com.vaadin.flow.component.combobox.ComboBox; @@ -10,11 +10,11 @@ import com.vaadin.flow.router.Route; import com.vaadin.flow.router.RouteAlias; import org.slf4j.LoggerFactory; -import org.togetherjava.logwatcher.accesscontrol.AllowedRoles; -import org.togetherjava.logwatcher.accesscontrol.Role; -import org.togetherjava.logwatcher.util.LogReader; -import org.togetherjava.logwatcher.util.NotificationUtils; -import org.togetherjava.logwatcher.views.MainLayout; +import org.togetherjava.tjbot.logwatcher.accesscontrol.AllowedRoles; +import org.togetherjava.tjbot.logwatcher.accesscontrol.Role; +import org.togetherjava.tjbot.logwatcher.util.LogReader; +import org.togetherjava.tjbot.logwatcher.util.NotificationUtils; +import org.togetherjava.tjbot.logwatcher.views.MainLayout; import javax.annotation.security.PermitAll; import java.io.UncheckedIOException; diff --git a/logviewer/src/main/java/org/togetherjava/logwatcher/views/logs/StreamedView.java b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/views/logs/StreamedView.java similarity index 92% rename from logviewer/src/main/java/org/togetherjava/logwatcher/views/logs/StreamedView.java rename to logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/views/logs/StreamedView.java index cbba4409e2..86832424a0 100644 --- a/logviewer/src/main/java/org/togetherjava/logwatcher/views/logs/StreamedView.java +++ b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/views/logs/StreamedView.java @@ -1,4 +1,4 @@ -package org.togetherjava.logwatcher.views.logs; +package org.togetherjava.tjbot.logwatcher.views.logs; import com.vaadin.componentfactory.EnhancedDialog; import com.vaadin.flow.component.*; @@ -11,12 +11,12 @@ import com.vaadin.flow.router.Route; import com.vaadin.flow.server.SessionDestroyEvent; import com.vaadin.flow.server.VaadinService; -import org.togetherjava.logwatcher.accesscontrol.AllowedRoles; -import org.togetherjava.logwatcher.accesscontrol.Role; -import org.togetherjava.logwatcher.constants.LogEventsConstants; -import org.togetherjava.logwatcher.logs.LogRepository; -import org.togetherjava.logwatcher.views.MainLayout; -import org.togetherjava.logwatcher.watcher.StreamWatcher; +import org.togetherjava.tjbot.logwatcher.accesscontrol.AllowedRoles; +import org.togetherjava.tjbot.logwatcher.accesscontrol.Role; +import org.togetherjava.tjbot.logwatcher.constants.LogEventsConstants; +import org.togetherjava.tjbot.logwatcher.logs.LogRepository; +import org.togetherjava.tjbot.logwatcher.views.MainLayout; +import org.togetherjava.tjbot.logwatcher.watcher.StreamWatcher; import org.togetherjava.tjbot.db.generated.tables.pojos.Logevents; import org.vaadin.crudui.crud.impl.GridCrud; diff --git a/logviewer/src/main/java/org/togetherjava/logwatcher/views/usermanagement/UserManagement.java b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/views/usermanagement/UserManagement.java similarity index 94% rename from logviewer/src/main/java/org/togetherjava/logwatcher/views/usermanagement/UserManagement.java rename to logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/views/usermanagement/UserManagement.java index 3087810b38..45d6f6b69b 100644 --- a/logviewer/src/main/java/org/togetherjava/logwatcher/views/usermanagement/UserManagement.java +++ b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/views/usermanagement/UserManagement.java @@ -1,4 +1,4 @@ -package org.togetherjava.logwatcher.views.usermanagement; +package org.togetherjava.tjbot.logwatcher.views.usermanagement; import com.vaadin.componentfactory.EnhancedDialog; import com.vaadin.flow.component.ClickEvent; @@ -16,12 +16,12 @@ import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import org.slf4j.LoggerFactory; -import org.togetherjava.logwatcher.accesscontrol.AllowedRoles; -import org.togetherjava.logwatcher.accesscontrol.Role; -import org.togetherjava.logwatcher.entities.UserWrapper; -import org.togetherjava.logwatcher.users.UserRepository; -import org.togetherjava.logwatcher.util.NotificationUtils; -import org.togetherjava.logwatcher.views.MainLayout; +import org.togetherjava.tjbot.logwatcher.accesscontrol.AllowedRoles; +import org.togetherjava.tjbot.logwatcher.accesscontrol.Role; +import org.togetherjava.tjbot.logwatcher.entities.UserWrapper; +import org.togetherjava.tjbot.logwatcher.users.UserRepository; +import org.togetherjava.tjbot.logwatcher.util.NotificationUtils; +import org.togetherjava.tjbot.logwatcher.views.MainLayout; import org.togetherjava.tjbot.db.DatabaseException; import org.togetherjava.tjbot.db.generated.tables.pojos.Users; diff --git a/logviewer/src/main/java/org/togetherjava/logwatcher/watcher/StreamWatcher.java b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/watcher/StreamWatcher.java similarity index 96% rename from logviewer/src/main/java/org/togetherjava/logwatcher/watcher/StreamWatcher.java rename to logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/watcher/StreamWatcher.java index 2600f990a7..3507b5df48 100644 --- a/logviewer/src/main/java/org/togetherjava/logwatcher/watcher/StreamWatcher.java +++ b/logviewer/src/main/java/org/togetherjava/tjbot/logwatcher/watcher/StreamWatcher.java @@ -1,4 +1,4 @@ -package org.togetherjava.logwatcher.watcher; +package org.togetherjava.tjbot.logwatcher.watcher; import org.slf4j.LoggerFactory; From 37e54e5f063623c6e22e20ad35f80c32c51e99ce Mon Sep 17 00:00:00 2001 From: borgrel <46281578+borgrel@users.noreply.github.com> Date: Tue, 19 Oct 2021 10:33:30 +0200 Subject: [PATCH 02/10] Propogated onReady event from CommandSystem to SlashCommand --- .../tjbot/commands/SlashCommand.java | 34 ++++++++++++++++--- .../tjbot/commands/SlashCommandAdapter.java | 7 ++++ .../tjbot/commands/system/CommandSystem.java | 5 +++ 3 files changed, 42 insertions(+), 4 deletions(-) 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 0960b223e7..dd88e90f9a 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommand.java @@ -1,6 +1,7 @@ package org.togetherjava.tjbot.commands; import net.dv8tion.jda.api.entities.Emoji; +import net.dv8tion.jda.api.events.ReadyEvent; import net.dv8tion.jda.api.events.interaction.ButtonClickEvent; import net.dv8tion.jda.api.events.interaction.SelectionMenuEvent; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; @@ -8,6 +9,7 @@ import net.dv8tion.jda.api.interactions.components.ButtonStyle; import net.dv8tion.jda.api.interactions.components.ComponentInteraction; import org.jetbrains.annotations.NotNull; +import org.togetherjava.tjbot.commands.system.ComponentIds; import java.util.List; @@ -88,6 +90,27 @@ public interface SlashCommand { @NotNull CommandData getData(); + /** + * Triggered by the command system after system startup is complete. This can be used for + * initialisation actions that cannot occur during construction. + *

+ * This method may be called multi-threaded. There is no guarantee as to the order that commands + * will get called and there is no guarantee which thread they will be called on or even that + * they will be called by the same thread. + *

+ * There is also no guarantee that slashCommands will be registered on guilds before this is + * called. Do not use this method to interact with slashCommands. + *

+ * Details are available in the given event and the event also enables implementations to + * respond to it. + *

+ * This method will be called in a multi-threaded context and the event may not be hold valid + * forever. + * + * @param event the event that triggered this + */ + void onReady(@NotNull ReadyEvent event); + /** * Triggered by the command system when a slash command corresponding to this implementation * (based on {@link #getData()} has been triggered. @@ -99,6 +122,10 @@ public interface SlashCommand { * Details are available in the given event and the event also enables implementations to * respond to it. *

+ * The helper {@link org.togetherjava.tjbot.commands.system.ComponentIds} can be used to + * generate valid IDs. Alternatively, if {@link SlashCommandAdapter} has been extended, it also + * offers a handy {@link SlashCommandAdapter#generateComponentId(String...)} method to ease the + * flow. *

* Buttons or menus have to be created with component ID (see * {@link ComponentInteraction#getComponentId()}, @@ -121,10 +148,9 @@ public interface SlashCommand { * {@link #onButtonClick(ButtonClickEvent, List)}, * {@link #onSelectionMenu(SelectionMenuEvent, List)}). *

- * The helper {@link org.togetherjava.tjbot.commands.system.ComponentIds} can be used to - * generate valid IDs. Alternatively, if {@link SlashCommandAdapter} has been extended, it also - * offers a handy {@link SlashCommandAdapter#generateComponentId(String...)} method to ease the - * flow. + * The helper {@link ComponentIds} can be used to generate valid IDs. Alternatively, if + * {@link SlashCommandAdapter} has been extended, it also offers a handy + * {@link SlashCommandAdapter#generateComponentId(String...)} method to ease the flow. *

*

* This method will be called in a multi-threaded context and the event may not be hold valid 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 88a2763b74..a698611196 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommandAdapter.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommandAdapter.java @@ -1,6 +1,7 @@ package org.togetherjava.tjbot.commands; import com.fasterxml.jackson.core.JsonProcessingException; +import net.dv8tion.jda.api.events.ReadyEvent; import net.dv8tion.jda.api.events.interaction.ButtonClickEvent; import net.dv8tion.jda.api.events.interaction.SelectionMenuEvent; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; @@ -97,6 +98,12 @@ protected SlashCommandAdapter(@NotNull String name, @NotNull String description, return data; } + @SuppressWarnings("NoopMethodInAbstractClass") + @Override + public void onReady(@NotNull ReadyEvent event) { + // Adapter does not react by default, subclasses may change this behavior + } + @SuppressWarnings("NoopMethodInAbstractClass") @Override public void onButtonClick(@NotNull ButtonClickEvent event, @NotNull List args) { diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/system/CommandSystem.java b/application/src/main/java/org/togetherjava/tjbot/commands/system/CommandSystem.java index b87d0ddc0b..e3bd22ff28 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/system/CommandSystem.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/system/CommandSystem.java @@ -89,6 +89,11 @@ public void onReady(@NotNull ReadyEvent event) { // NOTE We do not have to wait for reload to complete for the command system to be ready // itself logger.debug("Command system is now ready"); + + // Propagate the onReady event to all commands + // NOTE 'registerReloadCommands' will not be finished running, this does not wait for it + nameToSlashCommands.values() + .forEach(command -> COMMAND_SERVICE.execute(() -> command.onReady(event))); } @Override From 4bb7ee4bc1a108bb4b57d6e6fc11e9a93d318d90 Mon Sep 17 00:00:00 2001 From: java-coding-prodigy <85149944+java-coding-prodigy@users.noreply.github.com> Date: Tue, 19 Oct 2021 14:07:11 +0530 Subject: [PATCH 03/10] Adding a `/tex` command for LaTeX support, based on the lib jlatexmath --- application/build.gradle | 4 + .../togetherjava/tjbot/commands/Commands.java | 4 +- .../commands/mathcommands/TeXCommand.java | 106 ++++++++++++++++++ 3 files changed, 113 insertions(+), 1 deletion(-) create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/mathcommands/TeXCommand.java diff --git a/application/build.gradle b/application/build.gradle index e8fde55789..ab2815d6fb 100644 --- a/application/build.gradle +++ b/application/build.gradle @@ -53,6 +53,10 @@ dependencies { implementation 'org.jooq:jooq:3.15.3' + implementation 'org.scilab.forge:jlatexmath:1.0.7' + 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.core:jackson-databind:2.13.0' diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java b/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java index 88d6f4dd6e..f05083e745 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java @@ -3,6 +3,7 @@ import org.jetbrains.annotations.NotNull; import org.togetherjava.tjbot.commands.basic.DatabaseCommand; import org.togetherjava.tjbot.commands.basic.PingCommand; +import org.togetherjava.tjbot.commands.mathcommands.TeXCommand; import org.togetherjava.tjbot.db.Database; import java.util.Collection; @@ -26,6 +27,7 @@ public enum Commands { * generally should be avoided. * * @param database the database of the application, which commands can use to persist data + * * @return a collection of all slash commands */ public static @NotNull Collection createSlashCommands( @@ -33,6 +35,6 @@ public enum Commands { // NOTE The command system can add special system relevant commands also by itself, // hence this list may not necessarily represent the full list of all commands actually // available. - return List.of(new PingCommand(), new DatabaseCommand(database)); + return List.of(new PingCommand(), new DatabaseCommand(database), new TeXCommand()); } } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/mathcommands/TeXCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/mathcommands/TeXCommand.java new file mode 100644 index 0000000000..9f45417653 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/mathcommands/TeXCommand.java @@ -0,0 +1,106 @@ +package org.togetherjava.tjbot.commands.mathcommands; + +import net.dv8tion.jda.api.events.interaction.ButtonClickEvent; +import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; +import net.dv8tion.jda.api.interactions.commands.OptionType; +import net.dv8tion.jda.api.interactions.components.Button; +import net.dv8tion.jda.api.interactions.components.ButtonStyle; +import org.jetbrains.annotations.NotNull; +import org.scilab.forge.jlatexmath.ParseException; +import org.scilab.forge.jlatexmath.TeXConstants; +import org.scilab.forge.jlatexmath.TeXFormula; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.SlashCommandAdapter; +import org.togetherjava.tjbot.commands.SlashCommandVisibility; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.List; +import java.util.Objects; + +/** + * Implementation of a tex command which takes a string and renders an image corresponding to the + * mathematical expression in that string. + *

+ * The implemented command is {@code /tex}. This has a single option called {@code latex} which is a + * string. If it is invalid latex or there is an error in rendering the image, it displays an error + * message. + */ + +public class TeXCommand extends SlashCommandAdapter { + + private static final String LATEX_OPTION = "latex"; + private static final String RENDERING_ERROR = "There was an error generating the image"; + private static final float DEFAULT_IMAGE_SIZE = 40F; + private static final Color BACKGROUND_COLOR = Color.decode("#383C3C"); + private static final Color FOREGROUND_COLOR = Color.decode("#FFFFFF"); + private static final Logger logger = LoggerFactory.getLogger(TeXCommand.class); + + /** + * Creates a new Instance. + */ + public TeXCommand() { + super("tex", + "This command accepts a latex expression and generates an image corresponding to it.", + SlashCommandVisibility.GUILD); + getData().addOption(OptionType.STRING, LATEX_OPTION, + "The latex which is rendered as an image", true); + } + + @Override + public void onSlashCommand(@NotNull final SlashCommandEvent event) { + String latex = Objects.requireNonNull(event.getOption(LATEX_OPTION)).getAsString(); + String userID = (Objects.requireNonNull(event.getMember()).getId()); + TeXFormula formula; + try { + formula = new TeXFormula(latex); + } catch (ParseException e) { + event.reply("That is an invalid latex").setEphemeral(true).queue(); + return; + } + event.deferReply().queue(); + Image image = formula.createBufferedImage(TeXConstants.STYLE_DISPLAY, DEFAULT_IMAGE_SIZE, + FOREGROUND_COLOR, BACKGROUND_COLOR); + if (image.getWidth(null) == -1 || image.getHeight(null) == -1) { + event.getHook().setEphemeral(true).editOriginal(RENDERING_ERROR).queue(); + logger.warn( + "Unable to render latex, image does not have an accessible width or height. Formula was {}", + latex); + return; + } + BufferedImage renderedTextImage = new BufferedImage(image.getWidth(null), + image.getHeight(null), BufferedImage.TYPE_4BYTE_ABGR); + renderedTextImage.getGraphics().drawImage(image, 0, 0, null); + ByteArrayOutputStream renderedTextImageStream = new ByteArrayOutputStream(); + + try { + ImageIO.write(renderedTextImage, "png", renderedTextImageStream); + } catch (IOException e) { + event.getHook().setEphemeral(true).editOriginal(RENDERING_ERROR).queue(); + logger.warn( + "Unable to render latex, could not convert the image into an attachable form. Formula was {}", + latex, e); + return; + } + event.getHook() + .editOriginal(renderedTextImageStream.toByteArray(), "tex.png") + .setActionRow(Button.of(ButtonStyle.DANGER, generateComponentId(userID), "Delete")) + .queue(); + } + + @Override + public void onButtonClick(@NotNull final ButtonClickEvent event, + @NotNull final List args) { + if (!args.get(0).equals(Objects.requireNonNull(event.getMember()).getId())) { + event.reply("You are not the person who executed the command, you cannot do that") + .setEphemeral(true) + .queue(); + return; + } + event.getMessage().delete().queue(); + } +} From b126bae6c23ac8de28d5c1624efa55e498017d33 Mon Sep 17 00:00:00 2001 From: borgrel Date: Tue, 19 Oct 2021 11:14:22 +0200 Subject: [PATCH 04/10] Added framework for FreeCommand and ChannelStatus Added Util for ephemeral error messages Modified Config to load FreeChannel config Improved Javadocs Added test Status message Rebased onto development --- .../tjbot/commands/free/ChannelStatus.java | 70 ++++++++ .../tjbot/commands/free/FreeCommand.java | 166 ++++++++++++++++++ .../tjbot/commands/free/StatusMessage.java | 42 +++++ .../tjbot/commands/free/Util.java | 18 ++ .../org/togetherjava/tjbot/config/Config.java | 17 +- .../tjbot/config/FreeCommandConfig.java | 46 +++++ 6 files changed, 358 insertions(+), 1 deletion(-) create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/free/ChannelStatus.java create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/free/FreeCommand.java create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/free/StatusMessage.java create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/free/Util.java create mode 100644 application/src/main/java/org/togetherjava/tjbot/config/FreeCommandConfig.java diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/free/ChannelStatus.java b/application/src/main/java/org/togetherjava/tjbot/commands/free/ChannelStatus.java new file mode 100644 index 0000000000..81f3b68b60 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/free/ChannelStatus.java @@ -0,0 +1,70 @@ +package org.togetherjava.tjbot.commands.free; + +import org.jetbrains.annotations.NotNull; + +import java.util.Objects; + +public class ChannelStatus { + public static final boolean FREE = false; + public static final boolean BUSY = true; + + private static final String FREE_STATUS = ":green_circle:"; + private static final String BUSY_STATUS = ":red_circle:"; + + private final long channelID; + private boolean isBusy; + private String name; + + protected ChannelStatus(long id) { + channelID = id; + isBusy = true; + name = Long.toString(id); + } + + public boolean isBusy() { + return isBusy; + } + + public long getChannelID() { + return channelID; + } + + public @NotNull String getName() { + return name; + } + + public void setName(String name) { + this.name = Objects.requireNonNull(name); + } + + // todo make threadsafe? + protected void busy(boolean isBusy) { + this.isBusy = isBusy; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + ChannelStatus that = (ChannelStatus) o; + return channelID == that.channelID; + } + + @Override + public String toString() { + return "ChannelStatus{ %s is %s }".formatted(name, isBusy ? "busy" : "not busy"); + } + + public String toDiscord() { + return "%s\t%s".formatted(isBusy ? BUSY_STATUS : FREE_STATUS, name); + } + + @Override + public int hashCode() { + return Objects.hash(channelID); + } +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/free/FreeCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/free/FreeCommand.java new file mode 100644 index 0000000000..c10a7157b7 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/free/FreeCommand.java @@ -0,0 +1,166 @@ +package org.togetherjava.tjbot.commands.free; + +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.GuildChannel; +import net.dv8tion.jda.api.entities.TextChannel; +import net.dv8tion.jda.api.events.GenericEvent; +import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; +import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent; +import net.dv8tion.jda.api.hooks.EventListener; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.SlashCommandAdapter; +import org.togetherjava.tjbot.commands.SlashCommandVisibility; +import org.togetherjava.tjbot.config.Config; +import org.togetherjava.tjbot.config.FreeCommandConfig; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +// todo check if channel is valid before processing onSlashCommand (can SlashCommandVisibility be +// narrower than GUILD?) +// todo monitor all channels when list is empty? monitor none? (defaulting to all for testing) +// todo (use other emojis? use images?) +// todo add command to add/remove/status channels to monitor +// todo test if message is a reply and don't mark as busy if it is +// todo add button query to confirm that message is new question not additional info for existing +// discussion before marking as busy +// todo add scheduled tasks to check last message every 15mins and mark as free if 1hr (2hrs?) has +// passed + +/** + * Implementation of the free command. It is used to monitor a predefined list of channels and show + * users which ones are available for use and which are not. + *

+ * When a user posts a message in a channel that is being monitored that channel is automatically + * marked as busy until they post {@code /free} to notify the bot and other users that the channel + * is now available or after a preconfigured period of time has passed without any traffic. + *

+ * If any user posts a message that directly 'replies' to an existing message, in a monitored + * channel that is currently marked as free, the free status will remain. + *

+ * If a user starts typing in a channel where 2 or more users have posted multiple messages each, + * less than a configured time ago, they will receive an ephemeral message warning them that the + * channel is currently in use and that they should post in a free channel if they are trying to ask + * a question. + *

+ * A summary of the current status of those channels is displayed in a predefined channel. This + * channel may be one of the monitored channels however it is recommended that a different channel + * is used. + */ +public class FreeCommand extends SlashCommandAdapter implements EventListener { + private static final Logger logger = LoggerFactory.getLogger(FreeCommand.class); + private static final String FREE_COMMAND = "free"; + + // Map to store channel ID's, use Guild.getChannels() to guarantee order for display + private final Map channelsById; + private final Map guildToStatus; + + private boolean isRegistered; + + + /** + * Creates an instance of FreeCommand. + *

+ * This fetches configuration information from a json configuration file (see + * {@link FreeCommandConfig}) for further details. + */ + public FreeCommand() { + super(FREE_COMMAND, "marks this channel as free for another user to ask a question", + SlashCommandVisibility.GUILD); + + Collection config = Config.getInstance().getFreeCommandConfig(); + guildToStatus = config.stream() + .map(FreeCommandConfig::getStatusChannel) + // todo change Function.identity to JDA.getChannel.getGuild when viable. + .collect(Collectors.toMap(Function.identity(), Function.identity())); + channelsById = config.stream() + .map(FreeCommandConfig::getMonitoredChannels) + .flatMap(Collection::stream) + .map(ChannelStatus::new) + .collect(Collectors.toMap(ChannelStatus::getChannelID, Function.identity())); + + logger.debug("Config loaded: Display on {} and monitor {}", guildToStatus, channelsById); + isRegistered = false; + } + + /** + * When triggered with {@code /free} this will mark a help channel as not busy (free for another + * person to use). + *

+ * If this is called on from a channel that was not configured for monitoring (see + * {@link FreeCommandConfig}) the user will receive an ephemeral message stating such. + * + * @param event the event that triggered this + */ + @Override + public void onSlashCommand(@NotNull SlashCommandEvent event) { + logger.debug("/free used by {} on channel {}", event.getUser().getName(), + event.getChannel().getName()); + if (!isRegistered) { + event.getJDA().addEventListener(this); + } + long id = event.getChannel().getIdLong(); + ChannelStatus status = channelsById.get(id); + if (status != null) { + if (status.isBusy()) { + status.busy(ChannelStatus.FREE); + event.reply("This channel is now free.").queue(); + } else { + Util.sendErrorMessage(event, "This channel is already free, no changes made"); + } + } else { + Util.sendErrorMessage(event, + "This channel is not being monitored for free/busy status"); + } + drawStatus(event.getTextChannel()); + } + + public String drawStatus(TextChannel channel) { + final Guild guild = channel.getGuild(); + + List statusFor = guild.getChannels() + .stream() + .filter(channelInGuild -> channelsById.containsKey(channelInGuild.getIdLong())) + .toList(); + + String message = statusFor.stream() + .map(GuildChannel::getIdLong) + .map(channelsById::get) + .map(channelStatus -> { + // update name so that current name is used + channelStatus + .setName(guild.getGuildChannelById(channelStatus.getChannelID()).getName()); + return channelStatus; + }) + .map(ChannelStatus::toDiscord) + .collect(Collectors.joining("\n")); + + channel.getLatestMessageIdLong(); + channel.sendMessage(message).queue(); + + // Not implemented yet + return message; + } + + @Override + public void onEvent(@NotNull GenericEvent event) { + if (event instanceof GuildMessageReceivedEvent castEvent) { + if (castEvent.isWebhookMessage() || castEvent.getAuthor().isBot()) { + return; + } + ChannelStatus status = channelsById.get(castEvent.getChannel().getIdLong()); + if (status == null || status.isBusy()) { + logger.debug("Channel status is currently busy, skipping message {}", status); + return; + } + status.busy(ChannelStatus.BUSY); + castEvent.getMessage().reply("The channel was free, please ask your question").queue(); + + } + } +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/free/StatusMessage.java b/application/src/main/java/org/togetherjava/tjbot/commands/free/StatusMessage.java new file mode 100644 index 0000000000..d4c683d95c --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/free/StatusMessage.java @@ -0,0 +1,42 @@ +package org.togetherjava.tjbot.commands.free; + +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.Message; +import net.dv8tion.jda.api.entities.TextChannel; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +public class StatusMessage { + private final Guild guild; + private final TextChannel postingChannel; + private final Message existingStatus; + private final List channelStatuses; + + + private StatusMessage(@NotNull Guild guild, @NotNull TextChannel postingChannel, + @NotNull List channelStatuses, Message existingStatus) { + this.guild = guild; + this.postingChannel = postingChannel; + this.channelStatuses = channelStatuses; + this.existingStatus = existingStatus; + } + + private static class StatusMessageBuilder { + private List channelStatuses; + private TextChannel postingChannel; + + private StatusMessageBuilder(@NotNull List channelStatuses) { + this.channelStatuses = channelStatuses; + } + + public StatusMessageBuilder channelToPostIn(TextChannel channel) { + postingChannel = channel; + return this; + } + } + + public static StatusMessageBuilder builder(@NotNull List channelStatuses) { + return new StatusMessageBuilder(channelStatuses); + } +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/free/Util.java b/application/src/main/java/org/togetherjava/tjbot/commands/free/Util.java new file mode 100644 index 0000000000..4b2a3b85e4 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/free/Util.java @@ -0,0 +1,18 @@ +package org.togetherjava.tjbot.commands.free; + +import net.dv8tion.jda.api.interactions.Interaction; + +public class Util { + // private constructor to prevent this class getting instantiated + private Util() {} + + /** + * Helper method to easily send ephemeral messages to users. + * + * @param interaction The event or hook that this message is responding to + * @param message The text to be display for the user to read. + */ + public static void sendErrorMessage(Interaction interaction, String message) { + interaction.reply(message).setEphemeral(true).queue(); + } +} 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 96ca7ca368..048fee5a26 100644 --- a/application/src/main/java/org/togetherjava/tjbot/config/Config.java +++ b/application/src/main/java/org/togetherjava/tjbot/config/Config.java @@ -6,6 +6,9 @@ import java.io.IOException; import java.nio.file.Path; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; import java.util.Objects; /** @@ -23,15 +26,19 @@ public final class Config { private final String projectWebsite; private final String discordGuildInvite; + private final List freeCommand; + @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) private Config(@JsonProperty("token") String token, @JsonProperty("databasePath") String databasePath, @JsonProperty("projectWebsite") String projectWebsite, - @JsonProperty("discordGuildInvite") String discordGuildInvite) { + @JsonProperty("discordGuildInvite") String discordGuildInvite, + @JsonProperty("freeCommand") FreeCommandConfig[] freeCommand) { this.token = token; this.databasePath = databasePath; this.projectWebsite = projectWebsite; this.discordGuildInvite = discordGuildInvite; + this.freeCommand = Arrays.stream(freeCommand).toList(); } /** @@ -93,4 +100,12 @@ public String getProjectWebsite() { public String getDiscordGuildInvite() { return discordGuildInvite; } + + /** + * + * @return an + */ + public Collection getFreeCommandConfig() { + return freeCommand; + } } diff --git a/application/src/main/java/org/togetherjava/tjbot/config/FreeCommandConfig.java b/application/src/main/java/org/togetherjava/tjbot/config/FreeCommandConfig.java new file mode 100644 index 0000000000..835c620e04 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/config/FreeCommandConfig.java @@ -0,0 +1,46 @@ +package org.togetherjava.tjbot.config; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonRootName; + +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +@SuppressWarnings("ClassCanBeRecord") +@JsonRootName(value = "freeCommand") +public final class FreeCommandConfig { + private final long statusChannel; + private final List monitoredChannels; + + /** + * //todo add java docs, include required json format to configure this + * + * @param statusChannel + * @param monitoredChannels + */ + @JsonCreator + private FreeCommandConfig(@JsonProperty("statusChannel") long statusChannel, + @JsonProperty("monitoredChannels") long[] monitoredChannels) { + this.statusChannel = statusChannel; + this.monitoredChannels = Arrays.stream(monitoredChannels).boxed().toList(); + } + + /** + * Gets the channelID where the status message will be displayed. + * + * @return the channelID for the status message + */ + public long getStatusChannel() { + return statusChannel; + } + + /** + * + * @return + */ + public Collection getMonitoredChannels() { + return monitoredChannels; + } +} From 32e46b4267e5850b28180ce89366e17f691de7ce Mon Sep 17 00:00:00 2001 From: java-coding-prodigy <85149944+java-coding-prodigy@users.noreply.github.com> Date: Tue, 19 Oct 2021 18:49:06 +0530 Subject: [PATCH 05/10] Fix #208, #206 (tex background color, tex error message UX) --- .../togetherjava/tjbot/commands/mathcommands/TeXCommand.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/mathcommands/TeXCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/mathcommands/TeXCommand.java index 9f45417653..468fe7fda2 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/mathcommands/TeXCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/mathcommands/TeXCommand.java @@ -36,7 +36,7 @@ public class TeXCommand extends SlashCommandAdapter { private static final String LATEX_OPTION = "latex"; private static final String RENDERING_ERROR = "There was an error generating the image"; private static final float DEFAULT_IMAGE_SIZE = 40F; - private static final Color BACKGROUND_COLOR = Color.decode("#383C3C"); + private static final Color BACKGROUND_COLOR = Color.decode("#36393F"); private static final Color FOREGROUND_COLOR = Color.decode("#FFFFFF"); private static final Logger logger = LoggerFactory.getLogger(TeXCommand.class); @@ -59,7 +59,7 @@ public void onSlashCommand(@NotNull final SlashCommandEvent event) { try { formula = new TeXFormula(latex); } catch (ParseException e) { - event.reply("That is an invalid latex").setEphemeral(true).queue(); + event.reply("That is an invalid latex: " + e.getMessage()).setEphemeral(true).queue(); return; } event.deferReply().queue(); From 58afeb73b3e2d7e0cf8d46a3fcb5e30c016f3292 Mon Sep 17 00:00:00 2001 From: Jonas Date: Wed, 20 Oct 2021 11:41:34 +0200 Subject: [PATCH 06/10] Tag system (#135) Co-authored-by: Zabuzard --- .../org/togetherjava/tjbot/Application.java | 1 + .../togetherjava/tjbot/BootstrapLauncher.java | 7 +- .../togetherjava/tjbot/commands/Commands.java | 10 +- .../tjbot/commands/SlashCommand.java | 6 +- .../tjbot/commands/SlashCommandAdapter.java | 2 +- .../tjbot/commands/system/ReloadCommand.java | 4 +- .../tjbot/commands/tags/TagCommand.java | 51 +++ .../tjbot/commands/tags/TagContentStyle.java | 18 + .../tjbot/commands/tags/TagManageCommand.java | 310 ++++++++++++++++++ .../tjbot/commands/tags/TagSystem.java | 154 +++++++++ .../tjbot/commands/tags/TagsCommand.java | 67 ++++ .../tjbot/commands/tags/package-info.java | 7 + .../tjbot/commands/utils/MessageUtils.java | 50 ++- .../tjbot/commands/utils/package-info.java | 4 + .../org/togetherjava/tjbot/config/Config.java | 1 + .../main/resources/db/V2__Add_Tag_System.sql | 5 + .../commands/utils/MessageUtilsTest.java | 57 ++++ .../tjbot/db/DatabaseException.java | 2 +- .../tjbot/formatter/CodeSectionFormatter.java | 23 -- .../tjbot/formatter/Formatter.java | 13 - .../tjbot/formatter/tokenizer/Lexer.java | 6 - .../tjbot/formatter/tokenizer/Token.java | 3 - .../tjbot/formatter/tokenizer/TokenType.java | 2 - .../tokenizer/TokenizationException.java | 2 - .../formatter/util/LookaheadArrayDeque.java | 2 - .../tjbot/formatter/util/LookaheadQueue.java | 2 - .../tjbot/formatter/FormatterTest.java | 3 - .../tjbot/formatter/tokenizer/LexerTest.java | 3 - settings.gradle | 1 - 29 files changed, 739 insertions(+), 77 deletions(-) create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/tags/TagCommand.java create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/tags/TagContentStyle.java create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/tags/TagManageCommand.java create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/tags/TagSystem.java create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/tags/TagsCommand.java create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/tags/package-info.java create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/utils/package-info.java create mode 100644 application/src/main/resources/db/V2__Add_Tag_System.sql create mode 100644 application/src/test/java/org/togetherjava/tjbot/commands/utils/MessageUtilsTest.java diff --git a/application/src/main/java/org/togetherjava/tjbot/Application.java b/application/src/main/java/org/togetherjava/tjbot/Application.java index 673780d436..60a1d84b28 100644 --- a/application/src/main/java/org/togetherjava/tjbot/Application.java +++ b/application/src/main/java/org/togetherjava/tjbot/Application.java @@ -65,6 +65,7 @@ public static void main(final String[] args) { * @param token the Discord Bot token to connect with * @param databasePath the path to the database to use */ + @SuppressWarnings("WeakerAccess") public static void runBot(String token, Path databasePath) { logger.info("Starting bot..."); try { diff --git a/application/src/main/java/org/togetherjava/tjbot/BootstrapLauncher.java b/application/src/main/java/org/togetherjava/tjbot/BootstrapLauncher.java index 6b21b147e6..0be2bb353a 100644 --- a/application/src/main/java/org/togetherjava/tjbot/BootstrapLauncher.java +++ b/application/src/main/java/org/togetherjava/tjbot/BootstrapLauncher.java @@ -5,9 +5,13 @@ * main logic to take over. */ public enum BootstrapLauncher { - ; + /** + * Starts the main application. + * + * @param args arguments are forwarded, see {@link Application#main(String[])} + */ public static void main(String[] args) { setSystemProperties(); @@ -29,6 +33,7 @@ private static void setSystemProperties() { // NOTE This will likely be fixed with Java 18 or newer, remove afterwards (see // https://bugs.openjdk.java.net/browse/JDK-8274349 and // https://github.com/openjdk/jdk/pull/5784) + // noinspection UseOfSystemOutOrSystemErr System.out.println("Available Cores \"" + cores + "\", setting Parallelism Flag"); // noinspection AccessOfSystemProperties System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "1"); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java b/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java index f05083e745..3961b19ed8 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java @@ -4,6 +4,10 @@ import org.togetherjava.tjbot.commands.basic.DatabaseCommand; import org.togetherjava.tjbot.commands.basic.PingCommand; import org.togetherjava.tjbot.commands.mathcommands.TeXCommand; +import org.togetherjava.tjbot.commands.tags.TagCommand; +import org.togetherjava.tjbot.commands.tags.TagManageCommand; +import org.togetherjava.tjbot.commands.tags.TagSystem; +import org.togetherjava.tjbot.commands.tags.TagsCommand; import org.togetherjava.tjbot.db.Database; import java.util.Collection; @@ -27,14 +31,16 @@ public enum Commands { * generally should be avoided. * * @param database the database of the application, which commands can use to persist data - * * @return a collection of all slash commands */ public static @NotNull Collection createSlashCommands( @NotNull Database database) { + TagSystem tagSystem = new TagSystem(database); // NOTE The command system can add special system relevant commands also by itself, // hence this list may not necessarily represent the full list of all commands actually // available. - return List.of(new PingCommand(), new DatabaseCommand(database), new TeXCommand()); + return List.of(new PingCommand(), new DatabaseCommand(database), new TeXCommand(), + new TagCommand(tagSystem), new TagManageCommand(tagSystem), + new TagsCommand(tagSystem)); } } 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 dd88e90f9a..5f8b2d6c25 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommand.java @@ -113,7 +113,7 @@ public interface SlashCommand { /** * Triggered by the command system when a slash command corresponding to this implementation - * (based on {@link #getData()} has been triggered. + * (based on {@link #getData()}) has been triggered. *

* This method may be called multi-threaded. 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 @@ -162,7 +162,7 @@ public interface SlashCommand { /** * Triggered by the command system when a button corresponding to this implementation (based on - * {@link #getData()} has been clicked. + * {@link #getData()}) has been clicked. *

* This method may be called multi-threaded. 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 @@ -182,7 +182,7 @@ public interface SlashCommand { /** * Triggered by the command system when a selection menu corresponding to this implementation - * (based on {@link #getData()} has been clicked. + * (based on {@link #getData()}) has been clicked. *

* This method may be called multi-threaded. 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 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 a698611196..ef0f894b99 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommandAdapter.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommandAdapter.java @@ -23,7 +23,7 @@ *

*

* The adapter manages all command related data itself, which can be provided during construction - * (see {@link #SlashCommandAdapter(String, String, SlashCommandVisibility)}. In order to add + * (see {@link #SlashCommandAdapter(String, String, SlashCommandVisibility)}). In order to add * options, subcommands or similar command configurations, use {@link #getData()} and mutate the * returned data object (see {@link CommandData} for details on how to work with this class). *

diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/system/ReloadCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/system/ReloadCommand.java index 7254daf3b9..33613c797a 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/system/ReloadCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/system/ReloadCommand.java @@ -88,9 +88,7 @@ public void onButtonClick(@NotNull ButtonClickEvent event, @NotNull List ButtonStyle buttonStyle = Objects.requireNonNull(event.getButton()).getStyle(); switch (buttonStyle) { - case DANGER -> { - event.reply("Okay, will not reload.").queue(); - } + case DANGER -> event.reply("Okay, will not reload.").queue(); case SUCCESS -> { logger.info("Reloading commands, triggered by user '{}' in guild '{}'", userId, event.getGuild()); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagCommand.java new file mode 100644 index 0000000000..e82b1ad827 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagCommand.java @@ -0,0 +1,51 @@ +package org.togetherjava.tjbot.commands.tags; + +import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; +import net.dv8tion.jda.api.interactions.commands.OptionType; +import org.jetbrains.annotations.NotNull; +import org.togetherjava.tjbot.commands.SlashCommandAdapter; +import org.togetherjava.tjbot.commands.SlashCommandVisibility; +import org.togetherjava.tjbot.commands.utils.MessageUtils; + +import java.util.Objects; + +/** + * Implements the {@code /tag} command which lets the bot respond content of a tag that has been + * added previously. + *

+ * Tags can be added by using {@link TagManageCommand} and a list of all tags is available using + * {@link TagsCommand}. + */ +public final class TagCommand extends SlashCommandAdapter { + private final TagSystem tagSystem; + + private static final String ID_OPTION = "id"; + + /** + * Creates a new instance, using the given tag system as base. + * + * @param tagSystem the system providing the actual tag data + */ + public TagCommand(TagSystem tagSystem) { + super("tag", "Display a tags content", SlashCommandVisibility.GUILD); + + this.tagSystem = tagSystem; + + // TODO Thing about adding an ephemeral selection menu with pagination support + // if the user calls this without id or similar + getData().addOption(OptionType.STRING, ID_OPTION, "the id of the tag to display", true); + } + + @Override + public void onSlashCommand(@NotNull SlashCommandEvent event) { + String id = Objects.requireNonNull(event.getOption(ID_OPTION)).getAsString(); + if (tagSystem.isUnknownTagAndHandle(id, event)) { + return; + } + + event + .replyEmbeds(MessageUtils.generateEmbed(null, tagSystem.getTag(id).orElseThrow(), + event.getUser(), TagSystem.AMBIENT_COLOR)) + .queue(); + } +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagContentStyle.java b/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagContentStyle.java new file mode 100644 index 0000000000..898576a394 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagContentStyle.java @@ -0,0 +1,18 @@ +package org.togetherjava.tjbot.commands.tags; + +/** + * The style of a tag content. + */ +public enum TagContentStyle { + /** + * Content that will be interpreted by Discord, for example a message containing {@code **foo**} + * will be displayed in bold. + */ + INTERPRETED, + /** + * Content that will be displayed raw, not interpreted by Discord. For example a message + * containing {@code **foo**} will be displayed as {@code **foo**} literally, by escaping the + * special characters. + */ + RAW +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagManageCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagManageCommand.java new file mode 100644 index 0000000000..cff16854ef --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagManageCommand.java @@ -0,0 +1,310 @@ +package org.togetherjava.tjbot.commands.tags; + +import net.dv8tion.jda.api.Permission; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; +import net.dv8tion.jda.api.exceptions.ErrorResponseException; +import net.dv8tion.jda.api.interactions.Interaction; +import net.dv8tion.jda.api.interactions.commands.CommandInteraction; +import net.dv8tion.jda.api.interactions.commands.OptionType; +import net.dv8tion.jda.api.interactions.commands.build.SubcommandData; +import net.dv8tion.jda.api.requests.ErrorResponse; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.SlashCommandAdapter; +import org.togetherjava.tjbot.commands.SlashCommandVisibility; +import org.togetherjava.tjbot.commands.utils.MessageUtils; + +import java.util.Objects; +import java.util.OptionalLong; +import java.util.function.BiConsumer; +import java.util.function.Consumer; + +/** + * Implements the {@code /tag-manage} command which allows management of tags, such as creating, + * editing or deleting them. Available subcommands are: + *

+ *

+ * Tags can be added by using {@link TagManageCommand} and a list of all tags is available using + * {@link TagsCommand}. + */ +public final class TagManageCommand extends SlashCommandAdapter { + private static final Logger logger = LoggerFactory.getLogger(TagManageCommand.class); + private static final String ID_OPTION = "id"; + private static final String ID_DESCRIPTION = "the id of the tag"; + private static final String CONTENT_OPTION = "content"; + private static final String CONTENT_DESCRIPTION = "the content of the tag"; + private static final String MESSAGE_ID_OPTION = "message-id"; + private static final String MESSAGE_ID_DESCRIPTION = "the id of the message to refer to"; + private final TagSystem tagSystem; + + /** + * Creates a new instance, using the given tag system as base. + * + * @param tagSystem the system providing the actual tag data + */ + public TagManageCommand(TagSystem tagSystem) { + super("tag-manage", "Provides commands to manage all tags", SlashCommandVisibility.GUILD); + + this.tagSystem = tagSystem; + + // TODO Think about adding a "Are you sure"-dialog to 'edit', 'edit-with-message' and + // 'delete' + getData().addSubcommands(new SubcommandData(Subcommand.RAW.name, + "View the raw content of a tag, without Discord interpreting any of its content") + .addOption(OptionType.STRING, ID_OPTION, ID_DESCRIPTION, true), + new SubcommandData(Subcommand.CREATE.name, "Creates a new tag") + .addOption(OptionType.STRING, ID_OPTION, ID_DESCRIPTION, true) + .addOption(OptionType.STRING, CONTENT_OPTION, CONTENT_DESCRIPTION, true), + new SubcommandData(Subcommand.CREATE_WITH_MESSAGE.name, + "Creates a new tag. Content is retrieved from the given message.") + .addOption(OptionType.STRING, ID_OPTION, ID_DESCRIPTION, true) + .addOption(OptionType.STRING, MESSAGE_ID_OPTION, MESSAGE_ID_DESCRIPTION, + true), + new SubcommandData(Subcommand.EDIT.name, "Edits a tag, the old content is replaced") + .addOption(OptionType.STRING, ID_OPTION, ID_DESCRIPTION, true) + .addOption(OptionType.STRING, CONTENT_OPTION, CONTENT_DESCRIPTION, true), + new SubcommandData(Subcommand.EDIT_WITH_MESSAGE.name, + "Edits a tag, the old content is replaced. Content is retrieved from the given message.") + .addOption(OptionType.STRING, ID_OPTION, ID_DESCRIPTION, true) + .addOption(OptionType.STRING, MESSAGE_ID_OPTION, MESSAGE_ID_DESCRIPTION, + true), + new SubcommandData(Subcommand.DELETE.name, "Deletes a tag") + .addOption(OptionType.STRING, ID_OPTION, ID_DESCRIPTION, true)); + } + + private static void sendSuccessMessage(@NotNull Interaction event, @NotNull String id, + @NotNull String actionVerb) { + logger.info("User '{}' {} the tag with id '{}'.", event.getUser().getId(), actionVerb, id); + event.replyEmbeds(MessageUtils.generateEmbed("Success", + "Successfully %s tag '%s'.".formatted(actionVerb, id), event.getUser(), + TagSystem.AMBIENT_COLOR)) + .queue(); + } + + /** + * Attempts to parse the given message id. + *

+ * If the message id could not be parsed, because it is invalid, an error message is send to the + * user. + * + * @param messageId the message id to parse + * @param event the event to send messages with + * @return the parsed message id, if successful + */ + private static OptionalLong parseMessageIdAndHandle(@NotNull String messageId, + @NotNull Interaction event) { + try { + return OptionalLong.of(Long.parseLong(messageId)); + } catch (NumberFormatException e) { + event + .reply("The given message id '%s' is invalid, expected a number." + .formatted(messageId)) + .setEphemeral(true) + .queue(); + return OptionalLong.empty(); + } + } + + @Override + public void onSlashCommand(@NotNull SlashCommandEvent event) { + Member member = Objects.requireNonNull(event.getMember()); + + if (!member.hasPermission(Permission.MESSAGE_MANAGE)) { + event.reply( + "Tags can only be managed by users who have the 'MESSAGE_MANAGE' permission.") + .setEphemeral(true) + .queue(); + return; + } + + switch (Subcommand.fromName(event.getSubcommandName())) { + case RAW -> rawTag(event); + case CREATE -> createTag(event); + case CREATE_WITH_MESSAGE -> createTagWithMessage(event); + case EDIT -> editTag(event); + case EDIT_WITH_MESSAGE -> editTagWithMessage(event); + case DELETE -> deleteTag(event); + default -> throw new AssertionError( + "Unexpected subcommand '%s'".formatted(event.getSubcommandName())); + } + } + + private void rawTag(@NotNull SlashCommandEvent event) { + String id = Objects.requireNonNull(event.getOption(ID_OPTION)).getAsString(); + if (tagSystem.isUnknownTagAndHandle(id, event)) { + return; + } + + event.replyEmbeds(MessageUtils.generateEmbed(null, + MessageUtils.escapeMarkdown(tagSystem.getTag(id).orElseThrow()), event.getUser(), + TagSystem.AMBIENT_COLOR)) + .queue(); + } + + private void createTag(@NotNull CommandInteraction event) { + String content = Objects.requireNonNull(event.getOption(CONTENT_OPTION)).getAsString(); + + handleAction(TagStatus.NOT_EXISTS, id -> tagSystem.putTag(id, content), "created", event); + } + + private void createTagWithMessage(@NotNull CommandInteraction event) { + handleActionWithMessage(TagStatus.NOT_EXISTS, tagSystem::putTag, "created", event); + } + + private void editTag(@NotNull CommandInteraction event) { + String content = Objects.requireNonNull(event.getOption(CONTENT_OPTION)).getAsString(); + + handleAction(TagStatus.EXISTS, id -> tagSystem.putTag(id, content), "edited", event); + } + + private void editTagWithMessage(@NotNull CommandInteraction event) { + handleActionWithMessage(TagStatus.EXISTS, tagSystem::putTag, "edited", event); + } + + private void deleteTag(@NotNull CommandInteraction event) { + handleAction(TagStatus.EXISTS, tagSystem::deleteTag, "deleted", event); + } + + /** + * Executes the given action on the tag id and sends a success message to the user. + *

+ * If the tag status does not line up with the required status, an error message is send to the + * user. + * + * @param requiredTagStatus the required status of the tag + * @param idAction the action to perform on the id + * @param actionVerb the verb describing the executed action, i.e. edited or + * created, will be displayed in the message send to the user + * @param event the event to send messages with, it must have an {@code id} option set + */ + private void handleAction(@NotNull TagStatus requiredTagStatus, + @NotNull Consumer idAction, @NotNull String actionVerb, + @NotNull CommandInteraction event) { + String id = Objects.requireNonNull(event.getOption(ID_OPTION)).getAsString(); + if (isWrongTagStatusAndHandle(requiredTagStatus, id, event)) { + return; + } + + idAction.accept(id); + sendSuccessMessage(event, id, actionVerb); + } + + /** + * Executes the given action on the tag id and the content and sends a success message to the + * user. + *

+ * The content is retrieved by looking up the message with the id stored in the event. + *

+ * If the tag status does not line up with the required status or a message with the given id + * does not exist, an error message is send to the user. + * + * @param requiredTagStatus the required status of the tag + * @param idAndContentAction the action to perform on the id and content + * @param actionVerb the verb describing the executed action, i.e. edited or + * created, will be displayed in the message send to the user + * @param event the event to send messages with, it must have an {@code id} and + * {@code message-id} option set + */ + private void handleActionWithMessage(@NotNull TagStatus requiredTagStatus, + @NotNull BiConsumer idAndContentAction, + @NotNull String actionVerb, @NotNull CommandInteraction event) { + String tagId = Objects.requireNonNull(event.getOption(ID_OPTION)).getAsString(); + OptionalLong messageIdOpt = parseMessageIdAndHandle( + Objects.requireNonNull(event.getOption(MESSAGE_ID_OPTION)).getAsString(), event); + if (messageIdOpt.isEmpty()) { + return; + } + long messageId = messageIdOpt.orElseThrow(); + if (isWrongTagStatusAndHandle(requiredTagStatus, tagId, event)) { + return; + } + + event.getMessageChannel().retrieveMessageById(messageId).queue(message -> { + idAndContentAction.accept(tagId, message.getContentRaw()); + sendSuccessMessage(event, tagId, actionVerb); + }, failure -> { + if (failure instanceof ErrorResponseException ex + && ex.getErrorResponse() == ErrorResponse.UNKNOWN_MESSAGE) { + event.reply("The message with id '%d' does not exist.".formatted(messageId)) + .setEphemeral(true) + .queue(); + return; + } + + logger.warn("Unable to retrieve the message with id '{}' for an unknown reason.", + messageId, failure); + event + .reply("Something unexpected went wrong trying to locate the message with id '%d'." + .formatted(messageId)) + .setEphemeral(true) + .queue(); + }); + } + + /** + * Returns whether the status of the given tag is not equal to the required status. + *

+ * If not, it sends an error message to the user. + * + * @param requiredTagStatus the required status of the tag + * @param id the id of the tag to check + * @param event the event to send messages with + * @return whether the status of the given tag is not equal to the required status + */ + private boolean isWrongTagStatusAndHandle(@NotNull TagStatus requiredTagStatus, + @NotNull String id, @NotNull Interaction event) { + if (requiredTagStatus == TagStatus.EXISTS) { + return tagSystem.isUnknownTagAndHandle(id, event); + } else if (requiredTagStatus == TagStatus.NOT_EXISTS) { + if (tagSystem.hasTag(id)) { + event.reply("The tag with id '%s' already exists.".formatted(id)) + .setEphemeral(true) + .queue(); + return true; + } + } else { + throw new AssertionError("Unknown tag status '%s'".formatted(requiredTagStatus)); + } + return false; + } + + private enum TagStatus { + EXISTS, + NOT_EXISTS + } + + + private enum Subcommand { + RAW("raw"), + CREATE("create"), + CREATE_WITH_MESSAGE("create-with-message"), + EDIT("edit"), + EDIT_WITH_MESSAGE("edit-with-message"), + DELETE("delete"); + + private final String name; + + Subcommand(String name) { + this.name = name; + } + + static Subcommand fromName(String name) { + for (Subcommand subcommand : Subcommand.values()) { + if (subcommand.name.equals(name)) { + return subcommand; + } + } + throw new IllegalArgumentException( + "Subcommand with name '%s' is unknown".formatted(name)); + } + } +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagSystem.java b/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagSystem.java new file mode 100644 index 0000000000..b2698ea52a --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagSystem.java @@ -0,0 +1,154 @@ +package org.togetherjava.tjbot.commands.tags; + +import net.dv8tion.jda.api.entities.Emoji; +import net.dv8tion.jda.api.interactions.Interaction; +import net.dv8tion.jda.api.interactions.components.Button; +import net.dv8tion.jda.api.interactions.components.ButtonStyle; +import org.jetbrains.annotations.NotNull; +import org.togetherjava.tjbot.db.Database; +import org.togetherjava.tjbot.db.generated.tables.Tags; +import org.togetherjava.tjbot.db.generated.tables.records.TagsRecord; + +import java.awt.*; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * The core of the tag system. Provides methods to read and create tags, directly tied to the + * underlying database. + */ +public final class TagSystem { + /** + * The ambient color to use for tag system related messages. + */ + static final Color AMBIENT_COLOR = Color.decode("#FA8072"); + + private final Database database; + + /** + * Creates an instance. + * + * @param database the database to store and retrieve tags from + */ + public TagSystem(Database database) { + this.database = database; + } + + /** + * Creates a delete button with the given component id that can be used in message dialogs. For + * example to delete a message. + * + * @param componentId the component id to use for the button + * @return the created delete button + */ + @SuppressWarnings("StaticMethodOnlyUsedInOneClass") + static Button createDeleteButton(String componentId) { + return Button.of(ButtonStyle.DANGER, componentId, "Delete", + Emoji.fromUnicode("\uD83D\uDDD1")); // trash bin + } + + /** + * Returns whether the given tag is unknown to the system. + *

+ * If it is unknown, it sends an error message to the user. + * + * @param id the id of the tag to check + * @param event the event to send messages with + * @return whether the given tag is unknown to the system + */ + boolean isUnknownTagAndHandle(@NotNull String id, @NotNull Interaction event) { + if (hasTag(id)) { + return false; + } + // TODO Add fuzzy string matching suggestions (Levenshtein edit distance) + event.reply("Could not find any tag with id '%s'.".formatted(id)) + .setEphemeral(true) + .queue(); + return true; + } + + /** + * Checks if the given tag is known to the tag system. + * + * @param id the id of the tag to check + * @return whether the tag is known to the tag system + */ + boolean hasTag(String id) { + return database.readTransaction(context -> { + try (var selectFrom = context.selectFrom(Tags.TAGS)) { + return selectFrom.where(Tags.TAGS.ID.eq(id)).fetchOne() != null; + } + }); + } + + /** + * Deletes a tag from the tag system. + * + * @param id the id of the tag to delete + * @throws IllegalArgumentException if the tag is unknown to the system, see + * {@link #hasTag(String)} + */ + // Execute closes resources; without curly braces on the lambda, the call would be ambiguous + @SuppressWarnings({"resource", "java:S1602"}) + void deleteTag(String id) { + int deletedRecords = database.write(context -> { + return context.deleteFrom(Tags.TAGS).where(Tags.TAGS.ID.eq(id)).execute(); + }); + if (deletedRecords == 0) { + throw new IllegalArgumentException( + "Unable to delete the tag '%s', it is unknown to the system".formatted(id)); + } + } + + /** + * Inserts or replaces the tag with the given data into the system. + * + * @param id the id of the tag to put + * @param content the content of the tag to put + */ + // Execute closes resources; without curly braces on the lambda, the call would be ambiguous + @SuppressWarnings({"resource", "java:S1602"}) + void putTag(String id, String content) { + database.writeTransaction(context -> { + context.insertInto(Tags.TAGS, Tags.TAGS.ID, Tags.TAGS.CONTENT) + .values(id, content) + .onDuplicateKeyUpdate() + .set(Tags.TAGS.CONTENT, content) + .execute(); + }); + } + + /** + * Retrieves the content of the given tag, if it is known to the system (see + * {@link #hasTag(String)}). + * + * @param id the id of the tag to get + * @return the content of the tag, if the tag is known to the system + */ + Optional getTag(String id) { + return database.readTransaction(context -> { + try (var selectFrom = context.selectFrom(Tags.TAGS)) { + return Optional.ofNullable(selectFrom.where(Tags.TAGS.ID.eq(id)).fetchOne()) + .map(TagsRecord::getContent); + } + }); + } + + /** + * Gets the ids of all tags known to the system. + * + * @return a set of all ids known to the system, not backed + */ + Set getAllIds() { + return database.readTransaction(context -> { + try (var select = context.select(Tags.TAGS.ID)) { + return select.from(Tags.TAGS) + .fetch() + .stream() + .map(dbRecord -> dbRecord.getValue(Tags.TAGS.ID)) + .collect(Collectors.toSet()); + } + }); + } +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagsCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagsCommand.java new file mode 100644 index 0000000000..82baa36a94 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/tags/TagsCommand.java @@ -0,0 +1,67 @@ +package org.togetherjava.tjbot.commands.tags; + +import net.dv8tion.jda.api.Permission; +import net.dv8tion.jda.api.events.interaction.ButtonClickEvent; +import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; +import org.jetbrains.annotations.NotNull; +import org.togetherjava.tjbot.commands.SlashCommandAdapter; +import org.togetherjava.tjbot.commands.SlashCommandVisibility; +import org.togetherjava.tjbot.commands.utils.MessageUtils; + +import java.util.List; +import java.util.Objects; + +/** + * Implements the {@code /tags} command which lets the bot respond with all available tags. + *

+ * Tags can be added by using {@link TagManageCommand} and viewed by {@link TagCommand}. + *

+ * For example, suppose there is a tag with id {@code foo} and content {@code bar}, then: + * + *

+ * {@code
+ * /tag foo
+ * // TJ-Bot: bar
+ * }
+ * 
+ */ +public final class TagsCommand extends SlashCommandAdapter { + private final TagSystem tagSystem; + + /** + * Creates a new instance, using the given tag system as base. + * + * @param tagSystem the system providing the actual tag data + */ + public TagsCommand(TagSystem tagSystem) { + super("tags", "Displays all available tags", SlashCommandVisibility.GUILD); + + this.tagSystem = tagSystem; + } + + @Override + public void onSlashCommand(@NotNull SlashCommandEvent event) { + // TODO A list might be better than comma separated, which is hard to read + event.replyEmbeds(MessageUtils.generateEmbed("All available tags", + String.join(", ", tagSystem.getAllIds()), event.getUser(), TagSystem.AMBIENT_COLOR)) + .addActionRow( + TagSystem.createDeleteButton(generateComponentId(event.getUser().getId()))) + .queue(); + } + + @Override + public void onButtonClick(@NotNull ButtonClickEvent event, @NotNull List args) { + String userId = args.get(0); + + if (!event.getUser().getId().equals(userId) && !Objects.requireNonNull(event.getMember()) + .hasPermission(Permission.MESSAGE_MANAGE)) { + event.reply( + "The message can only be deleted by its author or an user with 'MESSAGE_MANAGE' permissions.") + .setEphemeral(true) + .queue(); + return; + } + + event.getMessage().delete().queue(); + } +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/tags/package-info.java b/application/src/main/java/org/togetherjava/tjbot/commands/tags/package-info.java new file mode 100644 index 0000000000..e250c06ae9 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/tags/package-info.java @@ -0,0 +1,7 @@ +/** + * This package offers the tag system and its commands. See + * {@link org.togetherjava.tjbot.commands.tags.TagSystem} for the core of the system and commands + * like {@link org.togetherjava.tjbot.commands.tags.TagCommand} as entry point to the package's + * offered functionality. + */ +package org.togetherjava.tjbot.commands.tags; 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 83feddad84..ce35d8789d 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,10 +1,17 @@ package org.togetherjava.tjbot.commands.utils; +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.User; import net.dv8tion.jda.api.interactions.components.ActionRow; import net.dv8tion.jda.api.interactions.components.Button; +import net.dv8tion.jda.api.utils.MarkdownSanitizer; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import java.awt.*; +import java.time.Instant; import java.util.List; /** @@ -13,16 +20,13 @@ * This class is meant to contain all utility methods for {@link Message} that can be used on all * other commands to avoid similar methods appearing everywhere. */ -public class MessageUtils { - - private MessageUtils() { - throw new UnsupportedOperationException(); - } +public enum MessageUtils { + ; /** * Disables all the buttons that a message has. Disabling buttons deems it as not clickable to * the user who sees it. - *

+ *

* This method already queues the changes for you and does not block in any way. * * @param message the message that contains at least one button @@ -39,4 +43,38 @@ public static void disableButtons(@NotNull Message message) { .queue(); } + /** + * Generates an embed with the given content. + * + * @param title title of the embed or {@code null} if not desired + * @param content content to display in the embed + * @param user name of the user who requested the embed or {@code null} if no user requested + * this + * @param ambientColor the ambient color of the embed or {@code null} for a default color + * @return the generated embed + */ + public static @NotNull MessageEmbed generateEmbed(@Nullable String title, + @NotNull CharSequence content, @Nullable User user, @Nullable Color ambientColor) { + return new EmbedBuilder().setTitle(title) + .setDescription(content) + .setTimestamp(Instant.now()) + .setFooter(user == null ? null : user.getName()) + .setColor(ambientColor) + .build(); + } + + /** + * 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 + */ + public static @NotNull String escapeMarkdown(@NotNull String text) { + // NOTE Unfortunately the utility does not escape backslashes '\', so we have to do it + // ourselves + return MarkdownSanitizer.escape(text.replace("\\", "\\\\")); + } + } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/utils/package-info.java b/application/src/main/java/org/togetherjava/tjbot/commands/utils/package-info.java new file mode 100644 index 0000000000..b51bd42a90 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/utils/package-info.java @@ -0,0 +1,4 @@ +/** + * This package contains general utility used by commands. + */ +package org.togetherjava.tjbot.commands.utils; 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 96ca7ca368..88097957f4 100644 --- a/application/src/main/java/org/togetherjava/tjbot/config/Config.java +++ b/application/src/main/java/org/togetherjava/tjbot/config/Config.java @@ -16,6 +16,7 @@ @SuppressWarnings({"Singleton", "ClassCanBeRecord"}) public final class Config { + @SuppressWarnings("RedundantFieldInitialization") private static Config config = null; private final String token; diff --git a/application/src/main/resources/db/V2__Add_Tag_System.sql b/application/src/main/resources/db/V2__Add_Tag_System.sql new file mode 100644 index 0000000000..b33cb48539 --- /dev/null +++ b/application/src/main/resources/db/V2__Add_Tag_System.sql @@ -0,0 +1,5 @@ +CREATE TABLE tags +( + id TEXT NOT NULL PRIMARY KEY, + content TEXT NOT NULL +) 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 new file mode 100644 index 0000000000..f5170c4235 --- /dev/null +++ b/application/src/test/java/org/togetherjava/tjbot/commands/utils/MessageUtilsTest.java @@ -0,0 +1,57 @@ +package org.togetherjava.tjbot.commands.utils; + +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +final class MessageUtilsTest { + + @Test + void escapeMarkdown() { + List tests = List.of(new TestCase("empty", "", ""), + new TestCase("no markdown", "hello world", "hello world"), + new TestCase("basic markdown", "\\*\\*hello\\*\\* \\_world\\_", + "**hello** _world_"), + new TestCase("code block", """ + \\```java + int x = 5; + \\``` + """, """ + ```java + int x = 5; + ``` + """), new TestCase("escape simple", "hello\\\\\\\\world\\\\\\\\test", + "hello\\\\world\\\\test"), + new TestCase("escape complex", """ + Hello\\\\\\\\world + \\```java + Hello\\\\\\\\ + world + \\``` + test out this + \\```java + "Hello \\\\" World\\\\\\\\\\\\"" haha + \\``` + """, """ + Hello\\\\world + ```java + Hello\\\\ + world + ``` + test out this + ```java + "Hello \\" World\\\\\\"" haha + ``` + """)); + + for (TestCase test : tests) { + assertEquals(test.escapedMessage(), MessageUtils.escapeMarkdown(test.originalMessage()), + "Test failed: " + test.testName()); + } + } + + private record TestCase(String testName, String escapedMessage, String originalMessage) { + } +} diff --git a/database/src/main/java/org/togetherjava/tjbot/db/DatabaseException.java b/database/src/main/java/org/togetherjava/tjbot/db/DatabaseException.java index 41705d62b0..87b2de3882 100644 --- a/database/src/main/java/org/togetherjava/tjbot/db/DatabaseException.java +++ b/database/src/main/java/org/togetherjava/tjbot/db/DatabaseException.java @@ -5,7 +5,7 @@ /** * Thrown when an error occurs while interacting with the database. */ -public class DatabaseException extends RuntimeException { +public final class DatabaseException extends RuntimeException { /** * Serial version UID. */ diff --git a/formatter/src/main/java/org/togetherjava/tjbot/formatter/CodeSectionFormatter.java b/formatter/src/main/java/org/togetherjava/tjbot/formatter/CodeSectionFormatter.java index 801bcf4f00..4ea0f1c367 100644 --- a/formatter/src/main/java/org/togetherjava/tjbot/formatter/CodeSectionFormatter.java +++ b/formatter/src/main/java/org/togetherjava/tjbot/formatter/CodeSectionFormatter.java @@ -11,8 +11,6 @@ /** * Formatter which specifically formats code tokens (that are part of a section) - * - * @author illuminator3 */ class CodeSectionFormatter { private final StringBuilder result = new StringBuilder(); @@ -37,7 +35,6 @@ class CodeSectionFormatter { * Removes all whitespaces from the given queue * * @param queue the queue to remove whitespaces from - * @author illuminator3 */ private static void purgeWhitespaces(Queue queue) { queue.removeIf(t -> t.type() == TokenType.WHITESPACE); @@ -45,8 +42,6 @@ private static void purgeWhitespaces(Queue queue) { /** * Starts the formatting process - * - * @author illuminator3 */ void format() { Token next; @@ -62,7 +57,6 @@ void format() { * Consumes the next token * * @param token token to consume - * @author illuminator3 */ private void consume(Token token) { TokenType type = token.type(); @@ -87,7 +81,6 @@ private void consume(Token token) { * Puts the next token into the result * * @param token token to put - * @author illuminator3 */ private void put(Token token) { TokenType type = token.type(); @@ -117,7 +110,6 @@ private void put(Token token) { * * @param token token to check * @return whether a space should be put after that token - * @author illuminator3 */ private boolean shouldPutSpaceAfter(Token token) { TokenType type = token.type(); @@ -138,7 +130,6 @@ private boolean shouldPutSpaceAfter(Token token) { * {@link SkippableLookaheadQueue#peek(int, Predicate)} * * @param type current token type - * @author illuminator3 */ private void checkFor(TokenType type) { if (isIndexedForLoop(type)) { // if it's a for int loop then set the forLevel to 2 @@ -150,7 +141,6 @@ private void checkFor(TokenType type) { * Handles the case of being inside a generic type declaration * * @param token current token - * @author illuminator3 */ private void handleGeneric(Token token) { TokenType type = token.type(); @@ -188,7 +178,6 @@ private void handleGeneric(Token token) { * * @param type current token type * @return whether the token type belongs to a generic type declaration - * @author illuminator3 */ private boolean checkGeneric(TokenType type) { if (type == TokenType.LESS_THAN) { @@ -227,7 +216,6 @@ private boolean checkGeneric(TokenType type) { * * @param type token type to check * @return whether it's valid inside a generic type declaration - * @author illuminator3 */ private boolean isValidGeneric(TokenType type) { return type == TokenType.WILDCARD || type == TokenType.LESS_THAN @@ -241,7 +229,6 @@ private boolean isValidGeneric(TokenType type) { * * @param type token type to check * @return whether a new line should be put after that token - * @author illuminator3 */ private boolean shouldPutNewLineAfter(TokenType type) { if (type == TokenType.OPEN_BRACES || type == TokenType.SEMICOLON @@ -261,7 +248,6 @@ private boolean shouldPutNewLineAfter(TokenType type) { * * @param type current token type * @return whether there's an indexed for loop or not - * @author illuminator3 */ private boolean isIndexedForLoop(TokenType type) { return type == TokenType.FOR && !internalEnhancedFor(); @@ -271,7 +257,6 @@ private boolean isIndexedForLoop(TokenType type) { * Checks if there's an enhanced for loop ahead without checking the current token type * * @return whether there's an enhanced for loop ahead - * @author illuminator3 */ private boolean internalEnhancedFor() { return queue.peek(3, t -> { @@ -286,7 +271,6 @@ private boolean internalEnhancedFor() { * closing parenthesis, an operator or a semicolon * * @return whether a space should be put after the parenthesis - * @author illuminator3 */ private boolean isParenthesisRule(Token token) { if (queue.isEmpty()) { @@ -303,8 +287,6 @@ private boolean isParenthesisRule(Token token) { /** * Appends a new line if there's more in the token queue - * - * @author illuminator3 */ private void appendNewLine() { if (!queue.isEmpty()) { @@ -321,7 +303,6 @@ private void appendNewLine() { * * @param token token to check * @return whether the given token is a keyword - * @author illuminator3 */ private boolean isKeyword(Token token) { return token.type().isKeyword(); @@ -332,7 +313,6 @@ private boolean isKeyword(Token token) { * * @param token token to check * @return whether the given token is an operator - * @author illuminator3 */ private boolean isOperator(Token token) { return token.type().isOperator(); @@ -342,7 +322,6 @@ private boolean isOperator(Token token) { * Updates the indentation based on the current token type * * @param type current token type - * @author illuminator3 */ private void updateIndentation(TokenType type) { if (type == TokenType.OPEN_BRACES) { @@ -354,8 +333,6 @@ private void updateIndentation(TokenType type) { /** * Applies the current indentation - * - * @author illuminator3 */ private void applyIndentation() { if (applyIndentation) { 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 624aec1b7f..48b9f2ca25 100644 --- a/formatter/src/main/java/org/togetherjava/tjbot/formatter/Formatter.java +++ b/formatter/src/main/java/org/togetherjava/tjbot/formatter/Formatter.java @@ -10,8 +10,6 @@ /** * Formatter which can format a given string into a string which contains code blocks etc - * - * @author illuminator3 */ public class Formatter { /** @@ -19,7 +17,6 @@ public class Formatter { * * @param tokens tokens to format * @return resulting code - * @author illuminator3 */ public String format(List tokens) { List

sections = sectionize(indexTokens(tokens)); @@ -44,7 +41,6 @@ public String format(List tokens) { * @param input input to format * @param lexer lexer to use * @return resulting code - * @author illuminator3 */ public String format(String input, Lexer lexer) { return format(lexer.tokenize(input)); @@ -55,7 +51,6 @@ public String format(String input, Lexer lexer) { * * @param tokens tokens to join * @return joined form of the tokens - * @author illuminator3 */ private String joinTokens(List tokens) { return tokens.stream().map(Token::content).collect(Collectors.joining()); @@ -67,7 +62,6 @@ private String joinTokens(List tokens) { * * @param tokens tokens to write * @return written code sections - * @author illuminator3 */ private StringBuilder writeCodeSection(List tokens) { CodeSectionFormatter formatter = new CodeSectionFormatter(tokens); @@ -82,7 +76,6 @@ private StringBuilder writeCodeSection(List tokens) { * * @param tokens not-indexed tokens * @return indexed tokens - * @author illuminator3 */ private List indexTokens(List tokens) { return tokens.stream() @@ -95,7 +88,6 @@ private List indexTokens(List tokens) { * * @param token token to check * @return true if it's a code token, false if not - * @author illuminator3 */ private boolean isTokenPartOfCode(Token token) { return token.type() != TokenType.UNKNOWN; @@ -107,7 +99,6 @@ private boolean isTokenPartOfCode(Token token) { * * @param checkedTokens checked tokens * @return list of sections - * @author illuminator3 */ private List
sectionize(List checkedTokens) { CheckedToken first = checkedTokens.get(0); @@ -135,16 +126,12 @@ private List
sectionize(List checkedTokens) { /** * Section POJR - * - * @author illuminator3 */ private static record Section(List tokens, boolean isCodeSection) { } /** * CheckedToken POJR - * - * @author illuminator3 */ private static record CheckedToken(Token token, boolean isCode) { } 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 cbea6a7f38..9838f1dc29 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 @@ -8,8 +8,6 @@ /** * Tokenizer that can turn a list of strings (or a string) into a list of tokens - * - * @author illuminator3 */ public class Lexer { /** @@ -23,7 +21,6 @@ public class Lexer { * * @param input input to tokenize * @return resulting tokens - * @author illuminator3 */ public List tokenize(String input) { return tokenize(Arrays.asList(patchComments(input).split("\n"))); @@ -34,7 +31,6 @@ public List tokenize(String input) { * * @param lines input to tokenize * @return resulting tokens - * @author illuminator3 */ public List tokenize(List lines) { return lines.stream().map(this::tokenizeLine).flatMap(List::stream).toList(); @@ -45,7 +41,6 @@ public List tokenize(List lines) { * * @param line input to tokenize * @return resulting tokens - * @author illuminator3 */ private List tokenizeLine(String line) { List tokens = new ArrayList<>(); @@ -80,7 +75,6 @@ private Token findToken(String content) { * * @param input input to patch * @return resulting string - * @author illuminator3 */ private String patchComments(String input) { // fix this, you shouldn't need this! Matcher matcher = commentPatcherRegex.matcher(input); 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 9d4d751256..c43d2e80a6 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 @@ -4,8 +4,6 @@ /** * Class representing a Token with a given content and a type - * - * @author illuminator3 */ public record Token(String content, TokenType type) { private static final Set displayTypes = @@ -20,7 +18,6 @@ public String toString() { * Returns a non-empty string if this token has something to display * * @return the displayed value - * @author illuminator3 */ private String formatForDisplay() { if (displayTypes.contains(type())) { 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 3a125fea74..5aebce63c1 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 @@ -4,8 +4,6 @@ /** * Represents every possible token that can be parsed by the lexer - * - * @author illuminator3 */ public enum TokenType { // keywords 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 index 1ae6c3790b..a233ed127e 100644 --- a/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/TokenizationException.java +++ b/formatter/src/main/java/org/togetherjava/tjbot/formatter/tokenizer/TokenizationException.java @@ -2,8 +2,6 @@ /** * Exception that can occur when lexing - * - * @author illuminator3 */ public class TokenizationException extends RuntimeException { public TokenizationException(String 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 index 9ed1cfdf6d..5361cbcbdc 100644 --- a/formatter/src/main/java/org/togetherjava/tjbot/formatter/util/LookaheadArrayDeque.java +++ b/formatter/src/main/java/org/togetherjava/tjbot/formatter/util/LookaheadArrayDeque.java @@ -7,8 +7,6 @@ /** * A {@link LookaheadQueue} implementation that is based on an {@link ArrayDeque} - * - * @author illuminator3 */ public class LookaheadArrayDeque extends ArrayDeque implements LookaheadQueue { public LookaheadArrayDeque() {} 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 index d72a4df9d7..ec45dd0408 100644 --- a/formatter/src/main/java/org/togetherjava/tjbot/formatter/util/LookaheadQueue.java +++ b/formatter/src/main/java/org/togetherjava/tjbot/formatter/util/LookaheadQueue.java @@ -5,8 +5,6 @@ public interface LookaheadQueue extends Queue { /** * Peeks into the "future", peek(0) would be the equivalent to peek() - * - * @author illuminator3 */ E peek(int n); } 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 3366c06edb..e94e45915d 100644 --- a/formatter/src/test/java/org/togetherjava/tjbot/formatter/FormatterTest.java +++ b/formatter/src/test/java/org/togetherjava/tjbot/formatter/FormatterTest.java @@ -8,9 +8,6 @@ import org.junit.jupiter.api.TestInstance; import org.togetherjava.tjbot.formatter.tokenizer.Lexer; -/** - * @author illuminator3 - */ @TestInstance(TestInstance.Lifecycle.PER_CLASS) class FormatterTest { Lexer lexer; 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 48c3f89796..05890cbd28 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 @@ -10,9 +10,6 @@ import java.util.ArrayList; import java.util.List; -/** - * @author illuminator3 - */ @TestInstance(TestInstance.Lifecycle.PER_CLASS) class LexerTest { Lexer lexer; diff --git a/settings.gradle b/settings.gradle index 1ba2012448..1dd56827f2 100644 --- a/settings.gradle +++ b/settings.gradle @@ -4,4 +4,3 @@ include 'application' include 'database' include 'formatter' include 'logviewer' - From f8ee501e54570afc8f3705981ea6516f41c438d5 Mon Sep 17 00:00:00 2001 From: borgrel Date: Wed, 20 Oct 2021 12:11:33 +0200 Subject: [PATCH 07/10] Added framework for FreeCommand and ChannelStatus Added Util for ephemeral error messages Modified Config to load FreeChannel config Improved Javadocs Added test Status message Rebased onto development Cleaned code --- .../togetherjava/tjbot/commands/Commands.java | 4 +- .../tjbot/commands/free/FreeCommand.java | 145 +++++++++++++----- .../tjbot/commands/free/Util.java | 4 +- .../org/togetherjava/tjbot/config/Config.java | 5 +- .../tjbot/config/FreeCommandConfig.java | 32 ++-- 5 files changed, 137 insertions(+), 53 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java b/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java index f05083e745..5a7997eef8 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java @@ -3,6 +3,7 @@ import org.jetbrains.annotations.NotNull; import org.togetherjava.tjbot.commands.basic.DatabaseCommand; import org.togetherjava.tjbot.commands.basic.PingCommand; +import org.togetherjava.tjbot.commands.free.FreeCommand; import org.togetherjava.tjbot.commands.mathcommands.TeXCommand; import org.togetherjava.tjbot.db.Database; @@ -35,6 +36,7 @@ public enum Commands { // NOTE The command system can add special system relevant commands also by itself, // hence this list may not necessarily represent the full list of all commands actually // available. - return List.of(new PingCommand(), new DatabaseCommand(database), new TeXCommand()); + return List.of(new PingCommand(), new DatabaseCommand(database), new TeXCommand(), + new FreeCommand()); } } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/free/FreeCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/free/FreeCommand.java index c10a7157b7..94d32a6678 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/free/FreeCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/free/FreeCommand.java @@ -2,8 +2,10 @@ import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.GuildChannel; +import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.events.GenericEvent; +import net.dv8tion.jda.api.events.ReadyEvent; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent; import net.dv8tion.jda.api.hooks.EventListener; @@ -15,15 +17,13 @@ import org.togetherjava.tjbot.config.Config; import org.togetherjava.tjbot.config.FreeCommandConfig; -import java.util.Collection; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; -// todo check if channel is valid before processing onSlashCommand (can SlashCommandVisibility be +// todo (can SlashCommandVisibility be // narrower than GUILD?) -// todo monitor all channels when list is empty? monitor none? (defaulting to all for testing) +// todo monitor all channels when list is empty? monitor none? // todo (use other emojis? use images?) // todo add command to add/remove/status channels to monitor // todo test if message is a reply and don't mark as busy if it is @@ -58,9 +58,10 @@ public class FreeCommand extends SlashCommandAdapter implements EventListener { // Map to store channel ID's, use Guild.getChannels() to guarantee order for display private final Map channelsById; - private final Map guildToStatus; + private final Map guildToStatusChannel; + private final Map channelToStatusMessage; - private boolean isRegistered; + private boolean isReady; /** @@ -74,18 +75,49 @@ public FreeCommand() { SlashCommandVisibility.GUILD); Collection config = Config.getInstance().getFreeCommandConfig(); - guildToStatus = config.stream() - .map(FreeCommandConfig::getStatusChannel) - // todo change Function.identity to JDA.getChannel.getGuild when viable. - .collect(Collectors.toMap(Function.identity(), Function.identity())); + guildToStatusChannel = new HashMap<>(); // JDA required to fetch guildID + channelToStatusMessage = new HashMap<>(); // empty .... used to track status messages channelsById = config.stream() .map(FreeCommandConfig::getMonitoredChannels) .flatMap(Collection::stream) .map(ChannelStatus::new) .collect(Collectors.toMap(ChannelStatus::getChannelID, Function.identity())); - logger.debug("Config loaded: Display on {} and monitor {}", guildToStatus, channelsById); - isRegistered = false; + isReady = false; + } + + @Override + public void onReady(@NotNull final ReadyEvent event) { + // todo remove this when onGuildMessageRecieved has another access point + event.getJDA().addEventListener(this); + + Collection config = Config.getInstance().getFreeCommandConfig(); + config.stream() + .map(FreeCommandConfig::getStatusChannel) + .distinct() // not necessary? validates user input, since input is from file + // should this test if already present first? + .forEach(id -> guildToStatusChannel + .put(event.getJDA().getGuildChannelById(id).getGuild().getIdLong(), id)); + + logger.debug("Config loaded:\nDisplay statuses on {}\nand monitor channels {}", + guildToStatusChannel, channelsById); + + // not collecting to map because onReady is not run during construction + guildToStatusChannel.values() + .stream() + .map(event.getJDA()::getTextChannelById) + .map(this::getStatusMessageIn) + .flatMap(Optional::stream) + .forEach(message -> channelToStatusMessage.put(message.getChannel().getIdLong(), + message.getIdLong())); + + + guildToStatusChannel.values() + .stream() + .map(event.getJDA()::getTextChannelById) + .forEach(this::drawStatus); + + isReady = true; } /** @@ -98,52 +130,71 @@ public FreeCommand() { * @param event the event that triggered this */ @Override - public void onSlashCommand(@NotNull SlashCommandEvent event) { + public void onSlashCommand(@NotNull final SlashCommandEvent event) { logger.debug("/free used by {} on channel {}", event.getUser().getName(), event.getChannel().getName()); - if (!isRegistered) { - event.getJDA().addEventListener(this); - } + if (!shouldHandle(event)) + return; + long id = event.getChannel().getIdLong(); + // do not need to test if key is present, shouldHandle(event) already does. ChannelStatus status = channelsById.get(id); - if (status != null) { - if (status.isBusy()) { - status.busy(ChannelStatus.FREE); - event.reply("This channel is now free.").queue(); - } else { - Util.sendErrorMessage(event, "This channel is already free, no changes made"); - } + if (status.isBusy()) { + status.busy(ChannelStatus.FREE); + drawStatus(getStatusChannelFor(event.getGuild())); + event.reply("This channel is now free.").queue(); } else { + Util.sendErrorMessage(event, "This channel is already free, no changes made"); + } + } + + private boolean shouldHandle(@NotNull final SlashCommandEvent event) { + if (!isReady) { + logger.debug( + "Slash command requested by {} in {}(channel: {}) before command is ready.", + event.getUser().getIdLong(), event.getGuild(), event.getChannel().getName()); + Util.sendErrorMessage(event, "Command not ready please try again in a minute"); + return false; + } + if (!guildToStatusChannel.containsKey(event.getGuild().getIdLong())) { + logger.error( + "Slash command used by {} in {}(channel: {}) when guild is not registed in Free Command", + event.getUser().getIdLong(), event.getGuild(), event.getChannel().getName()); + Util.sendErrorMessage(event, + "This guild (%s) is not configured to use the '/free' command, please add entries in the config, restart the bot and try again." + .formatted(event.getGuild().getName())); + return false; + } + if (!channelsById.containsKey(event.getChannel().getIdLong())) { + logger.debug("'/free called in unregistered channel {}({})", event.getGuild().getName(), + event.getChannel().getName()); Util.sendErrorMessage(event, "This channel is not being monitored for free/busy status"); + return false; } - drawStatus(event.getTextChannel()); + + return true; } public String drawStatus(TextChannel channel) { final Guild guild = channel.getGuild(); - List statusFor = guild.getChannels() + List statusFor = guild.getChannels() .stream() - .filter(channelInGuild -> channelsById.containsKey(channelInGuild.getIdLong())) - .toList(); - - String message = statusFor.stream() .map(GuildChannel::getIdLong) + .filter(channelsById::containsKey) .map(channelsById::get) - .map(channelStatus -> { - // update name so that current name is used - channelStatus - .setName(guild.getGuildChannelById(channelStatus.getChannelID()).getName()); - return channelStatus; - }) - .map(ChannelStatus::toDiscord) - .collect(Collectors.joining("\n")); + .toList(); + + // update name so that current channel name is used + statusFor.forEach(channelStatus -> channelStatus + .setName(guild.getGuildChannelById(channelStatus.getChannelID()).getName())); + String message = + statusFor.stream().map(ChannelStatus::toDiscord).collect(Collectors.joining("\n")); channel.getLatestMessageIdLong(); channel.sendMessage(message).queue(); - // Not implemented yet return message; } @@ -155,12 +206,24 @@ public void onEvent(@NotNull GenericEvent event) { } ChannelStatus status = channelsById.get(castEvent.getChannel().getIdLong()); if (status == null || status.isBusy()) { - logger.debug("Channel status is currently busy, skipping message {}", status); + logger.debug("Channel status is currently busy, ignoring message received. {} ", + status); return; } status.busy(ChannelStatus.BUSY); + drawStatus(getStatusChannelFor(castEvent.getGuild())); castEvent.getMessage().reply("The channel was free, please ask your question").queue(); - } } + + private TextChannel getStatusChannelFor(@NotNull final Guild guild) { + // todo add error checking for invalid keys ?? + return guild.getTextChannelById(guildToStatusChannel.get(guild.getIdLong())); + } + + private Optional getStatusMessageIn(TextChannel channel) { + channel.getHistory().retrievePast(100).queue(); + + return Optional.empty(); + } } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/free/Util.java b/application/src/main/java/org/togetherjava/tjbot/commands/free/Util.java index 4b2a3b85e4..bc4970bf9a 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/free/Util.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/free/Util.java @@ -1,6 +1,7 @@ package org.togetherjava.tjbot.commands.free; import net.dv8tion.jda.api.interactions.Interaction; +import org.jetbrains.annotations.NotNull; public class Util { // private constructor to prevent this class getting instantiated @@ -12,7 +13,8 @@ private Util() {} * @param interaction The event or hook that this message is responding to * @param message The text to be display for the user to read. */ - public static void sendErrorMessage(Interaction interaction, String message) { + public static void sendErrorMessage(@NotNull Interaction interaction, @NotNull String message) { interaction.reply(message).setEphemeral(true).queue(); } + } 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 048fee5a26..e0f4486a81 100644 --- a/application/src/main/java/org/togetherjava/tjbot/config/Config.java +++ b/application/src/main/java/org/togetherjava/tjbot/config/Config.java @@ -102,8 +102,11 @@ public String getDiscordGuildInvite() { } /** + * Gets a List of channel id's required to configure the free command system see + * {@link FreeCommandConfig} * - * @return an + * @return a List of instances of FreeCommandConfig, each of the instances are separated by + * guild. */ public Collection getFreeCommandConfig() { return freeCommand; diff --git a/application/src/main/java/org/togetherjava/tjbot/config/FreeCommandConfig.java b/application/src/main/java/org/togetherjava/tjbot/config/FreeCommandConfig.java index 835c620e04..0ee1e85813 100644 --- a/application/src/main/java/org/togetherjava/tjbot/config/FreeCommandConfig.java +++ b/application/src/main/java/org/togetherjava/tjbot/config/FreeCommandConfig.java @@ -8,18 +8,30 @@ import java.util.Collection; import java.util.List; +/** + * Config instance for the Free Command System see + * {@link org.togetherjava.tjbot.commands.free.FreeCommand} + * + * The Json looks as follows: + * + *
+ * "freeCommand": [
+ *   {
+ *       "statusChannel": long_number,
+ *       "monitoredChannels": [long_number, long_number]
+ *   }]
+ * 
+ * + * Additional Guilds may add their settings by adding additional {"statusChannel....... } + * + * The long channel ID can be found by right-clicking on the channel and selecting 'Copy ID' + */ @SuppressWarnings("ClassCanBeRecord") @JsonRootName(value = "freeCommand") public final class FreeCommandConfig { private final long statusChannel; private final List monitoredChannels; - /** - * //todo add java docs, include required json format to configure this - * - * @param statusChannel - * @param monitoredChannels - */ @JsonCreator private FreeCommandConfig(@JsonProperty("statusChannel") long statusChannel, @JsonProperty("monitoredChannels") long[] monitoredChannels) { @@ -28,17 +40,19 @@ private FreeCommandConfig(@JsonProperty("statusChannel") long statusChannel, } /** - * Gets the channelID where the status message will be displayed. + * Retrieves the channelID where the status message will be displayed. * - * @return the channelID for the status message + * @return the Channel ID where the Status Message is expected to be displayed */ public long getStatusChannel() { return statusChannel; } /** + * Retrieves a List of the channels on this guild that the guild wants monitored by the + * free/busy command system * - * @return + * @return an Unmodifiable List of Channel ID's */ public Collection getMonitoredChannels() { return monitoredChannels; From 672608c3f0e8aef6334ecf70b227d175877e8397 Mon Sep 17 00:00:00 2001 From: Daniel Tischner Date: Thu, 21 Oct 2021 12:21:39 +0200 Subject: [PATCH 08/10] Added JDA mock and tests Co-authored-by: Heatmanofurioso --- application/build.gradle | 2 + .../commands/basic/DatabaseCommandTest.java | 153 +++++++++++ .../tjbot/commands/basic/PingCommandTest.java | 22 ++ .../commands/system/ReloadCommandTest.java | 4 +- .../org/togetherjava/tjbot/jda/JdaTester.java | 138 ++++++++++ .../tjbot/jda/PayloadSlashCommand.java | 113 ++++++++ .../tjbot/jda/PayloadSlashCommandData.java | 60 +++++ .../tjbot/jda/PayloadSlashCommandMember.java | 145 ++++++++++ .../tjbot/jda/PayloadSlashCommandOption.java | 60 +++++ .../tjbot/jda/PayloadSlashCommandUser.java | 66 +++++ .../tjbot/jda/SlashCommandEventBuilder.java | 252 ++++++++++++++++++ .../togetherjava/tjbot/jda/package-info.java | 5 + 12 files changed, 1018 insertions(+), 2 deletions(-) create mode 100644 application/src/test/java/org/togetherjava/tjbot/commands/basic/DatabaseCommandTest.java create mode 100644 application/src/test/java/org/togetherjava/tjbot/commands/basic/PingCommandTest.java create mode 100644 application/src/test/java/org/togetherjava/tjbot/jda/JdaTester.java create mode 100644 application/src/test/java/org/togetherjava/tjbot/jda/PayloadSlashCommand.java create mode 100644 application/src/test/java/org/togetherjava/tjbot/jda/PayloadSlashCommandData.java create mode 100644 application/src/test/java/org/togetherjava/tjbot/jda/PayloadSlashCommandMember.java create mode 100644 application/src/test/java/org/togetherjava/tjbot/jda/PayloadSlashCommandOption.java create mode 100644 application/src/test/java/org/togetherjava/tjbot/jda/PayloadSlashCommandUser.java create mode 100644 application/src/test/java/org/togetherjava/tjbot/jda/SlashCommandEventBuilder.java create mode 100644 application/src/test/java/org/togetherjava/tjbot/jda/package-info.java diff --git a/application/build.gradle b/application/build.gradle index ab2815d6fb..ce7e55194a 100644 --- a/application/build.gradle +++ b/application/build.gradle @@ -60,6 +60,8 @@ dependencies { implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-csv:2.13.0' implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.0' + testImplementation 'org.mockito:mockito-core:3.12.4' + testRuntimeOnly 'org.mockito:mockito-core:3.12.4' testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1' } diff --git a/application/src/test/java/org/togetherjava/tjbot/commands/basic/DatabaseCommandTest.java b/application/src/test/java/org/togetherjava/tjbot/commands/basic/DatabaseCommandTest.java new file mode 100644 index 0000000000..2712ba78d1 --- /dev/null +++ b/application/src/test/java/org/togetherjava/tjbot/commands/basic/DatabaseCommandTest.java @@ -0,0 +1,153 @@ +package org.togetherjava.tjbot.commands.basic; + +import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; +import org.jetbrains.annotations.NotNull; +import org.jooq.Record1; +import org.jooq.Result; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.togetherjava.tjbot.commands.SlashCommand; +import org.togetherjava.tjbot.db.Database; +import org.togetherjava.tjbot.db.generated.tables.Storage; +import org.togetherjava.tjbot.db.generated.tables.records.StorageRecord; +import org.togetherjava.tjbot.jda.JdaTester; + +import java.sql.SQLException; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +final class DatabaseCommandTest { + + private Database database; + + private static SlashCommandEvent createGet(@NotNull String value, @NotNull SlashCommand command, + @NotNull JdaTester jdaTester) { + return jdaTester.createSlashCommandEvent(command) + .subcommand("get") + .option("key", value) + .build(); + } + + private static SlashCommandEvent createPut(@NotNull String key, @NotNull String value, + @NotNull SlashCommand command, @NotNull JdaTester jdaTester) { + return jdaTester.createSlashCommandEvent(command) + .subcommand("put") + .option("key", key) + .option("value", value) + .build(); + } + + @BeforeEach + void setupDatabase() throws SQLException { + // TODO This has to be done dynamically by the Flyway script, adjust gradle test settings + database = new Database("jdbc:sqlite:"); + database.write(context -> { + context.ddl(Storage.STORAGE).executeBatch(); + }); + } + + @Test + void getNoKey() { + SlashCommand command = new DatabaseCommand(database); + JdaTester jdaTester = new JdaTester(); + + SlashCommandEvent event = createGet("foo", command, jdaTester); + command.onSlashCommand(event); + + verify(event, times(1)).reply("Nothing found for the key 'foo'"); + } + + @Test + void getValidKey() { + SlashCommand command = new DatabaseCommand(database); + JdaTester jdaTester = new JdaTester(); + + putIntoDatabase("foo", "bar"); + + SlashCommandEvent event = createGet("foo", command, jdaTester); + command.onSlashCommand(event); + + verify(event, times(1)).reply("Saved message: bar"); + } + + @Test + void putEmpty() { + SlashCommand command = new DatabaseCommand(database); + JdaTester jdaTester = new JdaTester(); + + SlashCommandEvent event = createPut("foo", "bar", command, jdaTester); + command.onSlashCommand(event); + + verify(event, times(1)).reply("Saved under 'foo'."); + assertValueInDatabase("foo", "bar"); + } + + @Test + void putOverride() { + SlashCommand command = new DatabaseCommand(database); + JdaTester jdaTester = new JdaTester(); + + SlashCommandEvent event = createPut("foo", "bar", command, jdaTester); + command.onSlashCommand(event); + + event = createPut("foo", "baz", command, jdaTester); + command.onSlashCommand(event); + + verify(event, times(1)).reply("Saved under 'foo'."); + assertValueInDatabase("foo", "baz"); + } + + @Test + void getPutGet() { + SlashCommand command = new DatabaseCommand(database); + JdaTester jdaTester = new JdaTester(); + + SlashCommandEvent getEvent = createGet("foo", command, jdaTester); + command.onSlashCommand(getEvent); + verify(getEvent, times(1)).reply("Nothing found for the key 'foo'"); + + SlashCommandEvent putEvent = createPut("foo", "bar", command, jdaTester); + command.onSlashCommand(putEvent); + verify(putEvent, times(1)).reply("Saved under 'foo'."); + + command.onSlashCommand(getEvent); + verify(getEvent, times(1)).reply("Saved message: bar"); + } + + @Test + void getOrPutWithNoTable() throws SQLException { + SlashCommand command = new DatabaseCommand(new Database("jdbc:sqlite:")); + JdaTester jdaTester = new JdaTester(); + + SlashCommandEvent event = createGet("foo", command, jdaTester); + command.onSlashCommand(event); + verify(event, times(1)).reply("Sorry, something went wrong."); + + event = createPut("foo", "bar", command, jdaTester); + command.onSlashCommand(event); + verify(event, times(1)).reply("Sorry, something went wrong."); + } + + private void assertValueInDatabase(@NotNull String key, @NotNull String value) { + Result> results = database.read(context -> { + try (var select = context.select(Storage.STORAGE.VALUE)) { + return select.from(Storage.STORAGE).where(Storage.STORAGE.KEY.eq(key)).fetch(); + } + }); + assertEquals(1, results.size()); + assertEquals(value, results.get(0).get(Storage.STORAGE.VALUE)); + } + + private void putIntoDatabase(@NotNull String key, @NotNull String value) { + database.write(context -> { + StorageRecord storageRecord = + context.newRecord(Storage.STORAGE).setKey(key).setValue(value); + if (storageRecord.update() == 0) { + storageRecord.insert(); + } + }); + } + +} diff --git a/application/src/test/java/org/togetherjava/tjbot/commands/basic/PingCommandTest.java b/application/src/test/java/org/togetherjava/tjbot/commands/basic/PingCommandTest.java new file mode 100644 index 0000000000..457b7e3bec --- /dev/null +++ b/application/src/test/java/org/togetherjava/tjbot/commands/basic/PingCommandTest.java @@ -0,0 +1,22 @@ +package org.togetherjava.tjbot.commands.basic; + +import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; +import org.junit.jupiter.api.Test; +import org.togetherjava.tjbot.commands.SlashCommand; +import org.togetherjava.tjbot.jda.JdaTester; + +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +final class PingCommandTest { + @Test + void pingCommand() { + SlashCommand command = new PingCommand(); + JdaTester jdaTester = new JdaTester(); + + SlashCommandEvent event = jdaTester.createSlashCommandEvent(command).build(); + command.onSlashCommand(event); + + verify(event, times(1)).reply("Pong!"); + } +} diff --git a/application/src/test/java/org/togetherjava/tjbot/commands/system/ReloadCommandTest.java b/application/src/test/java/org/togetherjava/tjbot/commands/system/ReloadCommandTest.java index ad251f36eb..28ac0d29cc 100644 --- a/application/src/test/java/org/togetherjava/tjbot/commands/system/ReloadCommandTest.java +++ b/application/src/test/java/org/togetherjava/tjbot/commands/system/ReloadCommandTest.java @@ -13,8 +13,8 @@ final class ReloadCommandTest { @Test void ReloadCommand() { - // noinspection - // AnonymousInnerClassWithTooManyMethods,AnonymousInnerClass,AnonymousInnerClassMayBeStatic + @SuppressWarnings({"AnonymousInnerClassWithTooManyMethods", "AnonymousInnerClass", + "AnonymousInnerClassMayBeStatic"}) SlashCommandProvider slashCommandProvider = new SlashCommandProvider() { @Override public @NotNull Collection getSlashCommands() { diff --git a/application/src/test/java/org/togetherjava/tjbot/jda/JdaTester.java b/application/src/test/java/org/togetherjava/tjbot/jda/JdaTester.java new file mode 100644 index 0000000000..5c6ed68067 --- /dev/null +++ b/application/src/test/java/org/togetherjava/tjbot/jda/JdaTester.java @@ -0,0 +1,138 @@ +package org.togetherjava.tjbot.jda; + +import net.dv8tion.jda.api.Permission; +import net.dv8tion.jda.api.entities.SelfUser; +import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; +import net.dv8tion.jda.api.requests.restaction.MessageAction; +import net.dv8tion.jda.api.utils.ConcurrentSessionController; +import net.dv8tion.jda.api.utils.cache.CacheFlag; +import net.dv8tion.jda.internal.JDAImpl; +import net.dv8tion.jda.internal.entities.*; +import net.dv8tion.jda.internal.requests.Requester; +import net.dv8tion.jda.internal.requests.restaction.MessageActionImpl; +import net.dv8tion.jda.internal.requests.restaction.interactions.ReplyActionImpl; +import net.dv8tion.jda.internal.utils.config.AuthorizationConfig; +import org.jetbrains.annotations.NotNull; +import org.mockito.ArgumentMatchers; +import org.togetherjava.tjbot.commands.SlashCommand; + +import java.util.EnumSet; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.function.UnaryOperator; + +import static org.mockito.Mockito.*; + +/** + * Utility class for testing {@link SlashCommand}s. + *

+ * Mocks JDA and can create events that can be used to test {@link SlashCommand}s, e.g. + * {@link #createSlashCommandEvent(SlashCommand)}. The created events are Mockito mocks, which can + * be exploited for testing. + *

+ * An example test using this class might look like: + * + *

+ * {
+ *     @code
+ *     SlashCommand command = new PingCommand();
+ *     JdaTester jdaTester = new JdaTester();
+ *
+ *     SlashCommandEvent event = jdaTester.createSlashCommandEvent(command).build();
+ *     command.onSlashCommand(event);
+ *
+ *     verify(event, times(1)).reply("Pong!");
+ * }
+ * 
+ */ +public final class JdaTester { + private static final ScheduledExecutorService GATEWAY_POOL = new ScheduledThreadPoolExecutor(4); + private static final ScheduledExecutorService RATE_LIMIT_POOL = + new ScheduledThreadPoolExecutor(4); + private static final String TEST_TOKEN = "TEST_TOKEN"; + private static final long USER_ID = 1; + private static final long APPLICATION_ID = 1; + private static final long PRIVATE_CHANNEL_ID = 1; + private static final long GUILD_ID = 1; + private static final long TEXT_CHANNEL_ID = 1; + + private final JDAImpl jda; + private final MemberImpl member; + + /** + * Creates a new instance. The instance uses a fresh and isolated mocked JDA setup. + *

+ * Reusing this instance also means to reuse guilds, text channels and such from this JDA setup, + * which can have an impact on tests. For example a previous text that already send messages to + * a channel, the messages will then still be present in the instance. + */ + public JdaTester() { + // TODO Extend this functionality, make it nicer. + // Maybe offer a builder for multiple users and channels and what not + jda = mock(JDAImpl.class); + when(jda.getCacheFlags()).thenReturn(EnumSet.noneOf(CacheFlag.class)); + + SelfUser selfUser = mock(SelfUserImpl.class); + UserImpl user = spy(new UserImpl(USER_ID, jda)); + GuildImpl guild = spy(new GuildImpl(jda, GUILD_ID)); + member = spy(new MemberImpl(guild, user)); + TextChannelImpl textChannel = spy(new TextChannelImpl(TEXT_CHANNEL_ID, guild)); + PrivateChannelImpl privateChannel = spy(new PrivateChannelImpl(PRIVATE_CHANNEL_ID, user)); + MessageAction messageAction = mock(MessageActionImpl.class); + EntityBuilder entityBuilder = mock(EntityBuilder.class); + + // TODO Depending on the commands we might need a lot more mocking here + when(entityBuilder.createUser(any())).thenReturn(user); + when(entityBuilder.createMember(any(), any())).thenReturn(member); + // TODO Giving out all permissions makes it impossible to test permission requirements on + // commands + doReturn(true).when(member).hasPermission(ArgumentMatchers.any()); + when(selfUser.getApplicationId()).thenReturn(String.valueOf(APPLICATION_ID)); + when(selfUser.getApplicationIdLong()).thenReturn(APPLICATION_ID); + doReturn(selfUser).when(jda).getSelfUser(); + when(jda.getGuildChannelById(anyLong())).thenReturn(textChannel); + when(jda.getPrivateChannelById(anyLong())).thenReturn(privateChannel); + when(jda.getGuildById(anyLong())).thenReturn(guild); + when(jda.getEntityBuilder()).thenReturn(entityBuilder); + + when(jda.getGatewayPool()).thenReturn(GATEWAY_POOL); + when(jda.getRateLimitPool()).thenReturn(RATE_LIMIT_POOL); + when(jda.getSessionController()).thenReturn(new ConcurrentSessionController()); + doReturn(new Requester(jda, new AuthorizationConfig(TEST_TOKEN))).when(jda).getRequester(); + + doReturn(messageAction).when(privateChannel).sendMessage(anyString()); + } + + /** + * Creates a Mockito mocked slash command event, which can be used for + * {@link SlashCommand#onSlashCommand(SlashCommandEvent)}. + *

+ * The method creates a builder that can be used to further adjust the event before creation, + * e.g. provide options. + * + * @param command the command to create an event for + * @return a builder used to create a Mockito mocked slash command event + */ + public @NotNull SlashCommandEventBuilder createSlashCommandEvent( + @NotNull SlashCommand command) { + UnaryOperator mockOperator = event -> { + SlashCommandEvent slashCommandEvent = spy(event); + ReplyActionImpl replyAction = mock(ReplyActionImpl.class); + + doReturn(replyAction).when(slashCommandEvent).reply(anyString()); + when(replyAction.setEphemeral(anyBoolean())).thenReturn(replyAction); + doReturn(member).when(slashCommandEvent).getMember(); + + return slashCommandEvent; + }; + + return new SlashCommandEventBuilder(jda, mockOperator).command(command) + .token(TEST_TOKEN) + .channelId(String.valueOf(TEXT_CHANNEL_ID)) + .applicationId(String.valueOf(APPLICATION_ID)) + .guildId(String.valueOf(GUILD_ID)) + .userId(String.valueOf(USER_ID)); + } + + // TODO Add methods to create button and menu events as well +} diff --git a/application/src/test/java/org/togetherjava/tjbot/jda/PayloadSlashCommand.java b/application/src/test/java/org/togetherjava/tjbot/jda/PayloadSlashCommand.java new file mode 100644 index 0000000000..2dca9e0837 --- /dev/null +++ b/application/src/test/java/org/togetherjava/tjbot/jda/PayloadSlashCommand.java @@ -0,0 +1,113 @@ +package org.togetherjava.tjbot.jda; + +import com.fasterxml.jackson.annotation.JsonProperty; +import org.jetbrains.annotations.NotNull; + +final class PayloadSlashCommand { + @JsonProperty("guild_id") + private String guildId; + private String id; + private int type; + private int version; + @JsonProperty("channel_id") + private String channelId; + @JsonProperty("application_id") + private String applicationId; + private String token; + private PayloadSlashCommandMember member; + private PayloadSlashCommandData data; + + @SuppressWarnings("ConstructorWithTooManyParameters") + PayloadSlashCommand(@NotNull String guildId, @NotNull String id, int type, int version, + @NotNull String channelId, @NotNull String applicationId, @NotNull String token, + @NotNull PayloadSlashCommandMember member, @NotNull PayloadSlashCommandData data) { + this.guildId = guildId; + this.id = id; + this.type = type; + this.version = version; + this.channelId = channelId; + this.applicationId = applicationId; + this.token = token; + this.member = member; + this.data = data; + } + + @NotNull + public String getGuildId() { + return guildId; + } + + public void setGuildId(@NotNull String guildId) { + this.guildId = guildId; + } + + @NotNull + public String getId() { + return id; + } + + public void setId(@NotNull String id) { + this.id = id; + } + + public int getType() { + return type; + } + + public void setType(int type) { + this.type = type; + } + + public int getVersion() { + return version; + } + + public void setVersion(int version) { + this.version = version; + } + + @NotNull + public String getChannelId() { + return channelId; + } + + public void setChannelId(@NotNull String channelId) { + this.channelId = channelId; + } + + @NotNull + public String getApplicationId() { + return applicationId; + } + + public void setApplicationId(@NotNull String applicationId) { + this.applicationId = applicationId; + } + + @NotNull + public String getToken() { + return token; + } + + public void setToken(@NotNull String token) { + this.token = token; + } + + @NotNull + public PayloadSlashCommandMember getMember() { + return member; + } + + public void setMember(@NotNull PayloadSlashCommandMember member) { + this.member = member; + } + + @NotNull + public PayloadSlashCommandData getData() { + return data; + } + + public void setData(@NotNull PayloadSlashCommandData data) { + this.data = data; + } +} diff --git a/application/src/test/java/org/togetherjava/tjbot/jda/PayloadSlashCommandData.java b/application/src/test/java/org/togetherjava/tjbot/jda/PayloadSlashCommandData.java new file mode 100644 index 0000000000..18a79c32ab --- /dev/null +++ b/application/src/test/java/org/togetherjava/tjbot/jda/PayloadSlashCommandData.java @@ -0,0 +1,60 @@ +package org.togetherjava.tjbot.jda; + +import com.fasterxml.jackson.annotation.JsonInclude; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +final class PayloadSlashCommandData { + private String name; + private String id; + private int type; + @JsonInclude(JsonInclude.Include.NON_NULL) + private List options; + + PayloadSlashCommandData(@NotNull String name, @NotNull String id, int type, + @Nullable List options) { + this.name = name; + this.id = id; + this.type = type; + this.options = options == null ? null : new ArrayList<>(options); + } + + @NotNull + public String getName() { + return name; + } + + public void setName(@NotNull String name) { + this.name = name; + } + + @NotNull + public String getId() { + return id; + } + + public void setId(@NotNull String id) { + this.id = id; + } + + public int getType() { + return type; + } + + public void setType(int type) { + this.type = type; + } + + @Nullable + public List getOptions() { + return options == null ? null : Collections.unmodifiableList(options); + } + + public void setOptions(@Nullable List options) { + this.options = options == null ? null : new ArrayList<>(options); + } +} diff --git a/application/src/test/java/org/togetherjava/tjbot/jda/PayloadSlashCommandMember.java b/application/src/test/java/org/togetherjava/tjbot/jda/PayloadSlashCommandMember.java new file mode 100644 index 0000000000..7bef0d3d52 --- /dev/null +++ b/application/src/test/java/org/togetherjava/tjbot/jda/PayloadSlashCommandMember.java @@ -0,0 +1,145 @@ +package org.togetherjava.tjbot.jda; + +import com.fasterxml.jackson.annotation.JsonProperty; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +@SuppressWarnings("ClassWithTooManyFields") +final class PayloadSlashCommandMember { + @JsonProperty("premium_since") + private String premiumSince; + private String nick; + @JsonProperty("joined_at") + private String joinedAt; + private String permissions; + private List roles; + private boolean pending; + private boolean deaf; + private boolean mute; + private String avatar; + @JsonProperty("is_pending") + private boolean isPending; + private PayloadSlashCommandUser user; + + @SuppressWarnings("ConstructorWithTooManyParameters") + PayloadSlashCommandMember(@Nullable String premiumSince, @Nullable String nick, + @NotNull String joinedAt, @NotNull String permissions, @NotNull List roles, + boolean pending, boolean deaf, boolean mute, @Nullable String avatar, boolean isPending, + PayloadSlashCommandUser user) { + this.premiumSince = premiumSince; + this.nick = nick; + this.joinedAt = joinedAt; + this.permissions = permissions; + this.roles = new ArrayList<>(roles); + this.pending = pending; + this.deaf = deaf; + this.mute = mute; + this.avatar = avatar; + this.isPending = isPending; + this.user = user; + } + + public @NotNull PayloadSlashCommandUser getUser() { + return user; + } + + public void setUser(@NotNull PayloadSlashCommandUser user) { + this.user = user; + } + + @Nullable + public String getPremiumSince() { + return premiumSince; + } + + public void setPremiumSince(@Nullable String premiumSince) { + this.premiumSince = premiumSince; + } + + @Nullable + public String getNick() { + return nick; + } + + public void setNick(@Nullable String nick) { + this.nick = nick; + } + + @NotNull + public String getJoinedAt() { + return joinedAt; + } + + public void setJoinedAt(@NotNull String joinedAt) { + this.joinedAt = joinedAt; + } + + @NotNull + public String getPermissions() { + return permissions; + } + + public void setPermissions(@NotNull String permissions) { + this.permissions = permissions; + } + + @NotNull + public List getRoles() { + return Collections.unmodifiableList(roles); + } + + public void setRoles(@NotNull List roles) { + this.roles = new ArrayList<>(roles); + } + + // NOTE This is a problem in Discord, which has "pending" and "isPending" fields both at the + // same time. + @SuppressWarnings("SuspiciousGetterSetter") + public boolean isPending() { + return isPending; + } + + public void setIsPending(boolean isPending) { + this.isPending = isPending; + } + + // NOTE This is a problem in Discord, which has "pending" and "isPending" fields both at the + // same time. + @SuppressWarnings("BooleanMethodNameMustStartWithQuestion") + public boolean getPending() { + return pending; + } + + public void setPending(boolean pending) { + this.pending = pending; + } + + public boolean isDeaf() { + return deaf; + } + + public void setDeaf(boolean deaf) { + this.deaf = deaf; + } + + public boolean isMute() { + return mute; + } + + public void setMute(boolean mute) { + this.mute = mute; + } + + @Nullable + public String getAvatar() { + return avatar; + } + + public void setAvatar(@Nullable String avatar) { + this.avatar = avatar; + } +} diff --git a/application/src/test/java/org/togetherjava/tjbot/jda/PayloadSlashCommandOption.java b/application/src/test/java/org/togetherjava/tjbot/jda/PayloadSlashCommandOption.java new file mode 100644 index 0000000000..deb18329e4 --- /dev/null +++ b/application/src/test/java/org/togetherjava/tjbot/jda/PayloadSlashCommandOption.java @@ -0,0 +1,60 @@ +package org.togetherjava.tjbot.jda; + +import com.fasterxml.jackson.annotation.JsonInclude; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +final class PayloadSlashCommandOption { + private String name; + private int type; + private String value; + @JsonInclude(JsonInclude.Include.NON_NULL) + private List options; + + PayloadSlashCommandOption(@NotNull String name, int type, @Nullable String value, + @Nullable List options) { + this.name = name; + this.type = type; + this.value = value; + this.options = options == null ? null : new ArrayList<>(options); + } + + @NotNull + public String getName() { + return name; + } + + public void setName(@NotNull String name) { + this.name = name; + } + + public int getType() { + return type; + } + + public void setType(int type) { + this.type = type; + } + + @Nullable + public String getValue() { + return value; + } + + public void setValue(@Nullable String value) { + this.value = value; + } + + @Nullable + public List getOptions() { + return options == null ? null : Collections.unmodifiableList(options); + } + + public void setOptions(@Nullable List options) { + this.options = options == null ? null : new ArrayList<>(options); + } +} diff --git a/application/src/test/java/org/togetherjava/tjbot/jda/PayloadSlashCommandUser.java b/application/src/test/java/org/togetherjava/tjbot/jda/PayloadSlashCommandUser.java new file mode 100644 index 0000000000..8042bab3e9 --- /dev/null +++ b/application/src/test/java/org/togetherjava/tjbot/jda/PayloadSlashCommandUser.java @@ -0,0 +1,66 @@ +package org.togetherjava.tjbot.jda; + +import com.fasterxml.jackson.annotation.JsonProperty; +import org.jetbrains.annotations.NotNull; + +final class PayloadSlashCommandUser { + @JsonProperty("public_flags") + private int publicFlags; + private String id; + private String avatar; + private String username; + private String discriminator; + + PayloadSlashCommandUser(int publicFlags, @NotNull String id, @NotNull String avatar, + @NotNull String username, @NotNull String discriminator) { + this.publicFlags = publicFlags; + this.id = id; + this.avatar = avatar; + this.username = username; + this.discriminator = discriminator; + } + + public int getPublicFlags() { + return publicFlags; + } + + public void setPublicFlags(int publicFlags) { + this.publicFlags = publicFlags; + } + + @NotNull + public String getId() { + return id; + } + + public void setId(@NotNull String id) { + this.id = id; + } + + @NotNull + public String getAvatar() { + return avatar; + } + + public void setAvatar(@NotNull String avatar) { + this.avatar = avatar; + } + + @NotNull + public String getUsername() { + return username; + } + + public void setUsername(@NotNull String username) { + this.username = username; + } + + @NotNull + public String getDiscriminator() { + return discriminator; + } + + public void setDiscriminator(@NotNull String discriminator) { + this.discriminator = discriminator; + } +} diff --git a/application/src/test/java/org/togetherjava/tjbot/jda/SlashCommandEventBuilder.java b/application/src/test/java/org/togetherjava/tjbot/jda/SlashCommandEventBuilder.java new file mode 100644 index 0000000000..6cca185720 --- /dev/null +++ b/application/src/test/java/org/togetherjava/tjbot/jda/SlashCommandEventBuilder.java @@ -0,0 +1,252 @@ +package org.togetherjava.tjbot.jda; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; +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.utils.data.DataObject; +import net.dv8tion.jda.internal.JDAImpl; +import net.dv8tion.jda.internal.interactions.CommandInteractionImpl; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.togetherjava.tjbot.commands.SlashCommand; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; + +/** + * Builder to create slash command events that can be used for example with + * {@link SlashCommand#onSlashCommand(SlashCommandEvent)}. + *

+ * Create instances of this class by using {@link JdaTester#createSlashCommandEvent(SlashCommand)}. + *

+ * Among other Discord related things, the builder optionally accepts a subcommand + * ({@link #subcommand(String)}) and options ({@link #option(String, String)}). An already set + * subcommand can be cleared by using {@link #subcommand(String)} with {@code null}, options are + * cleared using {@link #clearOptions()}. + *

+ * Refer to the following examples: the command {@code ping} is build using + * + *

+ * {@code
+ * // /ping
+ * jdaTester.createSlashCommandEvent(command).build();
+ *
+ * // /days start:10.01.2021 end:13.01.2021
+ * jdaTester.createSlashCommandEvent(command)
+ *   .option("start", "10.01.2021")
+ *   .option("end", "13.01.2021")
+ *   .build();
+ *
+ * // /db put key:foo value:bar
+ * jdaTester.createSlashCommandEvent(command)
+ *   .subcommand("put")
+ *   .option("key", "foo")
+ *   .option("value", "bar")
+ *   .build();
+ * }
+ * 
+ */ +@SuppressWarnings("ClassWithTooManyFields") +public final class SlashCommandEventBuilder { + private static final ObjectMapper JSON = new ObjectMapper(); + private final JDAImpl jda; + private final UnaryOperator mockOperator; + private String token; + private String channelId; + private String applicationId; + private String guildId; + private String userId; + private SlashCommand command; + private final Map nameToOption = new HashMap<>(); + private String subcommand; + + SlashCommandEventBuilder(@NotNull JDAImpl jda, UnaryOperator mockOperator) { + this.jda = jda; + this.mockOperator = mockOperator; + } + + /** + * Sets the given option, overriding an existing value under the same name. + *

+ * If {@link #subcommand(String)} is set, this option will be interpreted as option to the + * subcommand. + *

+ * Use {@link #clearOptions()} to clear any set options. + * + * @param name the name of the option + * @param value the value of the option + * @return this builder instance for chaining + * @throws IllegalArgumentException if the option does not exist in the corresponding command, + * as specified by its {@link SlashCommand#getData()} + */ + public @NotNull SlashCommandEventBuilder option(@NotNull String name, @NotNull String value) { + // TODO Also add overloads for other types + requireOption(name, OptionType.STRING); + nameToOption.put(name, new Option(name, value, OptionType.STRING)); + return this; + } + + /** + * Clears all options previously set with {@link #option(String, String)}. + * + * @return this builder instance for chaining + */ + public @NotNull SlashCommandEventBuilder clearOptions() { + nameToOption.clear(); + return this; + } + + /** + * Sets the given subcommand. Call with {@code null} to clear any previously set subcommand. + *

+ * Once set, all options set by {@link #option(String, String)} will be interpreted as options + * to this subcommand. + * + * @param subcommand the name of the subcommand or {@code null} to clear it + * @return this builder instance for chaining + * @throws IllegalArgumentException if the subcommand does not exist in the corresponding + * command, as specified by its {@link SlashCommand#getData()} + */ + public @NotNull SlashCommandEventBuilder subcommand(@Nullable String subcommand) { + if (subcommand != null) { + requireSubcommand(subcommand); + } + + this.subcommand = subcommand; + return this; + } + + @NotNull + SlashCommandEventBuilder command(@NotNull SlashCommand command) { + this.command = command; + return this; + } + + @NotNull + SlashCommandEventBuilder channelId(@NotNull String channelId) { + this.channelId = channelId; + return this; + } + + @NotNull + SlashCommandEventBuilder token(@NotNull String token) { + this.token = token; + return this; + } + + @NotNull + SlashCommandEventBuilder applicationId(@NotNull String applicationId) { + this.applicationId = applicationId; + return this; + } + + @NotNull + SlashCommandEventBuilder guildId(@NotNull String guildId) { + this.guildId = guildId; + return this; + } + + @NotNull + SlashCommandEventBuilder userId(@NotNull String userId) { + this.userId = userId; + return this; + } + + /** + * Builds an instance of a slash command event, corresponding to the current configuration of + * the builder. + * + * @return the created slash command instance + */ + public @NotNull SlashCommandEvent build() { + PayloadSlashCommand event = createEvent(); + + String json; + try { + json = JSON.writeValueAsString(event); + } catch (JsonProcessingException e) { + throw new IllegalStateException(e); + } + + return mockOperator.apply(new SlashCommandEvent(jda, 0, + new CommandInteractionImpl(jda, DataObject.fromJson(json)))); + } + + private @NotNull PayloadSlashCommand createEvent() { + // TODO Validate that required options are set, check that subcommand is given if the + // command has one + // TODO Make as much of this configurable as needed + PayloadSlashCommandUser user = new PayloadSlashCommandUser(0, userId, + "286b894dc74634202d251d591f63537d", "Test-User", "3452"); + PayloadSlashCommandMember member = + new PayloadSlashCommandMember(null, null, "2021-09-07T18:25:16.615000+00:00", + "1099511627775", List.of(), false, false, false, null, false, user); + + List options; + if (subcommand == null) { + options = extractOptionsOrNull(nameToOption); + } else { + options = List.of(new PayloadSlashCommandOption(subcommand, 1, null, + extractOptionsOrNull(nameToOption))); + } + PayloadSlashCommandData data = + new PayloadSlashCommandData(command.getName(), "1", 1, options); + + return new PayloadSlashCommand(guildId, "897425767397466123", 2, 1, channelId, + applicationId, token, member, data); + } + + private static @Nullable List extractOptionsOrNull( + @NotNull Map nameToOption) { + if (nameToOption.isEmpty()) { + return null; + } + return nameToOption.values() + .stream() + .map(option -> new PayloadSlashCommandOption(option.name(), option.type.ordinal(), + option.value(), null)) + .toList(); + } + + @SuppressWarnings("UnusedReturnValue") + private @NotNull OptionData requireOption(@NotNull String name, @NotNull OptionType type) { + List options = subcommand == null ? command.getData().getOptions() + : requireSubcommand(subcommand).getOptions(); + + Supplier exceptionMessageSupplier = () -> subcommand == null + ? "The command '%s' does not support an option with name '%s' and type '%s'" + .formatted(command.getName(), name, type) + : "The subcommand '%s' of command '%s' does not support an option with name '%s' and type '%s'" + .formatted(command.getName(), subcommand, name, type); + + return options.stream() + .filter(option -> name.equals(option.getName())) + .filter(option -> type == option.getType()) + .findAny() + .orElseThrow(() -> { + throw new IllegalArgumentException(exceptionMessageSupplier.get()); + }); + } + + private @NotNull SubcommandData requireSubcommand(@NotNull String name) { + return command.getData() + .getSubcommands() + .stream() + .filter(subcommandData -> name.equals(subcommandData.getName())) + .findAny() + .orElseThrow(() -> { + throw new IllegalArgumentException( + "The command '%s' does not support a subcommand with name '%s'" + .formatted(command.getName(), name)); + }); + } + + private record Option(@NotNull String name, @NotNull String value, @NotNull OptionType type) { + } +} diff --git a/application/src/test/java/org/togetherjava/tjbot/jda/package-info.java b/application/src/test/java/org/togetherjava/tjbot/jda/package-info.java new file mode 100644 index 0000000000..f157e47b53 --- /dev/null +++ b/application/src/test/java/org/togetherjava/tjbot/jda/package-info.java @@ -0,0 +1,5 @@ +/** + * Provides utilities for testing with JDA, such as mocks. See + * {@link org.togetherjava.tjbot.jda.JdaTester} as entry point. + */ +package org.togetherjava.tjbot.jda; From 95d7f323a998b15abfa2c0723c30636d2f00c4cf Mon Sep 17 00:00:00 2001 From: Jonas Date: Thu, 21 Oct 2021 15:34:37 +0200 Subject: [PATCH 09/10] Fix Javadoc code example for commands (#199) --- .../tjbot/commands/SlashCommandAdapter.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) 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 ef0f894b99..b461447eec 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommandAdapter.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/SlashCommandAdapter.java @@ -35,13 +35,13 @@ *

* Some example commands are available in {@link org.togetherjava.tjbot.commands.basic}. A minimal * setup would consist of a class like - * + * *

  * {
  *     @code
- *     class PingCommand extends SlashCommandAdapter {
- *         PingCommand() {
- *             super("ping", "responds with !pong", SlashCommandVisibility.GUILD);
+ *     public class PingCommand extends SlashCommandAdapter {
+ *         public PingCommand() {
+ *             super("ping", "Responds with 'Pong!'", SlashCommandVisibility.GUILD);
  *         }
  *
  *         @Override
@@ -51,7 +51,7 @@
  *     }
  * }
  * 
- * + * * and registration of an instance of that class in {@link Commands}. */ public abstract class SlashCommandAdapter implements SlashCommand { From 14d2ae6283d629aaeb6948033f4adbb47f0cc37f Mon Sep 17 00:00:00 2001 From: borgrel Date: Fri, 22 Oct 2021 16:36:23 +0200 Subject: [PATCH 10/10] added thread safety for 'busy' added javadocs --- .../tjbot/commands/free/ChannelStatus.java | 85 +++++++++- .../tjbot/commands/free/FreeCommand.java | 146 +++++++++++++++--- .../tjbot/commands/free/StatusMessage.java | 5 + 3 files changed, 206 insertions(+), 30 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/free/ChannelStatus.java b/application/src/main/java/org/togetherjava/tjbot/commands/free/ChannelStatus.java index 81f3b68b60..fc3dfabcb1 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/free/ChannelStatus.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/free/ChannelStatus.java @@ -1,10 +1,15 @@ package org.togetherjava.tjbot.commands.free; +import net.dv8tion.jda.api.JDA; +import net.dv8tion.jda.api.entities.TextChannel; import org.jetbrains.annotations.NotNull; import java.util.Objects; -public class ChannelStatus { +/** + * Class that tracks the current free/busy status of a channel that requires monitoring. + */ +public final class ChannelStatus { public static final boolean FREE = false; public static final boolean BUSY = true; @@ -12,38 +17,90 @@ public class ChannelStatus { private static final String BUSY_STATUS = ":red_circle:"; private final long channelID; - private boolean isBusy; + private volatile boolean isBusy; private String name; + /** + * Creates an instance of a Channel Status. + *

+ * This does not validate the id as that requires the JDA. Any ChannelStatus that gets created + * with an invalid id *should* be ignored and won't be invoked. (Since the Channel statuses are + * selected by retrieval of channels id's via the guild id, before retrieving the relevant + * ChannelStatuses). + * + * @param id the long id of the {@link net.dv8tion.jda.api.entities.TextChannel} to monitor. + */ protected ChannelStatus(long id) { channelID = id; isBusy = true; name = Long.toString(id); } + /** + * Retrieves whether the channel is currently busy/free. + *

+ * This value is volatile but is not thread safe in any other way. While statuses change + * frequently, each individual status instance *should* only be modified from a single source, + * since it represents only a single channel and modification will only be triggered by activity + * in that one channel. + * + * @return the current stored status related to the channel id. + */ public boolean isBusy() { return isBusy; } + /** + * Retrieves the id for the {@link net.dv8tion.jda.api.entities.TextChannel} that this instance + * represents. There is no guarantee that the id is valid according to the {@link JDA}. + * + * @return the {@link net.dv8tion.jda.api.entities.TextChannel} id. + */ public long getChannelID() { return channelID; } + /** + * Retrieves the locally stored name of the {@link net.dv8tion.jda.api.entities.TextChannel} + * this represents. This value is initialised to the channel id and as such is never null. The + * name should first be set by retrieving the name the {@link JDA} currently uses, before + * calling this. + *

+ * The recommended value to use is {@link TextChannel#getAsMention()}. + * + * @return The currently stored name of the channel, originally the long id as string. + */ public @NotNull String getName() { return name; } + /** + * Method used to keep the channel name up to date with the {@link JDA}. This method is not + * called automatically. Manually update before using the value. + *

+ * The recommended value to use is {@link TextChannel#getAsMention()} + *

+ * This method is called in multithreaded context, however the value is not expected to change + * regularly and will not break anything if its invalid so no has not been made thread safe. + * + * @param name the value to set the channel name to. + */ public void setName(String name) { this.name = Objects.requireNonNull(name); } - // todo make threadsafe? protected void busy(boolean isBusy) { this.isBusy = isBusy; } - - + // todo should I overload equals with equals(long) so that a Set may be used instead of a Map + /** + * The identity of this object of solely based on the id value. Compares the long id's and + * determines if they are equal. + * + * @param o the other object to test against + * @return whether the objects have the same id or not. + */ @Override public boolean equals(Object o) { if (this == o) @@ -54,15 +111,31 @@ public boolean equals(Object o) { return channelID == that.channelID; } + /** + * A String representation of the instance, gives the name and the current status. + * + * @return a String representation of the instance. + */ @Override public String toString() { return "ChannelStatus{ %s is %s }".formatted(name, isBusy ? "busy" : "not busy"); } + /** + * A {@link #toString()} method spetially formatted for Discord ({@link JDA}. Uses emojis by + * string representation. + * + * @return a String representation of ChannelStatus, formatted for Discord + */ public String toDiscord() { - return "%s\t%s".formatted(isBusy ? BUSY_STATUS : FREE_STATUS, name); + return "%s %s".formatted(isBusy ? BUSY_STATUS : FREE_STATUS, name); } + /** + * The hash that represents the instance. It is based only on the id value. + * + * @return the instance's hash. + */ @Override public int hashCode() { return Objects.hash(channelID); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/free/FreeCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/free/FreeCommand.java index 94d32a6678..46a4dd7bd3 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/free/FreeCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/free/FreeCommand.java @@ -1,9 +1,6 @@ package org.togetherjava.tjbot.commands.free; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.GuildChannel; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; +import net.dv8tion.jda.api.entities.*; import net.dv8tion.jda.api.events.GenericEvent; import net.dv8tion.jda.api.events.ReadyEvent; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; @@ -14,15 +11,17 @@ import org.slf4j.LoggerFactory; import org.togetherjava.tjbot.commands.SlashCommandAdapter; import org.togetherjava.tjbot.commands.SlashCommandVisibility; +import org.togetherjava.tjbot.commands.utils.MessageUtils; import org.togetherjava.tjbot.config.Config; import org.togetherjava.tjbot.config.FreeCommandConfig; +import java.awt.*; import java.util.*; +import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; -// todo (can SlashCommandVisibility be -// narrower than GUILD?) +// todo (can SlashCommandVisibility be narrower than GUILD?) // todo monitor all channels when list is empty? monitor none? // todo (use other emojis? use images?) // todo add command to add/remove/status channels to monitor @@ -54,7 +53,9 @@ */ public class FreeCommand extends SlashCommandAdapter implements EventListener { private static final Logger logger = LoggerFactory.getLogger(FreeCommand.class); + private static final String STATUS_TITLE = "**__CHANNEL STATUS__**\n\n"; private static final String FREE_COMMAND = "free"; + private static final Color FREE_COLOR = Color.decode("#CCCC00"); // Map to store channel ID's, use Guild.getChannels() to guarantee order for display private final Map channelsById; @@ -86,6 +87,19 @@ public FreeCommand() { isReady = false; } + /** + * Reaction to the 'onReady' event. This method binds the configurables to the + * {@link net.dv8tion.jda.api.JDA} instance. Including fetching the names of the channels this + * command monitors (as per the JDA) + *

+ * It also updates the Status messages in their relevant channels, so that the message is up to + * date. + *

+ * This also registers a new listener on the {@link net.dv8tion.jda.api.JDA}, this should be + * removed when the code base supports additional functionality + * + * @param event the event this method reacts to + */ @Override public void onReady(@NotNull final ReadyEvent event) { // todo remove this when onGuildMessageRecieved has another access point @@ -115,7 +129,7 @@ public void onReady(@NotNull final ReadyEvent event) { guildToStatusChannel.values() .stream() .map(event.getJDA()::getTextChannelById) - .forEach(this::drawStatus); + .forEach(this::displayStatus); isReady = true; } @@ -141,13 +155,21 @@ public void onSlashCommand(@NotNull final SlashCommandEvent event) { ChannelStatus status = channelsById.get(id); if (status.isBusy()) { status.busy(ChannelStatus.FREE); - drawStatus(getStatusChannelFor(event.getGuild())); + displayStatus(getStatusChannelFor(event.getGuild())); event.reply("This channel is now free.").queue(); } else { Util.sendErrorMessage(event, "This channel is already free, no changes made"); } } + /** + * Private method to test event to see if it should be processed. + * + * Will respond to users describing the problem if the event should not be processed. + * + * @param event the event to test for validity. + * @return true if the event should be processed false otherwise. + */ private boolean shouldHandle(@NotNull final SlashCommandEvent event) { if (!isReady) { logger.debug( @@ -158,7 +180,7 @@ private boolean shouldHandle(@NotNull final SlashCommandEvent event) { } if (!guildToStatusChannel.containsKey(event.getGuild().getIdLong())) { logger.error( - "Slash command used by {} in {}(channel: {}) when guild is not registed in Free Command", + "Slash command used by {} in {}(channel: {}) when guild is not registered in Free Command", event.getUser().getIdLong(), event.getGuild(), event.getChannel().getName()); Util.sendErrorMessage(event, "This guild (%s) is not configured to use the '/free' command, please add entries in the config, restart the bot and try again." @@ -176,9 +198,44 @@ private boolean shouldHandle(@NotNull final SlashCommandEvent event) { return true; } - public String drawStatus(TextChannel channel) { + /** + * Builds the message that will be displayed for users. + *

+ * This method dynamically builds the status message as per the current values on the guild, + * including the channel categories. This method will detect any changes made on the guild and + * represent those changes in the status message. + * + * @param channel the text channel the status message will be posted in. + */ + public void displayStatus(@NotNull TextChannel channel) { final Guild guild = channel.getGuild(); + String messageTxt = buildStatusMessage(guild); + MessageEmbed embed = MessageUtils.generateEmbed(STATUS_TITLE, messageTxt, + channel.getJDA().getSelfUser(), FREE_COLOR); + + long latestMessageId = channel.getLatestMessageIdLong(); + Optional statusMessage = getStatusMessageIn(channel); + channel.sendMessage("Message selected is: " + statusMessage).queue(); + if (statusMessage.isPresent()) { + Message message = statusMessage.get(); + if (message.getIdLong() != latestMessageId) { + message.delete(); + } else { + message.editMessageEmbeds(embed); + } + } + + channel.sendMessageEmbeds(embed).queue(); + } + + public String buildStatusMessage(@NotNull Guild guild) { + if (!guildToStatusChannel.containsKey(guild.getIdLong())) { + throw new IllegalArgumentException( + "The guild '%s(%s)' is not registered in the free command system" + .formatted(guild.getName(), guild.getIdLong())); + } + List statusFor = guild.getChannels() .stream() .map(GuildChannel::getIdLong) @@ -188,31 +245,46 @@ public String drawStatus(TextChannel channel) { // update name so that current channel name is used statusFor.forEach(channelStatus -> channelStatus - .setName(guild.getGuildChannelById(channelStatus.getChannelID()).getName())); - String message = - statusFor.stream().map(ChannelStatus::toDiscord).collect(Collectors.joining("\n")); + .setName(guild.getGuildChannelById(channelStatus.getChannelID()).getAsMention())); - channel.getLatestMessageIdLong(); - channel.sendMessage(message).queue(); + // dynamically separate channels by channel categories + StringBuilder sb = new StringBuilder(); + String categoryName = ""; + for (ChannelStatus status : statusFor) { + Category category = guild.getGuildChannelById(status.getChannelID()).getParent(); + if (category != null && !category.getName().equals(categoryName)) { + categoryName = category.getName(); + sb.append("\n__").append(categoryName).append("__\n"); + } + sb.append(status.toDiscord()).append("\n"); + } - return message; + return sb.toString(); } + /** + * Method for responding to 'onGuildMessageRecieved' this will need to be replaced by a more + * appropriate method when the bot has more functionality. + *

+ * Marks channels as busy when a user posts a message in a monitored channel that is currently free. + * + * @param event the generic event that includes the 'onGuildMessageReceived'. + */ @Override public void onEvent(@NotNull GenericEvent event) { - if (event instanceof GuildMessageReceivedEvent castEvent) { - if (castEvent.isWebhookMessage() || castEvent.getAuthor().isBot()) { + if (event instanceof GuildMessageReceivedEvent guildEvent) { + if (guildEvent.isWebhookMessage() || guildEvent.getAuthor().isBot()) { return; } - ChannelStatus status = channelsById.get(castEvent.getChannel().getIdLong()); + ChannelStatus status = channelsById.get(guildEvent.getChannel().getIdLong()); if (status == null || status.isBusy()) { logger.debug("Channel status is currently busy, ignoring message received. {} ", status); return; } status.busy(ChannelStatus.BUSY); - drawStatus(getStatusChannelFor(castEvent.getGuild())); - castEvent.getMessage().reply("The channel was free, please ask your question").queue(); + displayStatus(getStatusChannelFor(guildEvent.getGuild())); + guildEvent.getMessage().reply("The channel was free, please ask your question").queue(); } } @@ -221,9 +293,35 @@ private TextChannel getStatusChannelFor(@NotNull final Guild guild) { return guild.getTextChannelById(guildToStatusChannel.get(guild.getIdLong())); } - private Optional getStatusMessageIn(TextChannel channel) { - channel.getHistory().retrievePast(100).queue(); + private Optional getStatusMessageIn(@NotNull TextChannel channel) { + if (channelToStatusMessage.containsKey(channel.getIdLong())) { + Long id = channelToStatusMessage.get(channel.getIdLong()); + if (id == null) { + return Optional.empty(); + } + Message message = channel.getHistory().getMessageById(id); + if (message == null) { + return Optional.empty(); + } + return Optional.of(message); + } + return findExistingStatusMessage(channel); + } + + private Optional findExistingStatusMessage(@NotNull TextChannel channel) { + // will only run when bots starts, afterwards its stored in a map + Optional result = channel.getHistory() + .retrievePast(100) + .map(history -> history.stream() + .filter(message -> !message.getEmbeds().isEmpty()) + .filter(message -> message.getAuthor().equals(channel.getJDA().getSelfUser())) + .filter(message -> message.getEmbeds().get(0).getTitle().equals(STATUS_TITLE)) + .findFirst()) + .complete(); - return Optional.empty(); + Message mapping = result.orElse(null); + channelToStatusMessage.put(channel.getIdLong(), + mapping == null ? null : mapping.getIdLong()); + return result; } } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/free/StatusMessage.java b/application/src/main/java/org/togetherjava/tjbot/commands/free/StatusMessage.java index d4c683d95c..4f57d3f4c1 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/free/StatusMessage.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/free/StatusMessage.java @@ -7,6 +7,11 @@ import java.util.List; +/** + * A start at building a class for status messages. Most functionality that should be here is + * currently in {@link FreeCommand} + */ +@SuppressWarnings("c") public class StatusMessage { private final Guild guild; private final TextChannel postingChannel;