Refactor datasource classes
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Bea 2022-11-22 00:28:33 +01:00
parent f9e1578899
commit 8faa9c4677
7 changed files with 60 additions and 59 deletions

View File

@ -2,9 +2,9 @@ package wtf.beatrice.hidekobot;
import net.dv8tion.jda.api.interactions.commands.Command; import net.dv8tion.jda.api.interactions.commands.Command;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import wtf.beatrice.hidekobot.database.DatabaseManager; import wtf.beatrice.hidekobot.datasource.DatabaseSource;
import wtf.beatrice.hidekobot.listeners.MessageLogger; import wtf.beatrice.hidekobot.listeners.MessageLogger;
import wtf.beatrice.hidekobot.utils.ConfigurationManager; import wtf.beatrice.hidekobot.datasource.ConfigurationSource;
import wtf.beatrice.hidekobot.utils.Logger; import wtf.beatrice.hidekobot.utils.Logger;
import java.awt.*; import java.awt.*;
@ -19,8 +19,8 @@ public class Cache
private static final Logger logger = new Logger(Cache.class); private static final Logger logger = new Logger(Cache.class);
private static ConfigurationManager configManager = null; private static ConfigurationSource configurationSource = null;
private static DatabaseManager dbManager = null; private static DatabaseSource databaseSource = null;
private static boolean verbose = false; private static boolean verbose = false;
private static MessageLogger verbosityLogger; private static MessageLogger verbosityLogger;
private static final long botMaintainerId = 979809420714332260L; private static final long botMaintainerId = 979809420714332260L;
@ -94,7 +94,7 @@ public class Cache
* @return a long of the account's id * @return a long of the account's id
*/ */
public static long getBotOwnerId() { public static long getBotOwnerId() {
return configManager == null ? 0L : (Long) configManager.getConfigValue("bot-owner-id"); return configurationSource == null ? 0L : (Long) configurationSource.getConfigValue("bot-owner-id");
} }
@ -104,7 +104,7 @@ public class Cache
* @return a String of the bot's token. * @return a String of the bot's token.
*/ */
public static String getBotToken() { public static String getBotToken() {
return configManager == null ? null : (String) configManager.getConfigValue("bot-token"); return configurationSource == null ? null : (String) configurationSource.getConfigValue("bot-token");
} }
/** /**
@ -142,21 +142,21 @@ public class Cache
} }
/** /**
* Set the already fully-initialized DatabaseManager instance, ready to be accessed and used. * Set the already fully-initialized DatabaseSource instance, ready to be accessed and used.
* *
* @param databaseManagerInstance the fully-initialized DatabaseManager instance. * @param databaseSourceInstance the fully-initialized DatabaseSource instance.
*/ */
public static void setDatabaseManagerInstance(DatabaseManager databaseManagerInstance) public static void setDatabaseSourceInstance(DatabaseSource databaseSourceInstance)
{ {
dbManager = databaseManagerInstance; databaseSource = databaseSourceInstance;
} }
/** /**
* Get the fully-initialized DatabaseManager instance, ready to be used. * Get the fully-initialized DatabaseSource instance, ready to be used.
* *
* @return the DatabaseManager instance. * @return the DatabaseSource instance.
*/ */
public static @Nullable DatabaseManager getDatabaseManager() { return dbManager; } public static @Nullable DatabaseSource getDatabaseSource() { return databaseSource; }
/** /**
* Get the DateTimeFormatter string for parsing the expired messages timestamp. * Get the DateTimeFormatter string for parsing the expired messages timestamp.
@ -189,8 +189,8 @@ public class Cache
*/ */
public static Color getBotColor() { public static Color getBotColor() {
Color defaultColor = Color.PINK; Color defaultColor = Color.PINK;
if(configManager == null) return defaultColor; if(configurationSource == null) return defaultColor;
String colorName = (String) configManager.getConfigValue("bot-color"); String colorName = (String) configurationSource.getConfigValue("bot-color");
Color color = null; Color color = null;
try { try {
@ -246,15 +246,15 @@ public class Cache
public static LocalDateTime getStartupTime() { return startupTime; } public static LocalDateTime getStartupTime() { return startupTime; }
public static String getFullHeartBeatLink() { public static String getFullHeartBeatLink() {
return configManager == null ? null : (String) configManager.getConfigValue("heartbeat-link"); return configurationSource == null ? null : (String) configurationSource.getConfigValue("heartbeat-link");
} }
//todo javadocs //todo javadocs
public static String getExecPath() { return execPath; } public static String getExecPath() { return execPath; }
private static ConfigurationManager getConfigurationManager() /*private static ConfigurationSource getConfigurationSource()
{ return configManager; } { return configurationSource; }*/
public static void setConfigManager(ConfigurationManager configurationManager) public static void setConfigurationSource(ConfigurationSource configurationSource)
{ configManager = configurationManager; } { Cache.configurationSource = configurationSource; }
} }

View File

@ -6,7 +6,7 @@ import net.dv8tion.jda.api.OnlineStatus;
import net.dv8tion.jda.api.entities.Activity; import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.requests.GatewayIntent; import net.dv8tion.jda.api.requests.GatewayIntent;
import sun.misc.Signal; import sun.misc.Signal;
import wtf.beatrice.hidekobot.database.DatabaseManager; import wtf.beatrice.hidekobot.datasource.DatabaseSource;
import wtf.beatrice.hidekobot.listeners.ButtonInteractionListener; import wtf.beatrice.hidekobot.listeners.ButtonInteractionListener;
import wtf.beatrice.hidekobot.listeners.MessageListener; import wtf.beatrice.hidekobot.listeners.MessageListener;
import wtf.beatrice.hidekobot.listeners.SlashCommandCompleter; import wtf.beatrice.hidekobot.listeners.SlashCommandCompleter;
@ -14,7 +14,7 @@ import wtf.beatrice.hidekobot.listeners.SlashCommandListener;
import wtf.beatrice.hidekobot.runnables.CommandsUpdateTask; import wtf.beatrice.hidekobot.runnables.CommandsUpdateTask;
import wtf.beatrice.hidekobot.runnables.ExpiredMessageTask; import wtf.beatrice.hidekobot.runnables.ExpiredMessageTask;
import wtf.beatrice.hidekobot.runnables.HeartBeatTask; import wtf.beatrice.hidekobot.runnables.HeartBeatTask;
import wtf.beatrice.hidekobot.utils.ConfigurationManager; import wtf.beatrice.hidekobot.datasource.ConfigurationSource;
import wtf.beatrice.hidekobot.utils.Logger; import wtf.beatrice.hidekobot.utils.Logger;
import wtf.beatrice.hidekobot.utils.SlashCommandUtil; import wtf.beatrice.hidekobot.utils.SlashCommandUtil;
@ -39,9 +39,9 @@ public class HidekoBot
// load configuration // load configuration
logger.log("Loading configuration..."); logger.log("Loading configuration...");
String configFilePath = Cache.getExecPath() + File.separator + "config.yml"; String configFilePath = Cache.getExecPath() + File.separator + "config.yml";
ConfigurationManager configurationManager = new ConfigurationManager(configFilePath); ConfigurationSource configurationSource = new ConfigurationSource(configFilePath);
configurationManager.initConfig(); configurationSource.initConfig();
Cache.setConfigManager(configurationManager); Cache.setConfigurationSource(configurationSource);
logger.log("Configuration loaded!"); logger.log("Configuration loaded!");
String botToken = Cache.getBotToken(); String botToken = Cache.getBotToken();
@ -115,11 +115,11 @@ public class HidekoBot
// connect to database // connect to database
logger.log("Connecting to database..."); logger.log("Connecting to database...");
String dbFilePath = Cache.getExecPath() + File.separator + "db.sqlite"; // in current directory String dbFilePath = Cache.getExecPath() + File.separator + "db.sqlite"; // in current directory
DatabaseManager dbManager = new DatabaseManager(dbFilePath); DatabaseSource databaseSource = new DatabaseSource(dbFilePath);
if(dbManager.connect() && dbManager.initDb()) if(databaseSource.connect() && databaseSource.initDb())
{ {
logger.log("Database connection initialized!"); logger.log("Database connection initialized!");
Cache.setDatabaseManagerInstance(dbManager); Cache.setDatabaseSourceInstance(databaseSource);
// load data here... // load data here...

View File

@ -165,8 +165,8 @@ public class ClearChatCommand
.setActionRow(dismissButton) .setActionRow(dismissButton)
.complete(); .complete();
Cache.getDatabaseManager().queueDisabling(message); Cache.getDatabaseSource().queueDisabling(message);
Cache.getDatabaseManager().trackRanCommandReply(message, event.getUser()); Cache.getDatabaseSource().trackRanCommandReply(message, event.getUser());
} }
}).start(); }).start();
@ -176,7 +176,7 @@ public class ClearChatCommand
public void dismissMessage(ButtonInteractionEvent event) public void dismissMessage(ButtonInteractionEvent event)
{ {
if(!(Cache.getDatabaseManager().isUserTrackedFor(event.getUser().getId(), event.getMessageId()))) if(!(Cache.getDatabaseSource().isUserTrackedFor(event.getUser().getId(), event.getMessageId())))
{ {
event.reply("❌ You did not run this command!").setEphemeral(true).queue(); event.reply("❌ You did not run this command!").setEphemeral(true).queue();
} else } else

View File

@ -38,7 +38,7 @@ public class CoinFlipCommand
public void buttonReFlip(ButtonInteractionEvent event) public void buttonReFlip(ButtonInteractionEvent event)
{ {
// check if the user interacting is the same one who ran the command // check if the user interacting is the same one who ran the command
if(!(Cache.getDatabaseManager().isUserTrackedFor(event.getUser().getId(), event.getMessageId()))) if(!(Cache.getDatabaseSource().isUserTrackedFor(event.getUser().getId(), event.getMessageId())))
{ {
event.reply("❌ You did not run this command!").setEphemeral(true).queue(); event.reply("❌ You did not run this command!").setEphemeral(true).queue();
return; return;
@ -63,8 +63,8 @@ public class CoinFlipCommand
{ {
String replyMessageId = replyMessage.getId(); String replyMessageId = replyMessage.getId();
Cache.getDatabaseManager().queueDisabling(replyMessage); Cache.getDatabaseSource().queueDisabling(replyMessage);
Cache.getDatabaseManager().trackRanCommandReply(replyMessage, user); Cache.getDatabaseSource().trackRanCommandReply(replyMessage, user);
} }
private String genRandom() private String genRandom()

View File

@ -1,13 +1,14 @@
package wtf.beatrice.hidekobot.utils; package wtf.beatrice.hidekobot.datasource;
import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.Yaml;
import wtf.beatrice.hidekobot.HidekoBot; import wtf.beatrice.hidekobot.HidekoBot;
import wtf.beatrice.hidekobot.utils.Logger;
import java.io.*; import java.io.*;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
public class ConfigurationManager public class ConfigurationSource
{ {
@ -15,7 +16,7 @@ public class ConfigurationManager
private final Logger logger; private final Logger logger;
private final String configFilePath; private final String configFilePath;
public ConfigurationManager(String configFilePath) public ConfigurationSource(String configFilePath)
{ {
this.configFilePath = configFilePath; this.configFilePath = configFilePath;
logger = new Logger(getClass()); logger = new Logger(getClass());

View File

@ -1,4 +1,4 @@
package wtf.beatrice.hidekobot.database; package wtf.beatrice.hidekobot.datasource;
import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.entities.User;
@ -12,7 +12,7 @@ import java.time.format.DateTimeFormatter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
public class DatabaseManager public class DatabaseSource
{ {
private final static String sqliteURL = "jdbc:sqlite:%path%"; private final static String sqliteURL = "jdbc:sqlite:%path%";
@ -20,7 +20,7 @@ public class DatabaseManager
private final String dbPath; private final String dbPath;
private final Logger logger; private final Logger logger;
public DatabaseManager(String dbPath) public DatabaseSource(String dbPath)
{ {
this.dbPath = dbPath; this.dbPath = dbPath;
this.logger = new Logger(getClass()); this.logger = new Logger(getClass());

View File

@ -9,7 +9,7 @@ import net.dv8tion.jda.api.interactions.components.LayoutComponent;
import net.dv8tion.jda.api.requests.RestAction; import net.dv8tion.jda.api.requests.RestAction;
import wtf.beatrice.hidekobot.Cache; import wtf.beatrice.hidekobot.Cache;
import wtf.beatrice.hidekobot.HidekoBot; import wtf.beatrice.hidekobot.HidekoBot;
import wtf.beatrice.hidekobot.database.DatabaseManager; import wtf.beatrice.hidekobot.datasource.DatabaseSource;
import wtf.beatrice.hidekobot.utils.Logger; import wtf.beatrice.hidekobot.utils.Logger;
import java.time.LocalDateTime; import java.time.LocalDateTime;
@ -21,14 +21,14 @@ public class ExpiredMessageTask implements Runnable {
private final DateTimeFormatter formatter; private final DateTimeFormatter formatter;
private final Logger logger; private final Logger logger;
private DatabaseManager databaseManager; private DatabaseSource databaseSource;
public ExpiredMessageTask() public ExpiredMessageTask()
{ {
String format = Cache.getExpiryTimestampFormat(); String format = Cache.getExpiryTimestampFormat();
formatter = DateTimeFormatter.ofPattern(format); formatter = DateTimeFormatter.ofPattern(format);
databaseManager = Cache.getDatabaseManager(); databaseSource = Cache.getDatabaseSource();
logger = new Logger(getClass()); logger = new Logger(getClass());
} }
@ -36,10 +36,10 @@ public class ExpiredMessageTask implements Runnable {
@Override @Override
public void run() { public void run() {
databaseManager = Cache.getDatabaseManager(); databaseSource = Cache.getDatabaseSource();
if(databaseManager == null) return; if(databaseSource == null) return;
List<String> expiringMessages = Cache.getDatabaseManager().getQueuedExpiringMessages(); List<String> expiringMessages = Cache.getDatabaseSource().getQueuedExpiringMessages();
if(expiringMessages == null || expiringMessages.isEmpty()) return; if(expiringMessages == null || expiringMessages.isEmpty()) return;
LocalDateTime now = LocalDateTime.now(); LocalDateTime now = LocalDateTime.now();
@ -49,11 +49,11 @@ public class ExpiredMessageTask implements Runnable {
if(Cache.isVerbose()) logger.log("expired check: " + messageId); if(Cache.isVerbose()) logger.log("expired check: " + messageId);
String expiryTimestamp = databaseManager.getQueuedExpiringMessageExpiryDate(messageId); String expiryTimestamp = databaseSource.getQueuedExpiringMessageExpiryDate(messageId);
if(expiryTimestamp == null || expiryTimestamp.equals("")) // if missing timestamp if(expiryTimestamp == null || expiryTimestamp.equals("")) // if missing timestamp
{ {
// count it as already expired // count it as already expired
databaseManager.untrackExpiredMessage(messageId); databaseSource.untrackExpiredMessage(messageId);
// move on to next message // move on to next message
continue; continue;
} }
@ -73,9 +73,9 @@ public class ExpiredMessageTask implements Runnable {
private void disableExpired(String messageId) private void disableExpired(String messageId)
{ {
String channelId = databaseManager.getQueuedExpiringMessageChannel(messageId); String channelId = databaseSource.getQueuedExpiringMessageChannel(messageId);
ChannelType msgChannelType = databaseManager.getTrackedMessageChannelType(messageId); ChannelType msgChannelType = databaseSource.getTrackedMessageChannelType(messageId);
MessageChannel textChannel = null; MessageChannel textChannel = null;
@ -83,20 +83,20 @@ public class ExpiredMessageTask implements Runnable {
// this should never happen, but only message channels are supported. // this should never happen, but only message channels are supported.
if(!msgChannelType.isMessage()) if(!msgChannelType.isMessage())
{ {
databaseManager.untrackExpiredMessage(messageId); databaseSource.untrackExpiredMessage(messageId);
return; return;
} }
// if this is a DM // if this is a DM
if(msgChannelType == ChannelType.PRIVATE) if(msgChannelType == ChannelType.PRIVATE)
{ {
String userId = databaseManager.getTrackedReplyUserId(messageId); String userId = databaseSource.getTrackedReplyUserId(messageId);
User user = HidekoBot.getAPI().retrieveUserById(userId).complete(); User user = HidekoBot.getAPI().retrieveUserById(userId).complete();
if(user == null) if(user == null)
{ {
// if user is not found, consider it expired // if user is not found, consider it expired
// (deleted profile, or blocked the bot) // (deleted profile, or blocked the bot)
databaseManager.untrackExpiredMessage(messageId); databaseSource.untrackExpiredMessage(messageId);
return; return;
} }
@ -104,13 +104,13 @@ public class ExpiredMessageTask implements Runnable {
} }
else else
{ {
String guildId = databaseManager.getQueuedExpiringMessageGuild(messageId); String guildId = databaseSource.getQueuedExpiringMessageGuild(messageId);
Guild guild = HidekoBot.getAPI().getGuildById(guildId); Guild guild = HidekoBot.getAPI().getGuildById(guildId);
if(guild == null) if(guild == null)
{ {
// if guild is not found, consider it expired // if guild is not found, consider it expired
// (server was deleted or bot was kicked) // (server was deleted or bot was kicked)
databaseManager.untrackExpiredMessage(messageId); databaseSource.untrackExpiredMessage(messageId);
return; return;
} }
textChannel = guild.getTextChannelById(channelId); textChannel = guild.getTextChannelById(channelId);
@ -120,7 +120,7 @@ public class ExpiredMessageTask implements Runnable {
{ {
// if channel is not found, count it as expired // if channel is not found, count it as expired
// (channel was deleted or bot permissions restricted) // (channel was deleted or bot permissions restricted)
databaseManager.untrackExpiredMessage(messageId); databaseSource.untrackExpiredMessage(messageId);
return; return;
} }
@ -134,7 +134,7 @@ public class ExpiredMessageTask implements Runnable {
message -> { message -> {
if(message == null) if(message == null)
{ {
databaseManager.untrackExpiredMessage(messageId); databaseSource.untrackExpiredMessage(messageId);
return; return;
} }
@ -147,11 +147,11 @@ public class ExpiredMessageTask implements Runnable {
} }
message.editMessageComponents(newComponents).queue(); message.editMessageComponents(newComponents).queue();
databaseManager.untrackExpiredMessage(messageId); databaseSource.untrackExpiredMessage(messageId);
}, },
(error) -> { (error) -> {
databaseManager.untrackExpiredMessage(messageId); databaseSource.untrackExpiredMessage(messageId);
}); });
} }
} }