Skip to content

Commit e084d42

Browse files
committed
chore: update old references of secrets in config to secrets class
1 parent 1798bd7 commit e084d42

10 files changed

Lines changed: 56 additions & 103 deletions

File tree

application/src/main/java/org/togetherjava/tjbot/Application.java

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import org.togetherjava.tjbot.features.system.BotCore;
1616
import org.togetherjava.tjbot.logging.LogMarkers;
1717
import org.togetherjava.tjbot.logging.discord.DiscordLogging;
18+
import org.togetherjava.tjbot.secrets.Secrets;
1819

1920
import java.io.IOException;
2021
import java.nio.file.Files;
@@ -34,6 +35,7 @@ private Application() {
3435

3536
private static final Logger logger = LoggerFactory.getLogger(Application.class);
3637
private static final String DEFAULT_CONFIG_PATH = "config.json";
38+
private static final String DEFAULT_SECRETS_PATH = "secrets.json";
3739

3840
/**
3941
* Starts the application.
@@ -58,11 +60,21 @@ public static void main(final String[] args) {
5860
return;
5961
}
6062

63+
Path secretsPath = Path.of(args.length == 1 ? args[0] : DEFAULT_SECRETS_PATH);
64+
Secrets secrets;
65+
try {
66+
secrets = Secrets.load(secretsPath);
67+
} catch (IOException e) {
68+
logger.error("Unable to load the configuration file from path '{}'",
69+
configPath.toAbsolutePath(), e);
70+
return;
71+
}
72+
6173
Thread.setDefaultUncaughtExceptionHandler(Application::onUncaughtException);
6274
Runtime.getRuntime().addShutdownHook(new Thread(Application::onShutdown));
63-
DiscordLogging.startDiscordLogging(config);
75+
DiscordLogging.startDiscordLogging(config, secrets);
6476

65-
runBot(config);
77+
runBot(config, secrets);
6678
}
6779

6880
/**
@@ -71,7 +83,7 @@ public static void main(final String[] args) {
7183
* @param config the configuration to run the bot with
7284
*/
7385
@SuppressWarnings("WeakerAccess")
74-
public static void runBot(Config config) {
86+
public static void runBot(Config config, Secrets secrets) {
7587
logger.info("Starting bot...");
7688

7789
Path databasePath = Path.of(config.getDatabasePath());
@@ -82,13 +94,13 @@ public static void runBot(Config config) {
8294
}
8395
Database database = new Database("jdbc:sqlite:" + databasePath.toAbsolutePath());
8496

85-
JDA jda = JDABuilder.createDefault(config.getToken())
97+
JDA jda = JDABuilder.createDefault(secrets.getToken())
8698
.enableIntents(GatewayIntent.GUILD_MEMBERS, GatewayIntent.MESSAGE_CONTENT)
8799
.build();
88100

89101
jda.awaitReady();
90102

91-
BotCore core = new BotCore(jda, database, config);
103+
BotCore core = new BotCore(jda, database, config, secrets);
92104
CommandReloading.reloadCommands(jda, core);
93105
core.scheduleRoutines(jda);
94106

application/src/main/java/org/togetherjava/tjbot/config/Config.java

Lines changed: 2 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,6 @@
1616
* Configuration of the application. Create instances using {@link #load(Path)}.
1717
*/
1818
public final class Config {
19-
private final String token;
20-
private final String githubApiKey;
2119
private final String databasePath;
2220
private final String projectWebsite;
2321
private final String discordGuildInvite;
@@ -36,11 +34,8 @@ public final class Config {
3634
private final HelpSystemConfig helpSystem;
3735
private final List<String> blacklistedFileExtension;
3836
private final String mediaOnlyChannelPattern;
39-
private final String logInfoChannelWebhook;
40-
private final String logErrorChannelWebhook;
4137
private final String githubReferencingEnabledChannelPattern;
4238
private final List<Long> githubRepositories;
43-
private final String openaiApiKey;
4439
private final String sourceCodeBaseUrl;
4540
private final JShellConfig jshell;
4641
private final HelperPruneConfig helperPruneConfig;
@@ -52,9 +47,7 @@ public final class Config {
5247

5348
@SuppressWarnings("ConstructorWithTooManyParameters")
5449
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
55-
private Config(@JsonProperty(value = "token", required = true) String token,
56-
@JsonProperty(value = "githubApiKey", required = true) String githubApiKey,
57-
@JsonProperty(value = "databasePath", required = true) String databasePath,
50+
private Config(@JsonProperty(value = "databasePath", required = true) String databasePath,
5851
@JsonProperty(value = "projectWebsite", required = true) String projectWebsite,
5952
@JsonProperty(value = "discordGuildInvite", required = true) String discordGuildInvite,
6053
@JsonProperty(value = "modAuditLogChannelPattern",
@@ -82,15 +75,11 @@ private Config(@JsonProperty(value = "token", required = true) String token,
8275
required = true) String mediaOnlyChannelPattern,
8376
@JsonProperty(value = "blacklistedFileExtension",
8477
required = true) List<String> blacklistedFileExtension,
85-
@JsonProperty(value = "logInfoChannelWebhook",
86-
required = true) String logInfoChannelWebhook,
87-
@JsonProperty(value = "logErrorChannelWebhook",
88-
required = true) String logErrorChannelWebhook,
78+
8979
@JsonProperty(value = "githubReferencingEnabledChannelPattern",
9080
required = true) String githubReferencingEnabledChannelPattern,
9181
@JsonProperty(value = "githubRepositories",
9282
required = true) List<Long> githubRepositories,
93-
@JsonProperty(value = "openaiApiKey", required = true) String openaiApiKey,
9483
@JsonProperty(value = "sourceCodeBaseUrl", required = true) String sourceCodeBaseUrl,
9584
@JsonProperty(value = "jshell", required = true) JShellConfig jshell,
9685
@JsonProperty(value = "memberCountCategoryPattern",
@@ -103,8 +92,6 @@ private Config(@JsonProperty(value = "token", required = true) String token,
10392
@JsonProperty(value = "selectRolesChannelPattern",
10493
required = true) String selectRolesChannelPattern,
10594
@JsonProperty(value = "topHelpers", required = true) TopHelpersConfig topHelpers) {
106-
this.token = Objects.requireNonNull(token);
107-
this.githubApiKey = Objects.requireNonNull(githubApiKey);
10895
this.databasePath = Objects.requireNonNull(databasePath);
10996
this.projectWebsite = Objects.requireNonNull(projectWebsite);
11097
this.memberCountCategoryPattern = Objects.requireNonNull(memberCountCategoryPattern);
@@ -125,12 +112,9 @@ private Config(@JsonProperty(value = "token", required = true) String token,
125112
this.helpSystem = Objects.requireNonNull(helpSystem);
126113
this.mediaOnlyChannelPattern = Objects.requireNonNull(mediaOnlyChannelPattern);
127114
this.blacklistedFileExtension = Objects.requireNonNull(blacklistedFileExtension);
128-
this.logInfoChannelWebhook = Objects.requireNonNull(logInfoChannelWebhook);
129-
this.logErrorChannelWebhook = Objects.requireNonNull(logErrorChannelWebhook);
130115
this.githubReferencingEnabledChannelPattern =
131116
Objects.requireNonNull(githubReferencingEnabledChannelPattern);
132117
this.githubRepositories = Objects.requireNonNull(githubRepositories);
133-
this.openaiApiKey = Objects.requireNonNull(openaiApiKey);
134118
this.sourceCodeBaseUrl = Objects.requireNonNull(sourceCodeBaseUrl);
135119
this.jshell = Objects.requireNonNull(jshell);
136120
this.helperPruneConfig = Objects.requireNonNull(helperPruneConfig);
@@ -191,27 +175,6 @@ public String getProjectsChannelPattern() {
191175
return projectsChannelPattern;
192176
}
193177

194-
/**
195-
* Gets the token of the Discord bot to connect this application to.
196-
*
197-
* @return the Discord bot token
198-
*/
199-
public String getToken() {
200-
return token;
201-
}
202-
203-
/**
204-
* Gets the API Key of GitHub.
205-
*
206-
* @return the API Key
207-
* @see <a href=
208-
* "https://docs.github.com/en/enterprise-server@3.4/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token">Create
209-
* a GitHub key</a>
210-
*/
211-
public String getGitHubApiKey() {
212-
return githubApiKey;
213-
}
214-
215178
/**
216179
* Gets the path where the database of the application is located at.
217180
*
@@ -356,33 +319,6 @@ public List<Long> getGitHubRepositories() {
356319
return githubRepositories;
357320
}
358321

359-
/**
360-
* The Discord channel webhook for posting log messages with levels INFO, DEBUG and TRACE.
361-
*
362-
* @return the webhook URL
363-
*/
364-
public String getLogInfoChannelWebhook() {
365-
return logInfoChannelWebhook;
366-
}
367-
368-
/**
369-
* The Discord channel webhook for posting log messages with levels FATAL, ERROR and WARNING.
370-
*
371-
* @return the webhook URL
372-
*/
373-
public String getLogErrorChannelWebhook() {
374-
return logErrorChannelWebhook;
375-
}
376-
377-
/**
378-
* The OpenAI token needed for communicating with OpenAI ChatGPT.
379-
*
380-
* @return the OpenAI API Token
381-
*/
382-
public String getOpenaiApiKey() {
383-
return openaiApiKey;
384-
}
385-
386322
/**
387323
* The base URL of the source code of this bot. E.g.
388324
* {@code getSourceCodeBaseUrl() + "/org/togetherjava/tjbot/config/Config.java"} would point to

application/src/main/java/org/togetherjava/tjbot/config/JShellConfig.java

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,30 +3,25 @@
33

44
import org.togetherjava.tjbot.features.utils.RateLimiter;
55

6-
import java.util.Objects;
76

87
/**
98
* JShell config.
10-
*
11-
* @param baseUrl the base url of the JShell REST API
9+
*
1210
* @param rateLimitWindowSeconds the number of seconds of the {@link RateLimiter rate limiter} for
1311
* jshell commands and code actions
1412
* @param rateLimitRequestsInWindow the number of requests of the {@link RateLimiter rate limiter}
1513
* for jshell commands and code actions
1614
*/
17-
public record JShellConfig(String baseUrl, int rateLimitWindowSeconds,
18-
int rateLimitRequestsInWindow) {
15+
public record JShellConfig(int rateLimitWindowSeconds, int rateLimitRequestsInWindow) {
1916
/**
2017
* Creates a JShell config.
2118
*
22-
* @param baseUrl the base url of the JShell REST API, must be not null
2319
* @param rateLimitWindowSeconds the number of seconds of the {@link RateLimiter rate limiter}
2420
* for jshell commands and code actions, must be higher than 0
2521
* @param rateLimitRequestsInWindow the number of requests of the {@link RateLimiter rate
2622
* limiter} for jshell commands and code actions, must be higher than 0
2723
*/
2824
public JShellConfig {
29-
Objects.requireNonNull(baseUrl);
3025
if (rateLimitWindowSeconds < 0) {
3126
throw new IllegalArgumentException(
3227
"Illegal rateLimitWindowSeconds : " + rateLimitWindowSeconds);

application/src/main/java/org/togetherjava/tjbot/features/Features.java

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@
7878
import org.togetherjava.tjbot.features.tophelper.TopHelpersMessageListener;
7979
import org.togetherjava.tjbot.features.tophelper.TopHelpersPurgeMessagesRoutine;
8080
import org.togetherjava.tjbot.features.tophelper.TopHelpersService;
81+
import org.togetherjava.tjbot.secrets.Secrets;
8182

8283
import java.util.ArrayList;
8384
import java.util.Collection;
@@ -88,7 +89,7 @@
8889
* it with the system.
8990
* <p>
9091
* To add a new slash command, extend the commands returned by
91-
* {@link #createFeatures(JDA, Database, Config)}.
92+
* {@link #createFeatures(JDA, Database, Config, Secrets)}.
9293
*/
9394
public class Features {
9495
private Features() {
@@ -106,19 +107,21 @@ private Features() {
106107
* @param config the configuration features should use
107108
* @return a collection of all features
108109
*/
109-
public static Collection<Feature> createFeatures(JDA jda, Database database, Config config) {
110+
public static Collection<Feature> createFeatures(JDA jda, Database database, Config config,
111+
Secrets secrets) {
110112
FeatureBlacklistConfig blacklistConfig = config.getFeatureBlacklistConfig();
111-
JShellEval jshellEval = new JShellEval(config.getJshell(), config.getGitHubApiKey());
113+
JShellEval jshellEval = new JShellEval(config.getJshell(), secrets.getJshellBaseUrl(),
114+
secrets.getGitHubApiKey());
112115

113116
TagSystem tagSystem = new TagSystem(database);
114117
BookmarksSystem bookmarksSystem = new BookmarksSystem(config, database);
115118
ModerationActionsStore actionsStore = new ModerationActionsStore(database);
116119
ModAuditLogWriter modAuditLogWriter = new ModAuditLogWriter(config);
117120
ScamHistoryStore scamHistoryStore = new ScamHistoryStore(database);
118-
GitHubReference githubReference = new GitHubReference(config);
121+
GitHubReference githubReference = new GitHubReference(config, secrets);
119122
CodeMessageHandler codeMessageHandler =
120123
new CodeMessageHandler(blacklistConfig.special(), jshellEval);
121-
ChatGptService chatGptService = new ChatGptService(config);
124+
ChatGptService chatGptService = new ChatGptService(secrets);
122125
HelpSystemHelper helpSystemHelper = new HelpSystemHelper(config, database, chatGptService);
123126
HelpThreadLifecycleListener helpThreadLifecycleListener =
124127
new HelpThreadLifecycleListener(helpSystemHelper, database);
@@ -153,7 +156,7 @@ public static Collection<Feature> createFeatures(JDA jda, Database database, Con
153156
features.add(new SuggestionsUpDownVoter(config));
154157
features.add(new ScamBlocker(actionsStore, scamHistoryStore, config));
155158
features.add(new MediaOnlyChannelListener(config));
156-
features.add(new FileSharingMessageListener(config));
159+
features.add(new FileSharingMessageListener(config, secrets));
157160
features.add(new BlacklistedAttachmentListener(config, modAuditLogWriter));
158161
features.add(githubReference);
159162
features.add(codeMessageHandler);

application/src/main/java/org/togetherjava/tjbot/features/chatgpt/ChatGptService.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import org.slf4j.Logger;
99
import org.slf4j.LoggerFactory;
1010

11-
import org.togetherjava.tjbot.config.Config;
11+
import org.togetherjava.tjbot.secrets.Secrets;
1212

1313
import javax.annotation.Nullable;
1414

@@ -54,10 +54,10 @@ public class ChatGptService {
5454
/**
5555
* Creates instance of ChatGPTService
5656
*
57-
* @param config needed for token to OpenAI API.
57+
* @param secrets needed for token to OpenAI API.
5858
*/
59-
public ChatGptService(Config config) {
60-
String apiKey = config.getOpenaiApiKey();
59+
public ChatGptService(Secrets secrets) {
60+
String apiKey = secrets.getOpenaiApiKey();
6161
boolean keyIsDefaultDescription = apiKey.startsWith("<") && apiKey.endsWith(">");
6262
if (apiKey.isBlank() || keyIsDefaultDescription) {
6363
isDisabled = true;

application/src/main/java/org/togetherjava/tjbot/features/filesharing/FileSharingMessageListener.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import org.togetherjava.tjbot.features.componentids.ComponentIdGenerator;
2222
import org.togetherjava.tjbot.features.componentids.ComponentIdInteractor;
2323
import org.togetherjava.tjbot.features.utils.Guilds;
24+
import org.togetherjava.tjbot.secrets.Secrets;
2425

2526
import java.io.IOException;
2627
import java.io.InputStream;
@@ -58,9 +59,9 @@ public final class FileSharingMessageListener extends MessageReceiverAdapter
5859
* @param config used to get api key and channel names.
5960
* @see org.togetherjava.tjbot.features.Features
6061
*/
61-
public FileSharingMessageListener(Config config) {
62+
public FileSharingMessageListener(Config config, Secrets secrets) {
6263
super(Pattern.compile(".*"));
63-
githubApiKey = config.getGitHubApiKey();
64+
githubApiKey = secrets.getGitHubApiKey();
6465
isHelpForumName =
6566
Pattern.compile(config.getHelpSystem().getHelpForumPattern()).asMatchPredicate();
6667
isSoftModRole = Pattern.compile(config.getSoftModerationRolePattern()).asMatchPredicate();

application/src/main/java/org/togetherjava/tjbot/features/github/GitHubReference.java

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
import org.togetherjava.tjbot.config.Config;
2323
import org.togetherjava.tjbot.features.MessageReceiverAdapter;
24+
import org.togetherjava.tjbot.secrets.Secrets;
2425

2526
import java.awt.Color;
2627
import java.io.FileNotFoundException;
@@ -67,6 +68,7 @@ public final class GitHubReference extends MessageReceiverAdapter {
6768
DateTimeFormatter.ofPattern("dd MMM, yyyy").withZone(ZoneOffset.UTC);
6869
private final Predicate<String> hasGithubIssueReferenceEnabled;
6970
private final Config config;
71+
private final Secrets secrets;
7072

7173
/**
7274
* The repositories that are searched when looking for an issue.
@@ -81,8 +83,9 @@ public final class GitHubReference extends MessageReceiverAdapter {
8183
*
8284
* @param config The Config to get allowed channel pattern for feature.
8385
*/
84-
public GitHubReference(Config config) {
86+
public GitHubReference(Config config, Secrets secrets) {
8587
this.config = config;
88+
this.secrets = secrets;
8689
this.hasGithubIssueReferenceEnabled =
8790
Pattern.compile(config.getGitHubReferencingEnabledChannelPattern())
8891
.asMatchPredicate();
@@ -96,15 +99,15 @@ private void acquireRepositories() {
9699
try {
97100
repositories = new ArrayList<>();
98101

99-
GitHub githubApi = GitHub.connectUsingOAuth(config.getGitHubApiKey());
102+
GitHub githubApi = GitHub.connectUsingOAuth(secrets.getGitHubApiKey());
100103

101104
for (long repoId : config.getGitHubRepositories()) {
102105
repositories.add(githubApi.getRepositoryById(repoId));
103106
}
104107
} catch (IOException ex) {
105108
logger.warn(
106109
"The GitHub key ({}) used in this config is invalid. Skipping GitHubReference feature – {}",
107-
config.getGitHubApiKey(), ex.getMessage());
110+
secrets.getGitHubApiKey(), ex.getMessage());
108111
}
109112
}
110113

application/src/main/java/org/togetherjava/tjbot/features/jshell/JShellEval.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,10 @@ public class JShellEval {
3838
* @param config the JShell configuration to use
3939
* @param gistApiToken token of Gist api in case a JShell result is uploaded here
4040
*/
41-
public JShellEval(JShellConfig config, String gistApiToken) {
41+
public JShellEval(JShellConfig config, String baseUrl, String gistApiToken) {
4242
this.gistApiToken = gistApiToken;
4343
this.api = new JShellApi(new ObjectMapper().registerModule(new Jdk17SealedClassesModule()),
44-
config.baseUrl());
44+
baseUrl);
4545
this.renderer = new ResultRenderer();
4646

4747
this.rateLimiter = new RateLimiter(Duration.ofSeconds(config.rateLimitWindowSeconds()),

0 commit comments

Comments
 (0)