Switch to JPA for database

This commit is contained in:
anthorob committed 2022-03-13 15:06:22 -04:00
1 parent 873c7c8d26
commit e3f47bbfe5
90 files changed
+1520 -1847

No files matched your search

+1
View File
@@ -9,6 +9,7 @@
# Config file # Config file
bot.config bot.config
bot.properties
# Mobile Tools for Java (J2ME) # Mobile Tools for Java (J2ME)
.mtj.tmp/ .mtj.tmp/
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JpaPluginProjectSettings">
<option name="lastSelectedLanguage" value="Java" />
</component>
</project>
+1 -1
View File
@@ -5,7 +5,7 @@ WORKDIR /app
COPY .mvn/ .mvn COPY .mvn/ .mvn
COPY mvnw pom.xml ./ COPY mvnw pom.xml ./
COPY src ./src COPY src ./src
COPY bot.config.example bot.config ./ COPY bot.properties.example bot.properties ./
RUN ./mvnw -q -Dmaven.test.skip=true package RUN ./mvnw -q -Dmaven.test.skip=true package
@@ -1,3 +1,4 @@
BOT_ENV=dev
BOT_TOKEN= BOT_TOKEN=
BOT_PREFIX= BOT_PREFIX=
BOT_OWNER= BOT_OWNER=
@@ -9,3 +10,5 @@ MYSQL_USER=
MYSQL_PASSWORD= MYSQL_PASSWORD=
MYSQL_DATABASE= MYSQL_DATABASE=
MYSQL_PORT=3306 MYSQL_PORT=3306
SENTRY_DSN=
+26 -10
View File
@@ -41,7 +41,7 @@
<manifest> <manifest>
<addClasspath>true</addClasspath> <addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix> <classpathPrefix>lib/</classpathPrefix>
<mainClass>netneutrality.MusicBot</mainClass> <mainClass>netneutrality.NetNeutrality</mainClass>
</manifest> </manifest>
</archive> </archive>
</configuration> </configuration>
@@ -53,7 +53,7 @@
<configuration> <configuration>
<archive> <archive>
<manifest> <manifest>
<mainClass>netneutrality.MusicBot</mainClass> <mainClass>netneutrality.NetNeutrality</mainClass>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries> <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries> <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest> </manifest>
@@ -121,6 +121,27 @@
<version>4.9.3</version> <version>4.9.3</version>
</dependency> </dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-hikaricp</artifactId>
<version>5.6.5.Final</version>
</dependency>
<dependency>
<groupId>io.sentry</groupId>
<artifactId>sentry</artifactId>
<version>5.6.3</version>
</dependency>
<dependency>
<groupId>p6spy</groupId>
<artifactId>p6spy</artifactId>
<version>3.9.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.json/json --> <!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency> <dependency>
<groupId>org.json</groupId> <groupId>org.json</groupId>
@@ -137,22 +158,17 @@
<dependency> <dependency>
<groupId>mysql</groupId> <groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId> <artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version> <version>8.0.28</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.17.0</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.logging.log4j</groupId> <groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId> <artifactId>log4j-core</artifactId>
<version>2.17.0</version> <version>2.17.1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.logging.log4j</groupId> <groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId> <artifactId>log4j-slf4j-impl</artifactId>
<version>2.17.0</version> <version>2.17.1</version>
</dependency> </dependency>
<dependency> <dependency>
@@ -1,2 +1 @@
ALTER TABLE `guild_settings` ADD `music_volume` INT NOT NULL DEFAULT '30' AFTER `music_channel`; ALTER TABLE `guild_settings` ADD `music_volume` INT NOT NULL DEFAULT '30' AFTER `music_channel`;
@@ -1,162 +0,0 @@
package netneutrality;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.TextChannel;
import netneutrality.db.DBController;
import netneutrality.db.controllers.DBGuild;
import netneutrality.db.controllers.DBMessage;
import netneutrality.db.entities.OGuild;
import netneutrality.handler.ratelimiter.IMessageRateLimiter;
import netneutrality.handler.ratelimiter.MessageRateLimiterImpl;
import netneutrality.utils.MessageFunction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class GuildManager {
public enum GuildSetting {
MUSIC_ROLE("MUSIC_ROLE", ""),
MUSIC_CHANNEL("MUSIC_CHANNEL", ""),
MUSIC_VOLUME("MUSIC_VOLUME", 30),
BLACKLIST_CHANNELS("BLACKLIST_EXCLUDE_CHANNELS", "");
private final String name;
private final Object defaultValue;
GuildSetting(String name, Object defaultValue) {
this.name = name;
this.defaultValue = defaultValue;
}
public String getName() {
return name;
}
public Object getDefaultValue() {
return defaultValue;
}
}
public static final Logger logger = LoggerFactory.getLogger(GuildManager.class);
private static final Map<String, GuildManager> managers = new ConcurrentHashMap<>();
private final Guild guild;
private OGuild guildEntity;
private final IMessageRateLimiter rateLimiter;
private GuildManager(Guild guild) {
this.guild = guild;
handleJoinEvent();
this.guildEntity = new OGuild(guild.getId());
this.rateLimiter = new MessageRateLimiterImpl();
managers.put(guild.getId(), this);
}
public static GuildManager getManager(Guild guild) {
if (managers.containsKey(guild.getId())) {
return managers.get(guild.getId());
} else {
return new GuildManager(guild);
}
}
// Getter
public static Map<String, GuildManager> getManagers() {
return managers;
}
public static GuildManager getManager(String guildId) {
return managers.getOrDefault(guildId, null);
}
public Object getSetting(GuildSetting key) {
return guildEntity.getSettings().getSettingByKey(key);
}
public boolean isLoggingEnabled() {
return guildEntity.isLogging();
}
public boolean isDebugEnabled() {
return guildEntity.isDebug();
}
public Map<String, Object> getSettings() {
return guildEntity.getSettings().getSettings();
}
public IMessageRateLimiter getRateLimiter() {
return rateLimiter;
}
public Guild getGuild() {
return guild;
}
public static boolean reloadSettingsForGuild(String guildId) {
if (managers.containsKey(guildId)) {
GuildManager manager = managers.get(guildId);
manager.reloadSettings();
return true;
}
return false;
}
public static boolean reloadSettingsForGuild(Guild guild) {
GuildManager manager = GuildManager.getManager(guild.getId());
manager.reloadSettings();
return true;
}
public void checkAndLogMessage(Message message, Member member, TextChannel channel) {
if (guildEntity.isLogging()) {
((DBMessage) DBController.get("message")).log(guild, channel, member, message);
}
}
public void checkBlacklist(Message message, Member member, TextChannel channel) {
//TODO: per-guild
MessageFunction.checkBlacklist(guild, message, channel);
}
public boolean existInDb() {
return DBController.get().exists("guilds", "guild_id", guild.getId());
}
public void reloadSettings() {
logger.debug("Reloading guild entity: " + guild.getId());
this.guildEntity = new OGuild(guild.getId());
}
public void handleJoinEvent() {
if (!existInDb()) {
((DBGuild) DBController.get("guild")).insertGuildInDB(guild);
guild.getTextChannels()
.stream()
.filter(textChannel -> textChannel.getName().equals("debug") || textChannel.getName().equals("log"))
.forEach(textChannel -> textChannel.sendMessage("Error logging enabled on channel " + textChannel.getAsMention()).queue());
}
}
public void removeFromDB() {
((DBGuild) DBController.get("guild")).removeGuildInDB(guild);
}
}
@@ -1,33 +1,45 @@
package netneutrality; package netneutrality;
import io.sentry.Sentry;
import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder; import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.Activity; import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.requests.GatewayIntent; import net.dv8tion.jda.api.requests.GatewayIntent;
import netneutrality.command.CommandManager; import netneutrality.command.CommandManager;
import netneutrality.core.LogHandler;
import netneutrality.db.DBController; import netneutrality.db.DBController;
import netneutrality.handler.hooks.guilds.ServerJoinHandler;
import netneutrality.handler.hooks.message.EditHandler; import netneutrality.handler.hooks.message.EditHandler;
import netneutrality.handler.hooks.message.MessageReceivedHandler; import netneutrality.handler.hooks.message.MessageReceivedHandler;
import netneutrality.handler.hooks.guilds.ServerJoinHandler;
import netneutrality.http.server.WebApi; import netneutrality.http.server.WebApi;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
import netneutrality.thread.BaseThreadFactory; import netneutrality.thread.BaseThreadFactory;
import netneutrality.thread.ShutdownThread; import netneutrality.thread.ShutdownThread;
import netneutrality.thread.ThreadManager;
import netneutrality.utils.Settings; import netneutrality.utils.Settings;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.security.auth.login.LoginException; import javax.security.auth.login.LoginException;
public class MusicBot { public class NetNeutrality {
private static JDA jda; private static JDA jda;
public final static Logger logger = LoggerFactory.getLogger(MusicBot.class); public final static Logger logger = LoggerFactory.getLogger(NetNeutrality.class);
public static void main(String[] args) { public static void main(String[] args) {
String sentryDsn = Settings.getInstance().get("SENTRY_DSN");
Sentry.init(options -> {
options.setDsn(sentryDsn);
options.setEnvironment(Settings.getInstance().get("BOT_ENV", "dev"));
// Set tracesSampleRate to 1.0 to capture 100% of transactions for performance monitoring.
// We recommend adjusting this value in production.
options.setTracesSampleRate(1.0);
// When first trying Sentry it's good to see what the SDK is doing:
options.setDebug(true);
});
DBController.init(); DBController.init();
@@ -35,7 +47,6 @@ public class MusicBot {
CommandManager.init(); CommandManager.init();
MusicManager.initPlayerManager(); MusicManager.initPlayerManager();
jda.getPresence().setActivity(Activity.watching("me load..."));
jda.addEventListener(new MessageReceivedHandler(), new EditHandler(), new ServerJoinHandler()); jda.addEventListener(new MessageReceivedHandler(), new EditHandler(), new ServerJoinHandler());
new WebApi(9000); new WebApi(9000);
@@ -47,11 +58,17 @@ public class MusicBot {
public static void initJDA() { public static void initJDA() {
try { try {
jda = JDABuilder.createDefault(Settings.getInstance().get("BOT_TOKEN")).enableIntents(GatewayIntent.GUILD_MEMBERS, GatewayIntent.GUILD_MESSAGE_REACTIONS, GatewayIntent.GUILD_VOICE_STATES).build(); jda = JDABuilder
.createDefault(Settings.getInstance().get("BOT_TOKEN"))
.enableIntents(GatewayIntent.GUILD_MEMBERS, GatewayIntent.GUILD_MESSAGE_REACTIONS, GatewayIntent.GUILD_VOICE_STATES)
.setActivity(Activity.watching("me load..."))
.build();
jda.awaitReady(); jda.awaitReady();
} catch (LoginException | IllegalArgumentException | InterruptedException e) { } catch (LoginException | IllegalArgumentException | InterruptedException e) {
logger.error(e.getMessage()); Sentry.captureException(e);
System.exit(0);
LogHandler.log(e);
System.exit(1);
} }
} }
@@ -9,7 +9,7 @@ package netneutrality.command;
import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.entities.Role;
import netneutrality.GuildManager; import netneutrality.core.GuildManager;
import netneutrality.utils.UserFunction; import netneutrality.utils.UserFunction;
public abstract class AbstractMusicCommand extends AbstractCommand { public abstract class AbstractMusicCommand extends AbstractCommand {
@@ -26,7 +26,7 @@ public abstract class AbstractMusicCommand extends AbstractCommand {
@Override @Override
public boolean canBeExecutedBy(Guild guild, Member member) { public boolean canBeExecutedBy(Guild guild, Member member) {
String roleDb = (String) GuildManager.getManager(guild).getSetting(GuildManager.GuildSetting.MUSIC_ROLE); String roleDb = GuildManager.getManager(guild).getSetting(GuildManager.Settings.MUSIC_ROLE);
boolean can = true; boolean can = true;
//System.out.println(roleDb); //System.out.println(roleDb);
@@ -8,6 +8,7 @@ package netneutrality.command;
import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Member;
import netneutrality.core.context.CommandContext;
import netneutrality.exceptions.CommandErrorException; import netneutrality.exceptions.CommandErrorException;
import netneutrality.exceptions.CommandExecutionException; import netneutrality.exceptions.CommandExecutionException;
@@ -8,7 +8,11 @@ package netneutrality.command.basic;
import net.dv8tion.jda.api.MessageBuilder; import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.MessageEmbed;
import netneutrality.command.*; import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandManager;
import netneutrality.command.CommandType;
import netneutrality.command.CommandUsage;
import netneutrality.core.context.CommandContext;
import netneutrality.utils.MessageFunction; import netneutrality.utils.MessageFunction;
import netneutrality.utils.UserFunction; import netneutrality.utils.UserFunction;
@@ -72,8 +76,6 @@ public class HelpCommand extends AbstractCommand {
context.replyPrivate("Command [" + c.getCommandName() + "] requires admin privileges"); context.replyPrivate("Command [" + c.getCommandName() + "] requires admin privileges");
} }
System.out.println(CommandUsage.create(c, new CommandUsage.Argument(CommandUsage.Argument.Type.REQUIRED, new String[] {"get", "add"}, "")));
MessageEmbed help = MessageFunction.buildHelpMessage(c); MessageEmbed help = MessageFunction.buildHelpMessage(c);
context.reply(new MessageBuilder().append(context.getDiscordUser()).append(" help has been sent your way!").build()); context.reply(new MessageBuilder().append(context.getDiscordUser()).append(" help has been sent your way!").build());
context.replyPrivate(help); context.replyPrivate(help);
@@ -7,9 +7,9 @@ package netneutrality.command.basic;
*/ */
import netneutrality.command.AbstractCommand; import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandType; import netneutrality.command.CommandType;
import netneutrality.command.CommandUsage; import netneutrality.command.CommandUsage;
import netneutrality.core.context.CommandContext;
public class PingCommand extends AbstractCommand { public class PingCommand extends AbstractCommand {
@@ -7,13 +7,11 @@ package netneutrality.command.bot;
*/ */
import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.entities.Role;
import netneutrality.GuildManager;
import netneutrality.command.AbstractCommand; import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandType; import netneutrality.command.CommandType;
import netneutrality.command.CommandUsage; import netneutrality.command.CommandUsage;
import netneutrality.db.DBController; import netneutrality.core.GuildManager;
import netneutrality.db.MysqlDatabase; import netneutrality.core.context.CommandContext;
import netneutrality.exceptions.CommandErrorException; import netneutrality.exceptions.CommandErrorException;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
@@ -60,7 +58,6 @@ public class ConfigureCommand extends AbstractCommand {
@Override @Override
public void execute(CommandContext context) { public void execute(CommandContext context) {
String[] args = context.getArgumentsAsArray(); String[] args = context.getArgumentsAsArray();
MysqlDatabase database = DBController.get();
GuildManager guildManager = GuildManager.getManager(context.getGuild()); GuildManager guildManager = GuildManager.getManager(context.getGuild());
if (args.length > 0) { if (args.length > 0) {
@@ -68,7 +65,7 @@ public class ConfigureCommand extends AbstractCommand {
if (context.getArg(0).equals("musicrole")) { if (context.getArg(0).equals("musicrole")) {
if (args.length == 1) { if (args.length == 1) {
String roleDb = (String) guildManager.getSetting(GuildManager.GuildSetting.MUSIC_ROLE); String roleDb = guildManager.getSetting(GuildManager.Settings.MUSIC_ROLE);
Role role = null; Role role = null;
if (!roleDb.isEmpty()) { if (!roleDb.isEmpty()) {
role = context.getGuild().getRoleById(roleDb); role = context.getGuild().getRoleById(roleDb);
@@ -83,15 +80,13 @@ public class ConfigureCommand extends AbstractCommand {
if (roles.size() == 1) { if (roles.size() == 1) {
Role role = roles.get(0); Role role = roles.get(0);
if (role.getGuild().getId().equals(context.getGuild().getId())) { if (role.getGuild().getId().equals(context.getGuild().getId())) {
database.prepareAndExecuteAsync("UPDATE guild_settings SET music_role = ? WHERE guild_id = ?", role.getId(), context.getGuild().getId()).blocking(); guildManager.setSettingValue(GuildManager.Settings.MUSIC_ROLE, role.getId());
guildManager.reloadSettings();
context.reply("Successfully set %s as the role needed for music command", role.getAsMention()); context.reply("Successfully set %s as the role needed for music command", role.getAsMention());
} }
} }
if (context.getArg(1).equals("reset")) { if (context.getArg(1).equals("reset")) {
database.prepareAndExecuteAsync("UPDATE guild_settings SET music_role = null WHERE guild_id = ?", context.getGuild().getId()).blocking(); guildManager.setSettingValue(GuildManager.Settings.MUSIC_ROLE, null);
guildManager.reloadSettings();
context.reply("Successful reset of the role"); context.reply("Successful reset of the role");
} }
} }
@@ -99,7 +94,7 @@ public class ConfigureCommand extends AbstractCommand {
if (context.getArg(0).equals("musicvolume")) { if (context.getArg(0).equals("musicvolume")) {
if (args.length == 1) { if (args.length == 1) {
int volume = (int) guildManager.getSetting(GuildManager.GuildSetting.MUSIC_VOLUME); int volume = Integer.parseInt(guildManager.getSetting(GuildManager.Settings.MUSIC_VOLUME));
context.reply("Default volume for music player: " + volume); context.reply("Default volume for music player: " + volume);
} }
@@ -108,8 +103,7 @@ public class ConfigureCommand extends AbstractCommand {
try { try {
int volume = Integer.parseInt(args[1]); int volume = Integer.parseInt(args[1]);
database.prepareAndExecuteAsync("UPDATE guild_settings SET music_volume = ? WHERE guild_id = ?", volume, context.getGuild().getId()).blocking(); guildManager.setSettingValue(GuildManager.Settings.MUSIC_VOLUME, String.valueOf(volume));
guildManager.reloadSettings();
MusicManager.get(context.getGuild()).setVolume(volume); MusicManager.get(context.getGuild()).setVolume(volume);
context.reply("Default volume for music player is now %d", volume); context.reply("Default volume for music player is now %d", volume);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
@@ -7,11 +7,10 @@ package netneutrality.command.crypto;
*/ */
import netneutrality.command.AbstractCommand; import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandType; import netneutrality.command.CommandType;
import netneutrality.command.CommandUsage; import netneutrality.command.CommandUsage;
import netneutrality.exceptions.CommandErrorException; import netneutrality.core.LogHandler;
import netneutrality.exceptions.CommandExecutionException; import netneutrality.core.context.CommandContext;
import netneutrality.http.WebModule; import netneutrality.http.WebModule;
import org.json.JSONException; import org.json.JSONException;
@@ -70,7 +69,8 @@ public class BitcoinPriceCommand extends AbstractCommand {
if (Currency.isCurrency(args[0].toUpperCase())) if (Currency.isCurrency(args[0].toUpperCase()))
currency = args[0].toUpperCase(); currency = args[0].toUpperCase();
else { else {
throw new CommandErrorException("Please enter a valid currency", context, null); context.reply("Please enter a valid currency");
return;
} }
} }
@@ -85,15 +85,11 @@ public class BitcoinPriceCommand extends AbstractCommand {
try { try {
WebModule http = new WebModule(String.format("%s?fsym=%s&tsyms=%s", baseURL, crypto, finalCurrency.toUpperCase())).request(); WebModule http = new WebModule(String.format("%s?fsym=%s&tsyms=%s", baseURL, crypto, finalCurrency.toUpperCase())).request();
price = dollarFormat.format(http.getAsObject().getDouble(finalCurrency)); price = dollarFormat.format(http.getAsObject().getDouble(finalCurrency));
t.editMessage(String.format("The current price of %s in %s is %s", crypto, finalCurrency, price)).queue();
} catch (IOException | JSONException | IllegalArgumentException | ArithmeticException e) { } catch (IOException | JSONException | IllegalArgumentException | ArithmeticException e) {
t.editMessage(String.format("Error getting price of %s!", crypto)).queue(); t.editMessage(String.format("Error getting price of %s!", crypto)).queue();
throw new CommandExecutionException("Error during web request", context, e); LogHandler.log(e);
} }
t.editMessage(String.format("The current price of %s in %s is %s", crypto, finalCurrency, price)).queue();
}); });
} }
} }
@@ -7,11 +7,10 @@ package netneutrality.command.crypto;
*/ */
import netneutrality.command.AbstractCommand; import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandType; import netneutrality.command.CommandType;
import netneutrality.command.CommandUsage; import netneutrality.command.CommandUsage;
import netneutrality.exceptions.CommandErrorException; import netneutrality.core.LogHandler;
import netneutrality.exceptions.CommandExecutionException; import netneutrality.core.context.CommandContext;
import netneutrality.http.WebModule; import netneutrality.http.WebModule;
import org.json.JSONException; import org.json.JSONException;
@@ -72,7 +71,8 @@ public class CryptoPriceCommand extends AbstractCommand {
if (Currency.isCurrency(args[1].toUpperCase())) if (Currency.isCurrency(args[1].toUpperCase()))
currency = args[1].toUpperCase(); currency = args[1].toUpperCase();
else { else {
throw new CommandErrorException("Please enter a valid currency", context, null); context.reply("Please enter a valid currency");
return;
} }
} }
@@ -88,17 +88,13 @@ public class CryptoPriceCommand extends AbstractCommand {
try { try {
WebModule http = new WebModule(String.format("%s?fsym=%s&tsyms=%s", baseURL, crypto, finalCurrency.toUpperCase())).request(); WebModule http = new WebModule(String.format("%s?fsym=%s&tsyms=%s", baseURL, crypto, finalCurrency.toUpperCase())).request();
price = dollarFormat.format(http.getAsObject().getDouble(finalCurrency)); price = dollarFormat.format(http.getAsObject().getDouble(finalCurrency));
t.editMessage(String.format("The current price of %s in %s is %s", crypto, finalCurrency, price)).queue();
} catch (IOException | JSONException | IllegalArgumentException | ArithmeticException e) { } catch (IOException | JSONException | IllegalArgumentException | ArithmeticException e) {
t.editMessage(String.format("Error getting price of %s!", crypto)).queue(); t.editMessage(String.format("Error getting price of %s!", crypto)).queue();
throw new CommandExecutionException("Error during web request", context, e); LogHandler.log(e);
} }
t.editMessage(String.format("The current price of %s in %s is %s", crypto, finalCurrency, price)).queue();
}); });
} }
} }
} }
@@ -7,11 +7,10 @@ package netneutrality.command.crypto;
*/ */
import netneutrality.command.AbstractCommand; import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandType; import netneutrality.command.CommandType;
import netneutrality.command.CommandUsage; import netneutrality.command.CommandUsage;
import netneutrality.exceptions.CommandErrorException; import netneutrality.core.LogHandler;
import netneutrality.exceptions.CommandExecutionException; import netneutrality.core.context.CommandContext;
import netneutrality.http.WebModule; import netneutrality.http.WebModule;
import org.json.JSONException; import org.json.JSONException;
@@ -70,7 +69,8 @@ public class EthereumPriceCommand extends AbstractCommand {
if (Currency.isCurrency(args[0].toUpperCase())) if (Currency.isCurrency(args[0].toUpperCase()))
currency = args[0].toUpperCase(); currency = args[0].toUpperCase();
else { else {
throw new CommandErrorException("Please enter a valid currency", context, null); context.reply("Please enter a valid currency");
return;
} }
} }
@@ -85,15 +85,11 @@ public class EthereumPriceCommand extends AbstractCommand {
try { try {
WebModule http = new WebModule(String.format("%s?fsym=%s&tsyms=%s", baseURL, crypto, finalCurrency.toUpperCase())).request(); WebModule http = new WebModule(String.format("%s?fsym=%s&tsyms=%s", baseURL, crypto, finalCurrency.toUpperCase())).request();
price = dollarFormat.format(http.getAsObject().getDouble(finalCurrency)); price = dollarFormat.format(http.getAsObject().getDouble(finalCurrency));
t.editMessage(String.format("The current price of %s in %s is %s", crypto, finalCurrency, price)).queue();
} catch (IOException | JSONException | IllegalArgumentException e) { } catch (IOException | JSONException | IllegalArgumentException e) {
t.editMessage(String.format("Error getting price of %s!", crypto)).queue(); t.editMessage(String.format("Error getting price of %s!", crypto)).queue();
throw new CommandExecutionException("Error during web request", context, e); LogHandler.log(e);
} }
t.editMessage(String.format("The current price of %s in %s is %s", crypto, finalCurrency, price)).queue();
}); });
} }
} }
@@ -7,11 +7,10 @@ package netneutrality.command.crypto;
*/ */
import netneutrality.command.AbstractCommand; import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandType; import netneutrality.command.CommandType;
import netneutrality.command.CommandUsage; import netneutrality.command.CommandUsage;
import netneutrality.exceptions.CommandErrorException; import netneutrality.core.LogHandler;
import netneutrality.exceptions.CommandExecutionException; import netneutrality.core.context.CommandContext;
import netneutrality.http.WebModule; import netneutrality.http.WebModule;
import org.json.JSONException; import org.json.JSONException;
@@ -70,7 +69,8 @@ public class LitecoinPriceCommand extends AbstractCommand {
if (Currency.isCurrency(args[0].toUpperCase())) if (Currency.isCurrency(args[0].toUpperCase()))
currency = args[0].toUpperCase(); currency = args[0].toUpperCase();
else { else {
throw new CommandErrorException("Please enter a valid currency", context, null); context.reply("Please enter a valid currency");
return;
} }
} }
@@ -85,14 +85,11 @@ public class LitecoinPriceCommand extends AbstractCommand {
try { try {
WebModule http = new WebModule(String.format("%s?fsym=%s&tsyms=%s", baseURL, crypto, finalCurrency.toUpperCase())).request(); WebModule http = new WebModule(String.format("%s?fsym=%s&tsyms=%s", baseURL, crypto, finalCurrency.toUpperCase())).request();
price = dollarFormat.format(http.getAsObject().getDouble(finalCurrency)); price = dollarFormat.format(http.getAsObject().getDouble(finalCurrency));
t.editMessage(String.format("The current price of %s in %s is %s", crypto, finalCurrency, price)).queue();
} catch (IOException | JSONException | IllegalArgumentException | ArithmeticException e) { } catch (IOException | JSONException | IllegalArgumentException | ArithmeticException e) {
t.editMessage(String.format("Error getting price of %s!", crypto)).queue(); t.editMessage(String.format("Error getting price of %s!", crypto)).queue();
throw new CommandExecutionException("Error during web request", context, e); LogHandler.log(e);
} }
t.editMessage(String.format("The current price of %s in %s is %s", crypto, finalCurrency, price)).queue();
}); });
} }
} }
@@ -7,13 +7,13 @@ package netneutrality.command.message;
*/ */
import netneutrality.command.AbstractCommand; import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandType; import netneutrality.command.CommandType;
import netneutrality.command.CommandUsage; import netneutrality.command.CommandUsage;
import netneutrality.core.LogHandler;
import netneutrality.core.context.CommandContext;
import netneutrality.db.DBController; import netneutrality.db.DBController;
import netneutrality.db.controllers.DBBlacklist; import netneutrality.db.controllers.DBBlacklist;
import netneutrality.db.models.MBlacklist; import netneutrality.db.entities.OBlacklist;
import netneutrality.exceptions.CommandExecutionException;
import java.util.ArrayList; import java.util.ArrayList;
@@ -57,71 +57,39 @@ public class BlacklistCommand extends AbstractCommand {
@Override @Override
public void execute(CommandContext context) { public void execute(CommandContext context) {
String[] args = context.getArgumentsAsArray(); String[] args = context.getArgumentsAsArray();
DBBlacklist controller = ((DBBlacklist) DBController.get("blacklist")); DBBlacklist controller = DBController.get("blacklist", DBBlacklist.class);
if (controller == null) { if (controller == null) {
throw new CommandExecutionException("Error getting database controller", context, null);
} }
if (args.length > 0 && args.length < 3) { if (args.length > 0 && args.length < 3) {
String word = (args.length == 2 ? args[1] : ""); String word = (args.length == 2 ? args[1] : "");
switch (args[0]) { switch (args[0]) {
case "get" -> {
case "get":
context.getChannel().sendMessage("Retrieving list, please wait...").queue(t -> { context.getChannel().sendMessage("Retrieving list, please wait...").queue(t -> {
ArrayList<OBlacklist> blacklists = new ArrayList<>();
try {
blacklists = controller.getBlacklistForGuild(context);
} catch (Exception e) {
LogHandler.log(e);
}
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
ArrayList<MBlacklist> blacklists = controller.getBlacklistFromServer(context.getGuild().getId()); for (OBlacklist bl : blacklists) {
for (MBlacklist bl : blacklists) { sb.append(bl.getWord()).append(" -> ").append(bl.getEnabled() ? "enabled" : "disabled").append("\n");
sb.append(bl.getWord()).append(" -> ").append(bl.isEnabled() ? "enabled" : "disabled").append("\n"); }
}
t.editMessage("List of blacklisted words for this server [" + context.getGuild().getName() + "] :\n" + (blacklists.isEmpty() ? "No word found" : sb.toString())).queue(); t.editMessage("List of blacklisted words for this server [" + context.getGuild().getName() + "] :\n" + (blacklists.isEmpty() ? "No word found" : sb.toString())).queue();
}); });
}
break; case "add" -> controller.add(word, context);
case "remove" -> controller.delete(word, context);
case "add": case "disable" -> controller.disable(word, context);
case "enable" -> controller.enable(word, context);
if (controller.add(new MBlacklist(word, true, context.getDiscordUser().getId(), context.getGuild().getId()))) {
context.reply(String.format("Added the word [%s] to the blacklist.", word));
} else {
context.reply(String.format("Error adding [%s] to the blacklist. It's already blacklisted!", word));
}
break;
case "remove":
if (controller.delete(word, context.getGuild().getId())) {
context.reply("Removed the word \"" + word + "\" from the blacklist.");
} else {
context.reply("Error removing \"" + word + "\" from the blacklist");
}
break;
case "disable":
if (controller.disable(word, context.getGuild().getId())) {
context.reply("Removed the word \"" + word + "\" from the blacklist.");
} else {
context.reply("Error removing \"" + word + "\" from the blacklist");
}
break;
case "enable":
if (controller.enable(word, context.getGuild().getId())) {
context.reply("Removed the word \"" + word + "\" from the blacklist.");
} else {
context.reply("Error removing \"" + word + "\" from the blacklist");
}
break;
} }
} }
} }
@@ -7,9 +7,9 @@ package netneutrality.command.message;
*/ */
import netneutrality.command.AbstractCommand; import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandType; import netneutrality.command.CommandType;
import netneutrality.command.CommandUsage; import netneutrality.command.CommandUsage;
import netneutrality.core.context.CommandContext;
import netneutrality.utils.ChannelFunction; import netneutrality.utils.ChannelFunction;
public class PruneCommand extends AbstractCommand { public class PruneCommand extends AbstractCommand {
@@ -8,9 +8,9 @@ package netneutrality.command.music;
*/ */
import netneutrality.command.AbstractMusicCommand; import netneutrality.command.AbstractMusicCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandType; import netneutrality.command.CommandType;
import netneutrality.command.CommandUsage; import netneutrality.command.CommandUsage;
import netneutrality.core.context.CommandContext;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
public class BitconnectCommand extends AbstractMusicCommand { public class BitconnectCommand extends AbstractMusicCommand {
@@ -9,8 +9,8 @@ package netneutrality.command.music;
import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Member;
import netneutrality.command.AbstractMusicCommand; import netneutrality.command.AbstractMusicCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandUsage; import netneutrality.command.CommandUsage;
import netneutrality.core.context.CommandContext;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
import netneutrality.utils.MessageFunction; import netneutrality.utils.MessageFunction;
import netneutrality.utils.MusicUtils; import netneutrality.utils.MusicUtils;
@@ -46,7 +46,8 @@ public class CurrentlyPlayingCommand extends AbstractMusicCommand {
public void execute(CommandContext context) { public void execute(CommandContext context) {
Member member = context.getGuildUser(); Member member = context.getGuildUser();
MusicManager player = MusicManager.get(context.getGuild()); MusicManager player = MusicManager.get(context.getGuild());
MusicUtils.checkIfConnected(player, context); if (!MusicUtils.checkIfConnected(player, context))
return;
if (player.getCurrentlyPlaying() != null) { if (player.getCurrentlyPlaying() != null) {
context.reply(MessageFunction.buildCurrentlyPlayingMessage(player, member)); context.reply(MessageFunction.buildCurrentlyPlayingMessage(player, member));
@@ -8,18 +8,14 @@ package netneutrality.command.music;
*/ */
import netneutrality.command.AbstractMusicCommand; import netneutrality.command.AbstractMusicCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandUsage; import netneutrality.command.CommandUsage;
import netneutrality.core.context.CommandContext;
import netneutrality.exceptions.CommandErrorException; import netneutrality.exceptions.CommandErrorException;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
import netneutrality.utils.MessageFunction; import netneutrality.utils.MessageFunction;
import netneutrality.utils.MusicUtils; import netneutrality.utils.MusicUtils;
public class DeleteQueueCommand extends AbstractMusicCommand { public class DeleteQueueCommand extends AbstractMusicCommand {
@Override
public boolean needAdmin() {
return true;
}
@Override @Override
public boolean isEnabled() { public boolean isEnabled() {
@@ -51,7 +47,11 @@ public class DeleteQueueCommand extends AbstractMusicCommand {
@Override @Override
public void execute(CommandContext context) { public void execute(CommandContext context) {
MusicManager player = MusicManager.get(context.getGuild()); MusicManager player = MusicManager.get(context.getGuild());
MusicUtils.checkIfConnected(player, context); if (!MusicUtils.checkIfConnected(player, context))
return;
if (!MusicUtils.checkIfDj(player, context))
return;
if (context.getArgumentsAsArray().length == 0) { if (context.getArgumentsAsArray().length == 0) {
context.reply("Select the track you want to delete from the queue (track# or all)"); context.reply("Select the track you want to delete from the queue (track# or all)");
@@ -66,7 +66,7 @@ public class DeleteQueueCommand extends AbstractMusicCommand {
if (queueSize > 0) { if (queueSize > 0) {
player.leave(); player.leave();
player.getScheduler().getQueue().clear(); player.getScheduler().getQueue().clear();
context.reply("Removed " + queueSize-- + (queueSize > 1 ? " tracks" : "track") + " from the queue"); context.reply(String.format("Removed %d track%s from the queue", queueSize--, (queueSize > 1 ? "s" : "")));
} else { } else {
context.reply("Queue is empty!"); context.reply("Queue is empty!");
} }
@@ -86,11 +86,6 @@ public class DeleteQueueCommand extends AbstractMusicCommand {
throw new CommandErrorException("Please enter a number", context, e); throw new CommandErrorException("Please enter a number", context, e);
} }
} }
} }
} }
} }
@@ -9,9 +9,8 @@ package netneutrality.command.music;
import net.dv8tion.jda.api.entities.VoiceChannel; import net.dv8tion.jda.api.entities.VoiceChannel;
import netneutrality.command.AbstractMusicCommand; import netneutrality.command.AbstractMusicCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandUsage; import netneutrality.command.CommandUsage;
import netneutrality.exceptions.CommandErrorException; import netneutrality.core.context.CommandContext;
import netneutrality.exceptions.CommandExecutionException; import netneutrality.exceptions.CommandExecutionException;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
@@ -47,15 +46,17 @@ public class JoinCommand extends AbstractMusicCommand {
MusicManager player = MusicManager.get(context.getGuild()); MusicManager player = MusicManager.get(context.getGuild());
if (context.getGuildUser().getVoiceState() == null) { if (context.getGuildUser().getVoiceState() == null) {
throw new CommandExecutionException("Voice state is null", context, null); throw new CommandExecutionException("Voice state is null, this should not happen", context, null);
} }
if (!context.getGuildUser().getVoiceState().inVoiceChannel()) { if (!context.getGuildUser().getVoiceState().inVoiceChannel()) {
throw new CommandErrorException("You are not in a voice channel", context, null); context.reply("You are not in a voice channel");
return;
} }
if (player.isConnected()) { if (player.isConnected()) {
throw new CommandErrorException("Player is already in a voice channel", context, null); context.reply("Player is already in a voice channel");
return;
} }
VoiceChannel vChannel = context.getGuildUser().getVoiceState().getChannel(); VoiceChannel vChannel = context.getGuildUser().getVoiceState().getChannel();
@@ -8,8 +8,8 @@ package netneutrality.command.music;
*/ */
import netneutrality.command.AbstractMusicCommand; import netneutrality.command.AbstractMusicCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandUsage; import netneutrality.command.CommandUsage;
import netneutrality.core.context.CommandContext;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
import netneutrality.utils.MusicUtils; import netneutrality.utils.MusicUtils;
@@ -47,7 +47,8 @@ public class LeaveCommand extends AbstractMusicCommand {
@Override @Override
public void execute(CommandContext context) { public void execute(CommandContext context) {
MusicManager player = MusicManager.get(context.getGuild()); MusicManager player = MusicManager.get(context.getGuild());
MusicUtils.checkIfConnected(player, context); if (!MusicUtils.checkIfConnected(player, context))
return;
player.leave(); player.leave();
} }
@@ -8,8 +8,8 @@ package netneutrality.command.music;
*/ */
import netneutrality.command.AbstractMusicCommand; import netneutrality.command.AbstractMusicCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandUsage; import netneutrality.command.CommandUsage;
import netneutrality.core.context.CommandContext;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
public class PlayCommand extends AbstractMusicCommand { public class PlayCommand extends AbstractMusicCommand {
@@ -8,8 +8,8 @@ package netneutrality.command.music;
*/ */
import netneutrality.command.AbstractMusicCommand; import netneutrality.command.AbstractMusicCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandUsage; import netneutrality.command.CommandUsage;
import netneutrality.core.context.CommandContext;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
import netneutrality.utils.MusicUtils; import netneutrality.utils.MusicUtils;
import netneutrality.utils.UserFunction; import netneutrality.utils.UserFunction;
@@ -43,7 +43,8 @@ public class SkipCommand extends AbstractMusicCommand {
@Override @Override
public void execute(CommandContext context) { public void execute(CommandContext context) {
MusicManager player = MusicManager.get(context.getGuild()); MusicManager player = MusicManager.get(context.getGuild());
MusicUtils.checkIfConnected(player, context); if (!MusicUtils.checkIfConnected(player, context))
return;
// Combined fonctionality of vote skip // Combined fonctionality of vote skip
//TODO: clean ifs //TODO: clean ifs
@@ -8,8 +8,8 @@ package netneutrality.command.music;
*/ */
import netneutrality.command.AbstractMusicCommand; import netneutrality.command.AbstractMusicCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandUsage; import netneutrality.command.CommandUsage;
import netneutrality.core.context.CommandContext;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
import netneutrality.utils.MusicUtils; import netneutrality.utils.MusicUtils;
import netneutrality.utils.UserFunction; import netneutrality.utils.UserFunction;
@@ -44,7 +44,8 @@ public class StopCommand extends AbstractMusicCommand {
@Override @Override
public void execute(CommandContext context) { public void execute(CommandContext context) {
MusicManager player = MusicManager.get(context.getGuild()); MusicManager player = MusicManager.get(context.getGuild());
MusicUtils.checkIfConnected(player, context); if (!MusicUtils.checkIfConnected(player, context))
return;
if (UserFunction.isAdmin(context.getGuildUser()) || context.getGuildUser().getId().equals(player.getRequesterOfCurrentTrack().getId())) { if (UserFunction.isAdmin(context.getGuildUser()) || context.getGuildUser().getId().equals(player.getRequesterOfCurrentTrack().getId())) {
player.leave(); player.leave();
@@ -9,8 +9,8 @@ package netneutrality.command.music;
import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Member;
import netneutrality.command.AbstractMusicCommand; import netneutrality.command.AbstractMusicCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandUsage; import netneutrality.command.CommandUsage;
import netneutrality.core.context.CommandContext;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
import netneutrality.utils.MessageFunction; import netneutrality.utils.MessageFunction;
import netneutrality.utils.MusicUtils; import netneutrality.utils.MusicUtils;
@@ -50,7 +50,8 @@ public class ViewQueueCommand extends AbstractMusicCommand {
public void execute(CommandContext context) { public void execute(CommandContext context) {
Member member = context.getGuildUser(); Member member = context.getGuildUser();
MusicManager player = MusicManager.get(context.getGuild()); MusicManager player = MusicManager.get(context.getGuild());
MusicUtils.checkIfConnected(player, context); if (!MusicUtils.checkIfConnected(player, context))
return;
int queueSize = player.getScheduler().getQueue().size(); int queueSize = player.getScheduler().getQueue().size();
if (queueSize > 0) { if (queueSize > 0) {
@@ -8,17 +8,13 @@ package netneutrality.command.music;
*/ */
import netneutrality.command.AbstractMusicCommand; import netneutrality.command.AbstractMusicCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandUsage; import netneutrality.command.CommandUsage;
import netneutrality.core.context.CommandContext;
import netneutrality.exceptions.CommandErrorException; import netneutrality.exceptions.CommandErrorException;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
import netneutrality.utils.MusicUtils; import netneutrality.utils.MusicUtils;
public class VolumeCommand extends AbstractMusicCommand { public class VolumeCommand extends AbstractMusicCommand {
@Override
public boolean needAdmin() {
return true;
}
@Override @Override
public boolean isEnabled() { public boolean isEnabled() {
@@ -48,14 +44,18 @@ public class VolumeCommand extends AbstractMusicCommand {
@Override @Override
public void execute(CommandContext context) { public void execute(CommandContext context) {
MusicManager player = MusicManager.get(context.getGuild()); MusicManager player = MusicManager.get(context.getGuild());
MusicUtils.checkIfConnected(player, context); if (!MusicUtils.checkIfConnected(player, context))
return;
if (!MusicUtils.checkIfDj(player, context))
return;
try { try {
int volume = Integer.parseInt(context.getArgumentsAsArray()[0]); int volume = Integer.parseInt(context.getArgumentsAsArray()[0]);
player.setVolume(volume); player.setVolume(volume);
context.reply("Volume set to %s", volume); context.reply("Volume set to %s", volume);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
throw new CommandErrorException("Please enter a value from 0 to 100", context, null); throw new CommandErrorException("Please enter a value from 0 to 100", context, e);
} }
} }
@@ -7,8 +7,8 @@ package netneutrality.command.music;
*/ */
import netneutrality.command.AbstractMusicCommand; import netneutrality.command.AbstractMusicCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandUsage; import netneutrality.command.CommandUsage;
import netneutrality.core.context.CommandContext;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
import netneutrality.utils.MusicUtils; import netneutrality.utils.MusicUtils;
@@ -41,9 +41,10 @@ public class VoteSkipCommand extends AbstractMusicCommand {
@Override @Override
public void execute(CommandContext context) { public void execute(CommandContext context) {
MusicManager manager = MusicManager.get(context.getGuild()); MusicManager player = MusicManager.get(context.getGuild());
MusicUtils.checkIfConnected(manager, context); if (!MusicUtils.checkIfConnected(player, context))
return;
manager.voteSkip(context); player.voteSkip(context);
} }
} }
@@ -9,18 +9,17 @@ package netneutrality.command.specific;
import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.entities.User;
import netneutrality.command.AbstractCommand; import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandType; import netneutrality.command.CommandType;
import netneutrality.command.CommandUsage; import netneutrality.command.CommandUsage;
import netneutrality.core.context.CommandContext;
import netneutrality.db.DBController; import netneutrality.db.DBController;
import netneutrality.db.controllers.DBMessage; import netneutrality.db.controllers.DBMessage;
import netneutrality.db.models.MMessage; import netneutrality.db.entities.OLogMessage;
import netneutrality.utils.Settings; import netneutrality.utils.Settings;
import java.awt.*; import java.awt.*;
import java.time.OffsetDateTime; import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter; import java.util.List;
import java.util.ArrayList;
public class DatabaseCommand extends AbstractCommand { public class DatabaseCommand extends AbstractCommand {
@@ -75,29 +74,28 @@ public class DatabaseCommand extends AbstractCommand {
if (args.length > 1) { if (args.length > 1) {
MMessage message = ((DBMessage) DBController.get("message")).getMessage(args[1]); OLogMessage message = DBController.get("message", DBMessage.class).getMessage(args[1]);
if (message != null) { if (message != null) {
EmbedBuilder embed = new EmbedBuilder(); EmbedBuilder embed = new EmbedBuilder();
embed.setColor(Color.BLUE); embed.setColor(Color.BLUE);
embed.setTimestamp( embed.setTimestamp(message.getDateSent());
DateTimeFormatter.ofPattern(Settings.getInstance().DATETIMEFORMAT).parse(message.getDateSent())); embed.setFooter("Guild : " + context.getGuild().getId() + " | ID : " + message.getMessageId(), null);
embed.setFooter("Guild : " + message.getServerId() + " | ID : " + message.getMessageId(), null);
embed.setDescription( embed.setDescription(
"Message from " + message.getSender() + " on the channel " + message.getChannelName()); "Message from " + message.getUserId() + " on the channel " + message.getChannelId());
embed.addField("Message: ", "" + message.getMessage(), false); embed.addField("Message: ", "" + message.getMessage(), false);
context.reply(embed.build()); context.reply(embed.build());
} else { } else {
//TODO: cached user lol xd //TODO: cached user lol xd
User user = context.getJDA().getUserById(args[1]); User user = context.getJDA().getUserById(args[1]);
if (user != null) { if (user != null) {
ArrayList<MMessage> messages = ((DBMessage) DBController.get("message")) List<OLogMessage> messages = DBController.get("message", DBMessage.class)
.getMessagesFromUser(user.getName(), context.getGuild().getName(), 10); .getMessagesFromUser(user.getName(), context.getGuild().getName(), 10);
EmbedBuilder embed = new EmbedBuilder(); EmbedBuilder embed = new EmbedBuilder();
embed.setColor(Color.BLUE); embed.setColor(Color.BLUE);
embed.setTimestamp(OffsetDateTime.now()); embed.setTimestamp(OffsetDateTime.now());
for (MMessage message1 : messages) { for (OLogMessage message1 : messages) {
embed.addField( embed.addField(
"Message in channel \"" + message1.getChannelName() + "\" sent on " "Message in channel \"" + message1.getChannelId() + "\" sent on "
+ message1.getDateSent(), + message1.getDateSent(),
"" + message1.getMessage(), false); "" + message1.getMessage(), false);
} }
@@ -7,9 +7,9 @@ package netneutrality.command.specific;
*/ */
import netneutrality.command.AbstractCommand; import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandType; import netneutrality.command.CommandType;
import netneutrality.command.CommandUsage; import netneutrality.command.CommandUsage;
import netneutrality.core.context.CommandContext;
public class LoggingCommand extends AbstractCommand { public class LoggingCommand extends AbstractCommand {
@@ -0,0 +1,279 @@
package netneutrality.core;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.TextChannel;
import netneutrality.NetNeutrality;
import netneutrality.db.DBController;
import netneutrality.db.controllers.DBMessage;
import netneutrality.db.entities.OBlacklist;
import netneutrality.db.entities.OGuild;
import netneutrality.db.entities.OGuildSetting;
import netneutrality.handler.ratelimiter.IMessageRateLimiter;
import netneutrality.handler.ratelimiter.MessageRateLimiterImpl;
import netneutrality.utils.JpaUtils;
import netneutrality.utils.MessageFunction;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class GuildManager {
public enum Settings {
MUSIC_ROLE("MUSIC_ROLE", ""),
MUSIC_CHANNEL("MUSIC_CHANNEL", ""),
MUSIC_VOLUME("MUSIC_VOLUME", "30"),
BLACKLIST_CHANNELS("BLACKLIST_EXCLUDE_CHANNELS", "");
private final String name;
private final String defaultValue;
Settings(String name, String defaultValue) {
this.name = name;
this.defaultValue = defaultValue;
}
public String getName() {
return name;
}
public String getDefaultValue() {
return defaultValue;
}
}
private static final Logger logger = LoggerFactory.getLogger(GuildManager.class);
private static final Map<String, GuildManager> managers = new ConcurrentHashMap<>();
private static final SessionFactory sessionFactory = SessionManager.getSessionFactory();
private final Map<String, String> settingsCache = new HashMap<>();
private final Set<String> blacklistCache = new HashSet<>();
private final Guild guild;
private OGuild guildEntity;
private final IMessageRateLimiter rateLimiter;
private GuildManager(Guild guild) {
this.guild = guild;
this.guildEntity = loadGuildFromDb(guild.getId());
this.rateLimiter = new MessageRateLimiterImpl();
managers.put(guild.getId(), this);
reloadBlacklistCache(true);
}
private GuildManager(String guildId) {
Guild temp = NetNeutrality.getJDA().getGuildById(guildId);
if (temp == null)
throw new IllegalArgumentException("Guild does not exist in current cache");
this.guild = temp;
this.guildEntity = loadGuildFromDb(guild.getId());
this.rateLimiter = new MessageRateLimiterImpl();
managers.put(guild.getId(), this);
reloadBlacklistCache(true);
}
public static GuildManager getManager(Guild guild) {
if (managers.containsKey(guild.getId())) {
return managers.get(guild.getId());
} else {
return new GuildManager(guild);
}
}
public static GuildManager getManager(String guildId) {
if (managers.containsKey(guildId)) {
return managers.get(guildId);
} else {
return new GuildManager(guildId);
}
}
// Getter
public static Map<String, GuildManager> getManagers() {
return managers;
}
public boolean isLoggingEnabled() {
return guildEntity.getLogging();
}
public boolean isDebugEnabled() {
return guildEntity.getDebug();
}
public IMessageRateLimiter getRateLimiter() {
return rateLimiter;
}
public Guild getGuild() {
return guild;
}
public OGuild getGuildEntity() {
return guildEntity;
}
public Set<String> getBlacklistCache() {
return blacklistCache;
}
public Map<String, String> getSettings() {
return settingsCache;
}
public String getSetting(Settings setting) {
String value = settingsCache.get(setting.getName());
if (value == null) {
setSettingValue(setting, null);
value = setting.getDefaultValue();
}
return value;
}
public void setSettingValue(Settings setting, String value) {
Session session = sessionFactory.openSession();
session.load(guildEntity, guildEntity.getGuildId());
if (value == null || value.isEmpty()) {
value = setting.getDefaultValue();
}
OGuildSetting oGuildSetting = guildEntity.getSettingByName(setting.getName());
session.beginTransaction();
if (oGuildSetting == null) {
oGuildSetting = new OGuildSetting();
oGuildSetting.setGuild(guildEntity);
oGuildSetting.setName(setting.getName());
oGuildSetting.setValue(value);
session.save(oGuildSetting);
} else {
oGuildSetting.setValue(value);
session.update(oGuildSetting);
}
session.getTransaction().commit();
reloadSettingsCache(false);
session.close();
}
public static boolean reloadSettingsForGuild(String guildId) {
GuildManager manager = GuildManager.getManager(guildId);
manager.reloadSettingsCache(true);
return true;
}
public static boolean reloadSettingsForGuild(Guild guild) {
GuildManager manager = GuildManager.getManager(guild.getId());
manager.reloadSettingsCache(true);
return true;
}
public void reloadSettingsCache(boolean close) {
logger.debug("Reloading settings cache for guild: " + guild.getId());
settingsCache.clear();
Session session = sessionFactory.openSession();
JpaUtils.tryLoad(session, guildEntity, guildEntity.getGuildId());
Set<OGuildSetting> settingSet = guildEntity.getGuildSettings();
for (OGuildSetting setting : settingSet) {
settingsCache.put(setting.getName(), setting.getValue());
}
if (close)
session.close();
}
public void reloadBlacklistCache(boolean close) {
logger.debug("Reloading blacklist cache for guild: " + guild.getId());
blacklistCache.clear();
Session session = sessionFactory.openSession();
JpaUtils.tryLoad(session, guildEntity, guildEntity.getGuildId());
Set<OBlacklist> oBlacklistSet = guildEntity.getBlacklists();
for (OBlacklist bl : oBlacklistSet) {
if (bl.getEnabled()) {
blacklistCache.add(bl.getWord());
}
}
if (close)
session.close();
}
public void checkAndLogMessage(Message message, Member member, TextChannel channel) {
if (isLoggingEnabled()) {
DBController.get("message", DBMessage.class).log(this, channel, member, message);
}
}
public void checkBlacklist(Message message, TextChannel channel) {
MessageFunction.testMessageAgainstBlacklist(message, channel, blacklistCache);
}
private OGuild loadGuildFromDb(String guildId) {
Session session = sessionFactory.openSession();
OGuild entity = session.get(OGuild.class, guildId);
if (entity == null) {
logger.debug("Guild[{}] doesn't exist in DB, creating entity..", guildId);
session.beginTransaction();
entity = new OGuild();
entity.setGuildId(guildId);
session.save(entity);
session.getTransaction().commit();
handleJoinEvent();
}
session.close();
return entity;
}
public void handleJoinEvent() {
guild.getTextChannels()
.stream()
.filter(textChannel -> textChannel.getName().equals("debug") || textChannel.getName().equals("log"))
.forEach(textChannel -> textChannel.sendMessage("Error logging enabled on channel " + textChannel.getAsMention()).queue());
}
public void reloadEntity() {
this.guildEntity = loadGuildFromDb(guild.getId());
}
public void removeFromDB() {
Session session = sessionFactory.openSession();
session.beginTransaction();
session.delete(guildEntity);
session.getTransaction().commit();
session.close();
managers.remove(guild.getId());
}
}
@@ -1,4 +1,4 @@
package netneutrality.handler; package netneutrality.core;
/* /*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
@@ -6,17 +6,15 @@ package netneutrality.handler;
* https://discord.gg/CdFcyQ * https://discord.gg/CdFcyQ
*/ */
import io.sentry.Sentry;
import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.entities.TextChannel;
import netneutrality.GuildManager; import netneutrality.core.context.CommandContext;
import netneutrality.command.CommandContext;
import netneutrality.exceptions.CommandErrorException; import netneutrality.exceptions.CommandErrorException;
import netneutrality.exceptions.CommandExecutionException; import netneutrality.exceptions.CommandExecutionException;
import netneutrality.utils.MessageFunction; import netneutrality.utils.MessageFunction;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.sql.SQLException;
public class LogHandler { public class LogHandler {
private final static Logger logger = LoggerFactory.getLogger(LogHandler.class); private final static Logger logger = LoggerFactory.getLogger(LogHandler.class);
@@ -27,15 +25,15 @@ public class LogHandler {
* @param e The exceptions to log * @param e The exceptions to log
*/ */
public static void log(Exception e) { public static void log(Exception e) {
if (e instanceof CommandErrorException) { if (e instanceof CommandErrorException) {
sendMessageToChannel((CommandErrorException) e); sendMessageToChannel((CommandErrorException) e);
} else if (e instanceof CommandExecutionException) { } else if (e instanceof CommandExecutionException) {
Sentry.captureException(e);
logInternally((CommandExecutionException) e); logInternally((CommandExecutionException) e);
tryLogToDebugChannel((CommandExecutionException) e); tryLogToDebugChannel((CommandExecutionException) e);
} else if (e instanceof SQLException) {
logger.error(e.getMessage(), e);
} else { } else {
Sentry.captureException(e);
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} }
@@ -55,11 +53,6 @@ public class LogHandler {
logger.error("Exception thrown from command [{}] in guild [{}]: {}", context.getCommand().getCommandName(), context.getGuild().getId(), error.getMessage(), error); logger.error("Exception thrown from command [{}] in guild [{}]: {}", context.getCommand().getCommandName(), context.getGuild().getId(), error.getMessage(), error);
} }
private static void tryLogToAllChannels(SQLException error) {
}
private static void tryLogToDebugChannel(CommandExecutionException error) { private static void tryLogToDebugChannel(CommandExecutionException error) {
CommandContext context = error.getCommandContext(); CommandContext context = error.getCommandContext();
@@ -0,0 +1,66 @@
package netneutrality.core;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import io.sentry.Sentry;
import netneutrality.utils.Settings;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Environment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
public class SessionManager {
private final static Logger logger = LoggerFactory.getLogger(SessionManager.class);
private static StandardServiceRegistry registry;
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder().configure();
Map<String, String> settings = new HashMap<>();
String dbName = Settings.getInstance().get("MYSQL_DATABASE", "netneutrality");
String dbUser = Settings.getInstance().get("MYSQL_USER", "root");
String dbPass = Settings.getInstance().get("MYSQL_PASSWORD", "");
String dbHost = Settings.getInstance().get("MYSQL_HOST", "localhost");
logger.info(String.format("Connecting to database '%s' at %s:3306 with user '%s'", dbName, dbHost, dbUser));
settings.put(Environment.URL, String.format("jdbc:mysql://%s:3306/%s", dbHost, dbName));
settings.put(Environment.USER, dbUser);
settings.put(Environment.PASS, dbPass);
registryBuilder.applySettings(settings);
registry = registryBuilder.build();
MetadataSources sources = new MetadataSources(registry);
Metadata metadata = sources.getMetadataBuilder().build();
sessionFactory = metadata.getSessionFactoryBuilder().build();
} catch (Exception e) {
Sentry.captureException(e);
shutdown();
logger.error("Error connecting to database. Shutting down..", e);
System.exit(1);
}
}
return sessionFactory;
}
public static void shutdown() {
if (registry != null) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
}
@@ -1,4 +1,4 @@
package netneutrality.utils;/* package netneutrality.core;/*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
* https://xtremcommunity.com/ * https://xtremcommunity.com/
@@ -6,7 +6,13 @@ package netneutrality.utils;/*
*/ */
import netneutrality.GuildManager; /*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
import netneutrality.music.TrackScheduler; import netneutrality.music.TrackScheduler;
import org.json.JSONArray; import org.json.JSONArray;
@@ -15,7 +21,6 @@ import org.json.JSONObject;
import java.io.File; import java.io.File;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files;
import java.util.Map; import java.util.Map;
public class UnsafeShutdown { public class UnsafeShutdown {
@@ -1,4 +1,4 @@
package netneutrality.command; package netneutrality.core.context;
/* /*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
@@ -6,14 +6,19 @@ package netneutrality.command;
* https://discord.gg/CdFcyQ * https://discord.gg/CdFcyQ
*/ */
import io.sentry.Breadcrumb;
import io.sentry.Sentry;
import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.MessageBuilder; import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.entities.*; import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent; import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import netneutrality.ThreadManager; import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandUsage;
import netneutrality.core.GuildManager;
import netneutrality.core.LogHandler;
import netneutrality.exceptions.CommandErrorException; import netneutrality.exceptions.CommandErrorException;
import netneutrality.exceptions.CommandExecutionException; import netneutrality.exceptions.CommandExecutionException;
import netneutrality.handler.LogHandler; import netneutrality.thread.ThreadManager;
import netneutrality.utils.Settings; import netneutrality.utils.Settings;
import netneutrality.utils.UserFunction; import netneutrality.utils.UserFunction;
@@ -39,6 +44,12 @@ public class CommandContext {
this.channel = channel; this.channel = channel;
this.user = user; this.user = user;
this.jda = jda; this.jda = jda;
io.sentry.protocol.User sentryUser = new io.sentry.protocol.User();
sentryUser.setId(member.getId());
sentryUser.setUsername(member.getEffectiveName());
Sentry.setUser(sentryUser);
Sentry.addBreadcrumb(Breadcrumb.info("New context for message id " + message.getId()));
} }
public static CommandContext createContext(GuildMessageReceivedEvent event) { public static CommandContext createContext(GuildMessageReceivedEvent event) {
@@ -104,6 +115,10 @@ public class CommandContext {
return command; return command;
} }
public GuildManager getGuildManager() {
return GuildManager.getManager(guild);
}
public void reply(CommandUsage usage) { public void reply(CommandUsage usage) {
reply(new MessageBuilder(usage.toString()).build()); reply(new MessageBuilder(usage.toString()).build());
} }
@@ -154,6 +169,15 @@ public class CommandContext {
this.command = command; this.command = command;
//TODO: Add usage check //TODO: Add usage check
Sentry.configureScope(scope -> {
scope.setContexts("command", command.getCommandName());
scope.setContexts("isAdmin", UserFunction.isAdmin(member));
scope.setContexts("canBeExecuted", command.canBeExecutedBy(guild, member));
scope.setTag("channel", channel.getId());
scope.setTag("message", message.getId());
scope.setTag("guild", guild.getId());
});
try { try {
if (command.needAdmin()) { if (command.needAdmin()) {
if (!UserFunction.isAdmin(member)) { if (!UserFunction.isAdmin(member)) {
@@ -7,27 +7,25 @@ package netneutrality.db;
* https://discord.gg/CdFcyQ * https://discord.gg/CdFcyQ
*/ */
import netneutrality.core.SessionManager;
import org.hibernate.SessionFactory;
public abstract class AbstractController { public abstract class AbstractController {
protected MysqlDatabase database; protected SessionFactory sessionFactory;
/** /**
* The controller name to be used in {@link DBController#get(String controller)} method * The controller name to be used in {@link DBController#get(String controller, Class returnType)} method
* *
* @return String * @return String
*/ */
public abstract String getControllerName(); public abstract String getControllerName();
/** public AbstractController() {
* Returns an instance of {@link MysqlDatabase} with the database name as set in the {@link DBController} class sessionFactory = SessionManager.getSessionFactory();
*
* @return {@link MysqlDatabase}
*/
protected MysqlDatabase getDatabase() {
return database;
} }
protected void setDatabase(MysqlDatabase database) { protected SessionFactory getSessionFactory() {
this.database = database; return sessionFactory;
} }
} }
@@ -1,66 +0,0 @@
package netneutrality.db;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import netneutrality.ThreadManager;
import netneutrality.db.models.MTableModel;
import java.sql.ResultSet;
import java.util.concurrent.*;
import java.util.function.Consumer;
public class AsyncMySqlAction {
private final ExecutorService executor = ThreadManager.getExecutor("db-action", ThreadManager.ExecutorType.SINGLE);
private final String sqlString;
private final Object[] params;
private final MysqlDatabase.CommandType type;
private final MysqlDatabase db;
public final String tableName;
public AsyncMySqlAction(MysqlDatabase db, String sql, Object... params) {
this.db = db;
this.sqlString = sql;
this.params = params;
this.tableName = sqlString.toUpperCase().split(" ")[1];
type = MysqlDatabase.CommandType.stringToType(sqlString.toUpperCase().split(" ")[0]);
}
public void async() {
async( success -> {} );
}
public void async(Consumer<MTableModel> success) {
switch (type) {
case INSERT -> executor.submit(() -> success.accept(new MTableModel(db.insert(this.sqlString, this.params))));
case UPDATE -> executor.submit(() -> success.accept(new MTableModel(db.update(this.sqlString, this.params))));
case DELETE -> executor.submit(() -> success.accept(new MTableModel(db.delete(this.sqlString, this.params))));
case SELECT -> executor.submit(() -> {
ResultSet result = db.prepareAndExecute(this.sqlString, this.params);
success.accept(MysqlDatabase.convertToTableModel(result, tableName));
});
}
}
public MTableModel blocking() {
MTableModel table;
table = switch (type) {
case INSERT -> new MTableModel(db.insert(this.sqlString, this.params));
case UPDATE -> new MTableModel(db.update(this.sqlString, this.params));
case DELETE -> new MTableModel(db.delete(this.sqlString, this.params));
case SELECT -> db.prepareAndExecute(this.sqlString, this.tableName, this.params);
};
return table;
}
}
@@ -7,20 +7,17 @@ package netneutrality.db;
* https://discord.gg/CdFcyQ * https://discord.gg/CdFcyQ
*/ */
import java.lang.reflect.InvocationTargetException; import netneutrality.core.SessionManager;
import java.lang.reflect.Modifier; import netneutrality.thread.ThreadManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import netneutrality.ThreadManager;
import netneutrality.utils.Settings;
import org.reflections.Reflections; import org.reflections.Reflections;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Set;
/** /**
* When creating a controller, all database actions must be executed in another thread using an executor. One is provided in the {@link ThreadManager} class * When creating a controller, all database actions must be executed in another thread using an executor. One is provided in the {@link ThreadManager} class
* A simple thread can't be used in this case because overlapping actions might happen and won't be executed. * A simple thread can't be used in this case because overlapping actions might happen and won't be executed.
@@ -31,59 +28,43 @@ public class DBController {
* A map that contains all the controllers currently loaded * A map that contains all the controllers currently loaded
*/ */
private final static HashMap<String, AbstractController> controllers = new HashMap<>(); private final static HashMap<String, AbstractController> controllers = new HashMap<>();
private final static Logger logger = LoggerFactory.getLogger(DBController.class); private final static Logger logger = LoggerFactory.getLogger(DBController.class);
private static final MysqlDatabase database = new MysqlDatabase(Settings.getInstance().get("MYSQL_DATABASE", "netneutrality"));
/** /**
* @param controller The name of the controller as defined in the {@link AbstractController#getControllerName()}'s method * @param controller The name of the controller as defined in the {@link AbstractController#getControllerName()}'s method
* @return {@link AbstractController} The class with an AbstractController type * @return {@link AbstractController} The class with an AbstractController type
*/ */
public static AbstractController get(String controller) { @SuppressWarnings("unchecked")
public static <T> T get(String controller, Class<T> returnType) {
if (returnType == null)
throw new IllegalArgumentException("return type is null");
if (controllers.isEmpty()) if (controllers.isEmpty())
init(); init();
if (database.isClosed())
database.reconnect();
if (controllers.containsKey(controller)) { if (controllers.containsKey(controller)) {
return controllers.get(controller); return (T) controllers.get(controller);
} } else
throw new RuntimeException("Error getting database controller");
return null;
}
public static MysqlDatabase get() {
if (database.isClosed()) {
logger.info("Reconnecting to database..");
database.reconnect();
}
return database;
} }
public static void shutdown() { public static void shutdown() {
try { SessionManager.shutdown();
database.close();
} catch (SQLException | NullPointerException ignored) { }
} }
/** /**
* Optional, will be called if the method {@link #get(String) get()} is used * Optional, will be called if the method {@link #get(String, Class) get()} is used
*/ */
public static void init() { public static void init() {
if (controllers.isEmpty()) if (controllers.isEmpty())
loadControllers(); loadControllers();
((ScheduledExecutorService) ThreadManager.getExecutor("db-keepalive", ThreadManager.ExecutorType.SCHEDULED))
.scheduleWithFixedDelay(() -> DBController.get().query("SELECT 1;"), 0, 120, TimeUnit.SECONDS);
} }
/** /**
* Loads all the controllers which extends {@link AbstractController} * Loads all the controllers which extends {@link AbstractController}
*/ */
private static void loadControllers() { private static void loadControllers() {
//TODO: to delete
logger.info("Loading databases controllers.."); logger.info("Loading databases controllers..");
Reflections reflections = new Reflections("netneutrality.db.controllers"); Reflections reflections = new Reflections("netneutrality.db.controllers");
@@ -96,7 +77,6 @@ public class DBController {
} }
AbstractController c = s.getConstructor().newInstance(); AbstractController c = s.getConstructor().newInstance();
c.setDatabase(database);
if (!controllers.containsKey(c.getControllerName())) { if (!controllers.containsKey(c.getControllerName())) {
controllers.put(c.getControllerName(), c); controllers.put(c.getControllerName(), c);
@@ -1,58 +0,0 @@
package netneutrality.db;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import com.mysql.cj.jdbc.MysqlDataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class MysqlConnector {
private final String dbName;
private final String dbUser;
private final String dbHost;
private final String dbPass;
private Connection c;
MysqlConnector(String dbName, String dbUser, String dbHost, String dbPass) {
this.dbName = dbName;
this.dbUser = dbUser;
this.dbHost = dbHost;
this.dbPass = dbPass;
}
/**
* Connect to a MySQL instance using the provided information
*
* @return {@link MysqlConnector}
*/
public MysqlConnector connect() throws SQLException {
MysqlDataSource dataSource = new MysqlDataSource();
String jdbc = "jdbc:mysql://" + dbHost + ":3306/" + dbName;
dataSource.setURL(jdbc);
dataSource.setUser(dbUser);
dataSource.setPassword(dbPass);
dataSource.setAutoReconnect(true);
dataSource.setConnectTimeout(5000);
c = dataSource.getConnection();
return this;
}
/**
* Get the MySQL connection. Must call {@link #connect()} beforehand.
*
* @return {@link Connection}
*/
public Connection getConnection() {
return c;
}
}
@@ -1,293 +0,0 @@
package netneutrality.db;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.Calendar;
import netneutrality.db.models.MRowModel;
import netneutrality.db.models.MTableModel;
import netneutrality.exceptions.UnimplementedParameterException;
import netneutrality.handler.LogHandler;
import netneutrality.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MysqlDatabase {
private final static Logger logger = LoggerFactory.getLogger(MysqlDatabase.class);
private final static Object dmlLock = new Object();
protected Connection connection;
private final String dbName;
protected enum CommandType {
SELECT("SELECT"), INSERT("INSERT"), UPDATE("UPDATE"), DELETE("DELETE");
private final String type;
CommandType(String type) {
this.type = type;
}
public static CommandType stringToType(String str) {
return CommandType.valueOf(str);
}
public String getType() {
return type;
}
}
protected MysqlDatabase(String dbName) {
this.dbName = dbName;
String dbUser = Settings.getInstance().get("MYSQL_USER", "root");
String dbPass = Settings.getInstance().get("MYSQL_PASSWORD", "");
String dbHost = Settings.getInstance().get("MYSQL_HOST", "localhost");
try {
logger.info(String.format("Connecting to database '%1$s' at %2$s:3306 with user '%3$s'", dbName, dbHost, dbUser));
connection = new MysqlConnector(dbName, dbUser, dbHost, dbPass).connect().getConnection();
} catch (SQLException e) {
logger.error("Error connecting to database. Shutting down..", e);
System.exit(-1);
}
}
/**
* Execute a simple query without any parameters.
* Example : SELECT * FROM table
*
* @param query The SQL query to execute
* @return {@link ResultSet}
*/
protected ResultSet query(String query) {
Statement stmt;
try {
stmt = connection.createStatement();
return stmt.executeQuery(query);
} catch (SQLException e) {
LogHandler.log(e);
}
return null;
}
/**
* Execute an UPDATE statement with the specified parameters.
* In the SQL query, where there is a parameter to be included, you need to replace it with ?
*
* @param sql The SQL query to execute
* @param params The parameters to include in the query
*/
protected int update(String sql, Object... params) {
return executeUpdate(sql, params);
}
/**
* Execute an INSERT statement with the specified parameters.
* In the SQL query, where there is a parameter to be included, you need to replace it with ?
*
* @param sql The SQL query to execute
* @param params The parameters to include in the query
* @return an integer of how many row were affected
*/
protected int insert(String sql, Object... params) {
return executeUpdate(sql, params);
}
/**
* Execute a DELETE statement with the specified parameters.
* In the SQL query, where there is a parameter to be included, you need to replace it with ?
*
* @param sql The SQL query to execute
* @param params The parameters to include in the query
* @return an integer of how many row were affected
*/
protected int delete(String sql, Object... params) {
return executeUpdate(sql, params);
}
private int executeUpdate(String sql, Object[] params) {
logger.debug("Query: " + sql);
synchronized (dmlLock) {
try {
PreparedStatement query = connection.prepareStatement(sql);
resolveParameters(query, params);
return query.executeUpdate();
} catch (SQLException e) {
LogHandler.log(e);
}
return -1;
}
}
public boolean exists(String table, String key, String value) {
return !prepareAndExecuteAsync(String.format("SELECT 1 FROM %s WHERE %s = ?", table, key), value).blocking().isEmpty();
}
/**
* Execute a SELECT statement with the specified parameters.
* In the SQL query, where there is a parameter to be included, you need to replace it with ?
*
* @param sql The SQL query to execute
* @param params The parameters to include in the query
* @return a ResultSet object, which can be converted to a model using {@link MysqlDatabase#convertToTableModel(ResultSet, String)}
*/
protected ResultSet prepareAndExecute(String sql, Object... params) {
try {
PreparedStatement query = connection.prepareStatement(sql);
resolveParameters(query, params);
return query.executeQuery();
} catch (SQLException e) {
logger.error(e.getMessage(), e);
}
return null;
}
protected MTableModel prepareAndExecute(String sql, String tableName, Object... params) {
try {
PreparedStatement query = connection.prepareStatement(sql);
resolveParameters(query, params);
return convertToTableModel(query.executeQuery(), tableName);
} catch (SQLException e) {
logger.error(e.getMessage(), e);
}
return null;
}
/**
* Execute a SELECT statement with the specified parameters.
* In the SQL query, where there is a parameter to be included, you need to replace it with ?
*
* @param sql The SQL query to execute
* @param params The parameters to include in the query
* @return a ResultSet object, which can be converted to a model using {@link MysqlDatabase#convertToTableModel(ResultSet, String)}
*/
public AsyncMySqlAction prepareAndExecuteAsync(String sql, Object... params) {
return new AsyncMySqlAction(this, sql, params);
}
/**
* Insert parameters (specified with a ?) in the SQL statement
* Taken from https://github.com/Kaaz/DiscordBot/blob/master/src/main/java/emily/db/MySQLAdapter.java#resolveParameters
*
* @param query The PreparedStatement object
* @param params The parameters to be included in the prepared statement
*/
private void resolveParameters(PreparedStatement query, Object... params) throws SQLException {
int index = 1;
for (Object p : params) {
if (p instanceof String) {
query.setString(index, (String) p);
} else if (p instanceof Integer) {
query.setInt(index, (int) p);
} else if (p instanceof Boolean) {
query.setBoolean(index, (Boolean) p);
} else if (p instanceof Long) {
query.setLong(index, (Long) p);
} else if (p instanceof Double) {
query.setDouble(index, (double) p);
} else if (p instanceof java.sql.Date date) {
query.setDate(index, date);
} else if (p instanceof java.util.Date date) {
Timestamp ts = new Timestamp(date.getTime());
query.setTimestamp(index, ts);
} else if (p instanceof Calendar cal) {
Timestamp ts = new Timestamp(cal.getTimeInMillis());
query.setTimestamp(index, ts);
} else if (p == null) {
query.setNull(index, Types.NULL);
} else {
throw new UnimplementedParameterException(p, index);
}
index++;
}
}
/**
* Close the MySQL connection
*/
public void close() throws SQLException {
System.out.println("Closing database...");
connection.close();
}
/**
* Recreate and reconnect the MySQL connection.
*/
public void reconnect() {
String dbUser = Settings.getInstance().get("MYSQL_USER", "root");
String dbPass = Settings.getInstance().get("MYSQL_PASSWORD", "");
String dbHost = Settings.getInstance().get("MYSQL_HOST", "localhost");
try {
logger.info("Reconnecting to database...");
connection = new MysqlConnector(dbName, dbUser, dbHost, dbPass).connect().getConnection();
} catch (SQLException e) {
logger.error("Error connecting to database. Shutting down..");
System.exit(0);
}
}
/**
* Check if the database is closed.
*
* @return the connection status
*/
public boolean isClosed() {
try {
return connection.isClosed();
} catch (SQLException e) {
return true;
}
}
/**
* @param rs The ResultSet returned by the SELECT query
* @return a {@link MTableModel} with the appropriate column and rows
*/
protected static MTableModel convertToTableModel(ResultSet rs, String tableName) {
MTableModel table = new MTableModel(tableName);
try {
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 1; i < metadata.getColumnCount() + 1; i++) {
table.addColumn(metadata.getColumnName(i));
}
while (rs.next()) {
MRowModel row = new MRowModel(rs.getRow() - 1);
for (int i = 0; i < metadata.getColumnCount(); i++) {
row.addColumnToRow(rs.getObject(i + 1));
}
table.addRow(row);
}
} catch (SQLException e) {
e.printStackTrace();
}
return table;
}
}
@@ -1,5 +1,4 @@
package netneutrality.db.controllers; package netneutrality.db.controllers;
/* /*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
@@ -7,73 +6,127 @@ package netneutrality.db.controllers;
* https://discord.gg/CdFcyQ * https://discord.gg/CdFcyQ
*/ */
import java.util.ArrayList; import netneutrality.core.GuildManager;
import netneutrality.core.context.CommandContext;
import netneutrality.db.AbstractController; import netneutrality.db.AbstractController;
import netneutrality.db.models.MBlacklist; import netneutrality.db.entities.OBlacklist;
import netneutrality.db.models.MTableModel; import netneutrality.db.entities.OGuild;
import org.slf4j.Logger; import netneutrality.utils.JpaUtils;
import org.slf4j.LoggerFactory; import org.hibernate.Session;
import org.hibernate.query.Query;
import java.util.ArrayList;
public class DBBlacklist extends AbstractController { public class DBBlacklist extends AbstractController {
private final Logger logger = LoggerFactory.getLogger(DBBlacklist.class); public void add(String word, CommandContext context) {
GuildManager guildManager = GuildManager.getManager(context.getGuild());
Session session = getSessionFactory().openSession();
public boolean add(MBlacklist obj) { OBlacklist bl = getWordFromDb(word, context.getGuild().getId());
if (!isAlreadyBlacklisted(obj.getWord(), obj.getServerId())) {
return database.prepareAndExecuteAsync("INSERT INTO blacklist VALUES(?,?,?,?)", obj.getServerId(), obj.getWord(), obj.isEnabled(), obj.getCreatorId()).blocking().isSuccess(); if (bl == null) {
session.beginTransaction();
bl = new OBlacklist();
bl.setGuild(guildManager.getGuildEntity());
bl.setCreatorId(context.getGuildUser().getId());
bl.setWord(word);
bl.setEnabled(true);
session.save(bl);
session.getTransaction().commit();
guildManager.reloadBlacklistCache(false);
context.reply(String.format("Added the word [%s] to the blacklist.", word));
} else {
context.reply("Word is already blacklisted");
} }
return false; session.close();
} }
public boolean delete(String word, String serverId) { public void delete(String word, CommandContext context) {
if (isAlreadyBlacklisted(word, serverId)) { GuildManager guildManager = GuildManager.getManager(context.getGuild());
return database.prepareAndExecuteAsync("DELETE FROM blacklist WHERE word = ? AND guild_id = ?", word, serverId).blocking().isSuccess(); Session session = getSessionFactory().openSession();
OBlacklist bl = getWordFromDb(word, context.getGuild().getId());
if (bl != null) {
session.beginTransaction();
session.delete(bl);
session.getTransaction().commit();
guildManager.reloadBlacklistCache(false);
context.reply("Removed the word [%s] from the blacklist.", word);
} else {
context.reply("Can't delete word because it doesn't exist");
} }
return false; session.close();
} }
public boolean enable(String word, String serverId) { public void enable(String word, CommandContext context) {
if (isAlreadyBlacklisted(word, serverId)) { GuildManager guildManager = GuildManager.getManager(context.getGuild());
return database.prepareAndExecuteAsync("UPDATE blacklist SET enabled = 1 WHERE word = ? AND guild_id = ?", word, serverId).blocking().isSuccess(); Session session = getSessionFactory().openSession();
OBlacklist bl = getWordFromDb(word, context.getGuild().getId());
if (bl != null && !bl.getEnabled()) {
session.beginTransaction();
bl.setEnabled(true);
session.update(bl);
session.getTransaction().commit();
guildManager.reloadBlacklistCache(false);
context.reply("Enabled the word [%s] for the blacklist.", word);
} else {
context.reply("Either word doesn't exist or is already enabled");
} }
return false; session.close();
} }
public boolean disable(String word, String serverId) { public void disable(String word, CommandContext context) {
if (isAlreadyBlacklisted(word, serverId)) { GuildManager guildManager = GuildManager.getManager(context.getGuild());
return database.prepareAndExecuteAsync("UPDATE blacklist SET enabled = 0 WHERE word = ? AND guild_id = ?", word, serverId).blocking().isSuccess(); Session session = getSessionFactory().openSession();
OBlacklist bl = getWordFromDb(word, context.getGuild().getId());
if (bl != null && bl.getEnabled()) {
session.beginTransaction();
bl.setEnabled(false);
session.update(bl);
session.getTransaction().commit();
guildManager.reloadBlacklistCache(false);
context.reply("Disabled the word [%s] for the blacklist.", word);
} else {
context.reply("Either word doesn't exist or is already disabled");
} }
return false; session.close();
} }
public ArrayList<MBlacklist> getBlacklistFromServer(String serverId) { public ArrayList<OBlacklist> getBlacklistForGuild(CommandContext context) {
GuildManager guildManager = GuildManager.getManager(context.getGuild());
Session session = getSessionFactory().openSession();
MTableModel model = database.prepareAndExecuteAsync("SELECT * FROM blacklist WHERE guild_id = ? AND enabled = 1", serverId).blocking(); OGuild guildEntity = guildManager.getGuildEntity();
ArrayList<MBlacklist> output = new ArrayList<>(); JpaUtils.tryLoad(session, guildEntity, guildEntity.getGuildId());
if (model.getNbRows() > 0) { ArrayList<OBlacklist> blacklists = new ArrayList<>(guildEntity.getBlacklists());
session.close();
for (int row = 0; row < model.getNbRows(); row++) { return blacklists;
MBlacklist bl = new MBlacklist(model.getRow(row));
output.add(bl);
}
}
return output;
} }
private boolean isAlreadyBlacklisted(String word, String serverId) { private OBlacklist getWordFromDb(String word, String guildId) {
MTableModel table = database.prepareAndExecuteAsync("SELECT COUNT(*) FROM blacklist WHERE word = ? AND guild_id = ?", word, serverId).blocking(); Session session = getSessionFactory().openSession();
if (!table.isEmpty()) {
return ((int) table.getRowModel(0).getItem(0)) != 0;
}
return false; Query<OBlacklist> query = session.createNamedQuery("OBlacklist.findByWordEqualsIgnoreCaseAndGuild_GuildIdEquals", OBlacklist.class);
query.setParameter("guildId", guildId);
query.setParameter("word", word);
OBlacklist blacklist = query.uniqueResult();
session.close();
return blacklist;
} }
@Override @Override
@@ -1,31 +0,0 @@
package netneutrality.db.controllers;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import net.dv8tion.jda.api.entities.Guild;
import netneutrality.db.AbstractController;
public class DBGuild extends AbstractController {
public void insertGuildInDB(Guild g) {
if (!database.exists("guilds", "guild_id", g.getId())) {
database.prepareAndExecuteAsync("INSERT INTO guilds VALUES(?, ?, ?, ?)", g.getId(), "0", null, null).blocking();
}
}
public void removeGuildInDB(Guild g) {
if (database.exists("guilds", "guild_id", g.getId())) {
database.prepareAndExecuteAsync("DELETE FROM guilds WHERE guild_id = ?", g.getId()).blocking();
}
}
@Override
public String getControllerName() {
return "guild";
}
}
@@ -1,33 +0,0 @@
package netneutrality.db.controllers;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import netneutrality.db.AbstractController;
import netneutrality.db.models.MTableModel;
public class DBLogging extends AbstractController {
public void setupLog(String serverId, String channelId) {
database.prepareAndExecuteAsync("INSERT INTO logging VALUES(?,?,?)", serverId, channelId, true).blocking();
}
public void toggleLog(String serverId, String channelId) {
database.prepareAndExecuteAsync("UPDATE logging SET enabled = NOT enabled WHERE guild_id = ? AND channelId = ?", serverId, channelId).blocking();
}
public boolean isLoggingEnabled(String serverId, String channelId) {
MTableModel table = database.prepareAndExecuteAsync("SELECT enabled FROM logging WHERE guild_id = ? AND channelId = ?", serverId, channelId).blocking();
return (Boolean) table.getRow(0).get(0);
}
@Override
public String getControllerName() {
return "logging";
}
}
@@ -7,74 +7,94 @@ package netneutrality.db.controllers;
* https://discord.gg/CdFcyQ * https://discord.gg/CdFcyQ
*/ */
import java.util.ArrayList; import net.dv8tion.jda.api.entities.Member;
import java.util.Date; import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.entities.*; import netneutrality.core.GuildManager;
import netneutrality.db.AbstractController; import netneutrality.db.AbstractController;
import netneutrality.db.DBController; import netneutrality.db.entities.OLogMessage;
import netneutrality.db.MysqlDatabase; import org.hibernate.Session;
import netneutrality.db.models.MMessage; import org.hibernate.query.Query;
import netneutrality.db.models.MTableModel;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.List;
public class DBMessage extends AbstractController { public class DBMessage extends AbstractController {
private final static Logger logger = LoggerFactory.getLogger(DBMessage.class); private final static Logger logger = LoggerFactory.getLogger(DBMessage.class);
/** public void log(GuildManager guildManager, TextChannel channel, Member author, Message message) {
* Returns an instance of {@link MysqlDatabase} with the database name as set in the {@link DBController} class Session session = getSessionFactory().openSession();
* session.beginTransaction();
* @return {@link MysqlDatabase}
*/
public MysqlDatabase getDatabase() {
return database;
}
public void log(Guild guild, TextChannel channel, Member author, Message message) { OLogMessage logMessage = new OLogMessage();
String guildId = guild.getId(); logMessage.setGuild(guildManager.getGuildEntity());
String channelId = channel.getId(); logMessage.setMessageId(message.getId());
String authorId = author.getId(); logMessage.setMessage(message.getContentRaw().trim());
Date dateSent = new Date(message.getTimeCreated().toInstant().toEpochMilli()); logMessage.setChannelId(channel.getId());
String messageId = message.getId(); logMessage.setUserId(author.getId());
String msg = message.getContentRaw().trim(); logMessage.setDateSent(message.getTimeCreated().toInstant());
database.prepareAndExecuteAsync("INSERT INTO log_message VALUES(?,?,?,?,?,?,?)", guildId, channelId, authorId, dateSent, messageId, msg, null).blocking(); session.save(logMessage);
session.getTransaction().commit();
session.close();
} }
public void logEdit(String messageId, String newMessage) { public void logEdit(String messageId, String newMessage) {
database.prepareAndExecuteAsync("UPDATE log_message SET edited_message = ? WHERE message_id = ?", newMessage, messageId).blocking(); Session session = getSessionFactory().openSession();
Query<OLogMessage> query = session.createNamedQuery("OLogMessage.findByMessageIdEquals", OLogMessage.class);
query.setParameter("messageId", messageId);
} OLogMessage message = query.uniqueResult();
if (message != null) {
session.beginTransaction();
message.setEditedMessage(newMessage);
public MMessage getMessage(String messageId) { session.update(message);
MTableModel table = database.prepareAndExecuteAsync("SELECT * FROM log_message WHERE message_id = ?", messageId).blocking(); session.getTransaction().commit();
if (table.getNbRows() > 0) {
return new MMessage(table.getRowModel(0));
} }
return null; session.close();
} }
public ArrayList<MMessage> getMessagesFromUser(String username, String serverName, int max) { public OLogMessage getMessage(String messageId) {
ArrayList<MMessage> messages = new ArrayList<>(); Session session = getSessionFactory().openSession();
Query<OLogMessage> query = session.createNamedQuery("OLogMessage.findByMessageIdEquals", OLogMessage.class);
query.setParameter("messageId", messageId);
MTableModel table = database.prepareAndExecuteAsync("SELECT * FROM log_message WHERE user_id = ? AND guild_id = ? ORDER BY date_sent DESC LIMIT ?", username, serverName, max).blocking(); OLogMessage message = query.uniqueResult();
if (table.getNbRows() > 0) { session.close();
for (int row = 0; row < max; row++) {
messages.add(new MMessage(table.getRowModel(row))); return message;
} }
}
public List<OLogMessage> getMessagesFromUser(String userId, String guildId, int max) {
Session session = getSessionFactory().openSession();
Query<OLogMessage> query = session.createNamedQuery("OLogMessage.findByUserIdEquals", OLogMessage.class);
query.setParameter("guildId", guildId);
query.setParameter("userId", userId);
query.setMaxResults(max);
List<OLogMessage> messages = query.getResultList();
session.close();
return messages; return messages;
} }
public String getMessageString(String messageId) { public String getMessageString(String messageId) {
MTableModel table = database.prepareAndExecuteAsync("SELECT message FROM log_message WHERE message_id = ?", messageId).blocking(); Session session = getSessionFactory().openSession();
Query<OLogMessage> query = session.createNamedQuery("OLogMessage.findByMessageIdEquals", OLogMessage.class);
query.setParameter("messageId", messageId);
OLogMessage message = query.uniqueResult();
session.close();
if (message == null)
return null;
else
return message.getMessage();
return (String) table.getRowModel(0).getItem(0);
} }
@@ -1,54 +0,0 @@
package netneutrality.db.entities;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import netneutrality.db.DBController;
import netneutrality.db.models.MTableModel;
import netneutrality.handler.LogHandler;
public abstract class AbstractEntity implements EntityInterface {
private final String primaryKey;
private final String[] primaryKeys;
protected MTableModel table;
public AbstractEntity(String primaryKey, String... primaryKeys) throws ArrayIndexOutOfBoundsException {
this.primaryKey = primaryKey;
this.primaryKeys = primaryKeys;
fillTableModel();
try {
if (!table.isEmpty())
convertFromTableModel(table);
} catch (NullPointerException e) {
LogHandler.log("Table structure does not match expected variables", e);
}
}
private void fillTableModel() throws ArrayIndexOutOfBoundsException {
StringBuilder whereClause = new StringBuilder();
for (String pk : getPrimaryKeys()) {
whereClause.append(pk).append(" = ?");
//TODO: Fix last and
if (getPrimaryKeys().length > 1)
whereClause.append(" AND ");
}
String sql = "SELECT * FROM " + getTableName() + " WHERE " + whereClause;
// MusicBot.logger.debug(sql + " - pk: " + primaryKey);
if (this.primaryKeys.length > 0)
this.table = DBController.get().prepareAndExecuteAsync(sql, this.primaryKey, this.primaryKeys).blocking();
else
this.table = DBController.get().prepareAndExecuteAsync(sql, this.primaryKey).blocking();
}
}
@@ -1,21 +0,0 @@
package netneutrality.db.entities;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import netneutrality.db.models.MTableModel;
public interface EntityInterface {
String getTableName();
String[] getPrimaryKeys();
boolean exists();
void convertFromTableModel(MTableModel table);
}
@@ -0,0 +1,75 @@
package netneutrality.db.entities;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import javax.persistence.*;
@Entity
@Table(name = "blacklist")
@NamedQueries({
@NamedQuery(name = "OBlacklist.findByWordEqualsIgnoreCaseAndGuild_GuildIdEquals", query = "select o from OBlacklist o where upper(o.word) = upper(:word) and o.guild.guildId = :guildId")
})
public class OBlacklist {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Integer id;
@Column(name = "word", nullable = false)
private String word;
@Column(name = "enabled", nullable = false)
private Boolean enabled = false;
@Column(name = "creator_id", nullable = false)
private String creatorId;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "guild_id", nullable = false)
private OGuild guild;
public OGuild getGuild() {
return guild;
}
public void setGuild(OGuild guild) {
this.guild = guild;
}
public String getCreatorId() {
return creatorId;
}
public void setCreatorId(String creatorId) {
this.creatorId = creatorId;
}
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
@@ -7,72 +7,112 @@ package netneutrality.db.entities;
* https://discord.gg/CdFcyQ * https://discord.gg/CdFcyQ
*/ */
import javax.persistence.*;
import java.util.LinkedHashSet;
import java.util.Optional;
import java.util.Set;
import netneutrality.GuildManager; @Entity
import netneutrality.db.models.MTableModel; @Table(name = "guilds")
public class OGuild {
public class OGuild extends AbstractEntity { @Id
@Column(name = "guild_id", nullable = false)
private String guildId;
private String guildID; @Column(name = "logging", nullable = false)
private boolean logging; private Boolean logging = false;
private boolean debug;
private String logchannel;
private OGuildSetting settings; @Column(name = "debug", nullable = false)
private Boolean debug = true;
public OGuild(String guildId) { @Column(name = "log_channel")
super(guildId); private String logChannel;
this.settings = new OGuildSetting(this); @OneToMany(mappedBy = "guild")
private Set<OGuildSetting> guildSettings = new LinkedHashSet<>();
@OneToMany(mappedBy = "guild")
private Set<OBlacklist> blacklists = new LinkedHashSet<>();
@OneToMany(mappedBy = "guild")
private Set<OLogMessage> logMessages = new LinkedHashSet<>();
@OneToMany(mappedBy = "guild")
private Set<OLogging> OLoggings = new LinkedHashSet<>();
public Set<OLogging> getLoggings() {
return OLoggings;
} }
public boolean isLogging() { public void setLoggings(Set<OLogging> OLoggings) {
this.OLoggings = OLoggings;
}
public Set<OLogMessage> getLogMessages() {
return logMessages;
}
public void setLogMessages(Set<OLogMessage> logMessages) {
this.logMessages = logMessages;
}
public Set<OBlacklist> getBlacklists() {
return blacklists;
}
public void setBlacklists(Set<OBlacklist> blacklists) {
this.blacklists = blacklists;
}
public Set<OGuildSetting> getGuildSettings() {
return guildSettings;
}
public void setGuildSettings(Set<OGuildSetting> guildSettings) {
this.guildSettings = guildSettings;
}
public String getLogChannel() {
return logChannel;
}
public void setLogChannel(String logChannel) {
this.logChannel = logChannel;
}
public Boolean getLogging() {
return logging; return logging;
} }
public boolean isDebug() { public void setLogging(Boolean logging) {
this.logging = logging;
}
public Boolean getDebug() {
return debug; return debug;
} }
public String getLogchannel() { public void setDebug(Boolean debug) {
return logchannel; this.debug = debug;
}
public void reloadSettings() {
GuildManager.logger.debug("Reloading settings for guild: " + guildID);
this.settings = new OGuildSetting(this);
}
public String getGuildID() {
return guildID;
}
public OGuildSetting getSettings() {
return settings;
}
@Override
public boolean exists() {
return guildID != null;
}
@Override
public String getTableName() {
return "guilds";
}
@Override
public String[] getPrimaryKeys() {
return new String[] {"guild_id"};
} }
@Override public String getGuildId() {
public void convertFromTableModel(MTableModel table) { return guildId;
this.guildID = (String) table.getRow(0).get(0);
this.logging = ((Integer) table.getRow(0).get(1)) == 1;
this.debug = ((Boolean) table.getRow(0).get(2));
this.logchannel = (String) table.getRow(0).get(3);
} }
public void setGuildId(String guildId) {
this.guildId = guildId;
}
public OGuildSetting getSettingByName(String name) {
Optional<OGuildSetting> setting = getGuildSettings()
.stream()
.filter(setting1 -> setting1.getName().equalsIgnoreCase(name))
.findFirst();
return setting.orElse(null);
}
} }
@@ -1,73 +1,65 @@
package netneutrality.db.entities;/* package netneutrality.db.entities;
/*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
* https://xtremcommunity.com/ * https://xtremcommunity.com/
* https://discord.gg/CdFcyQ * https://discord.gg/CdFcyQ
*/ */
import netneutrality.GuildManager; import javax.persistence.*;
import netneutrality.db.models.MRowModel;
import netneutrality.db.models.MTableModel;
import java.util.*; @Entity
@Table(name = "guild_settings")
@NamedQueries({
@NamedQuery(name = "settings_findByName", query = "select o from OGuildSetting o where o.guild.id = :id and upper(o.name) = upper(:name)")
})
public class OGuildSetting {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Integer id;
public class OGuildSetting extends AbstractEntity { @Column(name = "name", nullable = false)
private final OGuild guild; private String name;
private Map<String, Object> settings;
public OGuildSetting(OGuild OGuild) { @Lob
super(OGuild.getGuildID()); @Column(name = "value", nullable = false)
private String value;
this.guild = OGuild; @ManyToOne(fetch = FetchType.LAZY, optional = false)
} @JoinColumn(name = "guild_id", nullable = false)
private OGuild guild;
public OGuild getGuild() { public OGuild getGuild() {
return guild; return guild;
} }
public Map<String, Object> getSettings() { public void setGuild(OGuild guild) {
return settings; this.guild = guild;
} }
public Object getSettingByKey(GuildManager.GuildSetting key) { public String getValue() {
if (settings.containsKey(key.getName())) { return value;
return settings.get(key.getName());
}
return key.getDefaultValue();
} }
@Override public void setValue(String value) {
public String getTableName() { this.value = value;
return "guild_settings";
} }
@Override public String getName() {
public String[] getPrimaryKeys() { return name;
return new String[] {"guild_id"};
} }
@Override public void setName(String name) {
public boolean exists() { this.name = name;
return !settings.isEmpty();
} }
@Override public Integer getId() {
public void convertFromTableModel(MTableModel table) { return id;
settings = new HashMap<>(); }
List<String> columns = table.getColumns();
MRowModel row = table.getRowModel(0);
for (int i = 0; i < columns.size(); i++) {
if (i == 0) continue;
String key = columns.get(i).toUpperCase();
Object value = row.getItem(i);
settings.put(key, value);
}
public void setId(Integer id) {
this.id = id;
} }
} }
@@ -0,0 +1,111 @@
package netneutrality.db.entities;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import javax.persistence.*;
import java.time.Instant;
@Entity
@Table(name = "log_message")
@NamedQueries({
@NamedQuery(name = "OLogMessage.findByMessageIdEquals", query = "select o from OLogMessage o where o.messageId = :messageId"),
@NamedQuery(name = "OLogMessage.findByGuild_GuildIdEqualsAndUserIdEquals", query = "select o from OLogMessage o where o.guild.guildId = :guildId and o.userId = :userId")
})
public class OLogMessage {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Integer id;
@Column(name = "channel_id", nullable = false)
private String channelId;
@Column(name = "message_id", nullable = false)
private String messageId;
@Column(name = "user_id", nullable = false)
private String userId;
@Convert(disableConversion = true)
@Column(name = "date_sent", nullable = false)
private Instant dateSent;
@Column(name = "message", length = 2000)
private String message;
@Column(name = "edited_message", length = 2000)
private String editedMessage;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "guild_id", nullable = false)
private OGuild guild;
public OGuild getGuild() {
return guild;
}
public void setGuild(OGuild guild) {
this.guild = guild;
}
public String getEditedMessage() {
return editedMessage;
}
public void setEditedMessage(String editedMessage) {
this.editedMessage = editedMessage;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Instant getDateSent() {
return dateSent;
}
public void setDateSent(Instant dateSent) {
this.dateSent = dateSent;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getMessageId() {
return messageId;
}
public void setMessageId(String messageId) {
this.messageId = messageId;
}
public String getChannelId() {
return channelId;
}
public void setChannelId(String channelId) {
this.channelId = channelId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
@@ -0,0 +1,49 @@
package netneutrality.db.entities;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import javax.persistence.*;
@Entity
@Table(name = "logging")
public class OLogging {
@EmbeddedId
private OLoggingId id;
@MapsId("guildId")
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "guild_id", nullable = false)
private OGuild guild;
@Column(name = "enabled", nullable = false)
private Boolean enabled = false;
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public OGuild getGuild() {
return guild;
}
public void setGuild(OGuild guild) {
this.guild = guild;
}
public OLoggingId getId() {
return id;
}
public void setId(OLoggingId id) {
this.id = id;
}
}
@@ -0,0 +1,56 @@
package netneutrality.db.entities;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import org.hibernate.Hibernate;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import java.io.Serial;
import java.io.Serializable;
import java.util.Objects;
@Embeddable
public class OLoggingId implements Serializable {
@Serial
private static final long serialVersionUID = 8216581265618800768L;
@Column(name = "guild_id", nullable = false)
private String guildId;
@Column(name = "channel_id", nullable = false)
private String channelId;
public String getChannelId() {
return channelId;
}
public void setChannelId(String channelId) {
this.channelId = channelId;
}
public String getGuildId() {
return guildId;
}
public void setGuildId(String guildId) {
this.guildId = guildId;
}
@Override
public int hashCode() {
return Objects.hash(guildId, channelId);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
OLoggingId entity = (OLoggingId) o;
return Objects.equals(this.guildId, entity.guildId) &&
Objects.equals(this.channelId, entity.channelId);
}
}
@@ -1,66 +0,0 @@
package netneutrality.db.entities;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import netneutrality.command.CommandType;
import netneutrality.db.models.MTableModel;
public class OPermission extends AbstractEntity {
private final String guild_id;
private final String role_id;
public CommandType type;
public String command;
public OPermission(String guild_id, String role_id) {
super(guild_id, role_id);
this.guild_id = guild_id;
this.role_id = role_id;
}
@Override
public boolean exists() {
return guild_id != null && role_id != null;
}
public String getGuildId() {
return guild_id;
}
public String getRoleId() {
return role_id;
}
public CommandType getType() {
return type;
}
public String getCommand() {
return command;
}
@Override
public String getTableName() {
return "permissions";
}
@Override
public String[] getPrimaryKeys() {
return new String[] {"guild_id", "role_id"};
}
@Override
public void convertFromTableModel(MTableModel table) {
this.type = (CommandType) table.getRow(0).get(2);
this.command = (String) table.getRow(0).get(3);
}
}
@@ -1,4 +1,4 @@
package netneutrality.db.models; package netneutrality.db.entities;
/* /*
* Copyright (c) anthorob * Copyright (c) anthorob
@@ -7,7 +7,7 @@ package netneutrality.db.models;
* https://discord.gg/CdFcyQ * https://discord.gg/CdFcyQ
*/ */
public class MSellyOrder { public class OSellyOrder {
private final String id; private final String id;
private final String productId; private final String productId;
@@ -23,7 +23,7 @@ public class MSellyOrder {
private final float usdValue; private final float usdValue;
private final String createdAt; private final String createdAt;
public MSellyOrder(String id, String productId, String email, String ip, float value, String currency, String gateway, int risk, int status, int cryptoValue, String cryptoAddress, float usdValue, String createdAt) { public OSellyOrder(String id, String productId, String email, String ip, float value, String currency, String gateway, int risk, int status, int cryptoValue, String cryptoAddress, float usdValue, String createdAt) {
this.id = id; this.id = id;
this.productId = productId; this.productId = productId;
this.email = email; this.email = email;
@@ -1,59 +0,0 @@
package netneutrality.db.models;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import java.util.List;
public class MBlacklist {
private final String word;
private final boolean enabled;
private final String creatorId;
private final String serverId;
public MBlacklist(String word, boolean enabled, String creatorId, String serverId) {
this.word = word;
this.enabled = enabled;
this.creatorId = creatorId;
this.serverId = serverId;
}
public MBlacklist(List<Object> row) {
this.word = (String) row.get(1);
this.enabled = (Boolean) row.get(2);
this.creatorId = (String) row.get(3);
this.serverId = (String) row.get(0);
}
/**
* @return String The blacklisted word
*/
public String getWord() {
return word;
}
public boolean isEnabled() {
return enabled;
}
public String getCreatorId() {
return creatorId;
}
public String getServerId() {
return serverId;
}
@Override
public String toString() {
return "[word=" + word + ", enabled=" + enabled + "]";
}
}
@@ -1,66 +0,0 @@
package netneutrality.db.models;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
public class MMessage {
private final String serverId;
private final String channelName;
private final String sender;
private final String dateSent;
private final String messageId;
private final String message;
private final String editedMessage;
public MMessage(MRowModel row) {
this.serverId = (String) row.getItem(0);
this.channelName = (String) row.getItem(1);
this.sender = (String) row.getItem(2);
this.dateSent = (String) row.getItem(3);
this.messageId = (String) row.getItem(4);
this.message = (String) row.getItem(5);
this.editedMessage = "";
}
public String getServerId() {
return serverId;
}
public String getChannelName() {
return channelName;
}
public String getSender() {
return sender;
}
public String getDateSent() {
return dateSent;
}
public String getMessageId() {
return messageId;
}
public String getMessage() {
return message;
}
public String getEditedMessage() {
return editedMessage;
}
@Override
public String toString() {
return "MMessage [serverName=" + serverId + ", channelName=" + channelName + ", sender=" + sender
+ ", dateSent=" + dateSent + ", messageId=" + messageId + ", message=" + message + ", editedMessage="
+ editedMessage + "]";
}
}
@@ -1,80 +0,0 @@
package netneutrality.db.models;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MRowModel {
private final ArrayList<Object> row;
private int rowIndex;
public MRowModel() {
row = new ArrayList<>();
}
public MRowModel(Integer rowIndex) {
row = new ArrayList<>();
this.rowIndex = rowIndex;
}
public MRowModel(Object... objs) {
row = new ArrayList<>();
row.addAll(Arrays.asList(objs));
}
public int getRowIndex() {
return rowIndex;
}
/**
* Add an item to the row. No checks are made to match the table itself
* @param obj Object to add to the row
*/
public void addColumnToRow(Object obj) {
row.add(obj);
}
/**
* Get a list of all objects in the row.
* @return List of objects
*/
public List<Object> getRow() {
return row;
}
/**
* <pre>
* Get an item at the specified index.
*
* Example:
* SQL: SELECT first, second, third
* Index: 0 1 2
* </pre>
*
* @param index Index
* @return The object
*/
public Object getItem(int index) {
try {
return row.get(index);
} catch (Exception e) {
return null;
}
}
public int count() {
return row.size();
}
@Override
public String toString() {
return row.toString();
}
}
@@ -1,47 +0,0 @@
package netneutrality.db.models;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import java.util.ArrayList;
public class MRowsModel {
private final ArrayList<MRowModel> rows;
private String[] primaryKeys;
public MRowsModel() {
rows = new ArrayList<>();
}
public void addRow(MRowModel row) {
rows.add(row);
}
public MRowModel getRowModel(int index) {
if (!rows.isEmpty())
return rows.get(index);
return null;
}
public int size() {
return rows.size();
}
public void addColumnInRow(int index, Object obj) {
rows.get(index).addColumnToRow(obj);
}
public ArrayList<MRowModel> getRows() {
return rows;
}
@Override
public String toString() {
return rows.toString();
}
}
@@ -1,19 +0,0 @@
package netneutrality.db.models;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
public class MSellyProduct {
private String id;
private String title;
private String description;
private String stock;
private float price;
private String currency;
private boolean isPrivate;
}
@@ -1,118 +0,0 @@
package netneutrality.db.models;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class MTableModel {
private final boolean emptyResult;
private final boolean success;
private final String name;
private final List<String> column;
private final MRowsModel rows;
public MTableModel() {
this.emptyResult = true;
this.success = false;
this.name = null;
this.column = new LinkedList<>();
this.rows = new MRowsModel();
}
public MTableModel(int success) {
this.emptyResult = true;
this.success = success > 0;
this.name = null;
this.column = new LinkedList<>();
this.rows = new MRowsModel();
}
public MTableModel(String tableName) {
this.emptyResult = false;
this.success = true;
this.name = tableName;
this.column = new LinkedList<>();
this.rows = new MRowsModel();
}
public MTableModel(String... columns) {
this.emptyResult = false;
this.success = true;
this.name = null;
this.column = new LinkedList<>();
this.rows = new MRowsModel();
Collections.addAll(column, columns);
}
public boolean isEmptyResult() {
return emptyResult;
}
public boolean isSuccess() {
return success;
}
public String getName() {
return name;
}
public void addColumn(String name) {
column.add(name);
}
public void addRow(MRowModel row) {
rows.addRow(row);
}
public MRowsModel getRows() {
return rows;
}
public List<Object> getRow(int index) {
if (getNbRows() != 0)
return rows.getRowModel(index).getRow();
return null;
}
/**
* Represent a row in a table
*
* @param rowIndex The index of the row
* @return A row model
*/
public MRowModel getRowModel(int rowIndex) {
if (getNbRows() != 0)
return rows.getRowModel(rowIndex);
return new MRowModel();
}
public List<String> getColumns() {
return column;
}
public boolean isEmpty() {
return rows.getRows().isEmpty();
}
public int getNbRows() {
return rows.getRows().size();
}
@Override
public String toString() {
return "Column: " + column + ", Rows (" + getNbRows() + "): " + rows;
}
}
@@ -7,7 +7,7 @@ package netneutrality.exceptions;
* https://discord.gg/CdFcyQ * https://discord.gg/CdFcyQ
*/ */
import netneutrality.command.CommandContext; import netneutrality.core.context.CommandContext;
/** /**
* Used to reply with a message in the text channel where the command was executed * Used to reply with a message in the text channel where the command was executed
@@ -7,7 +7,7 @@ package netneutrality.exceptions;
* https://discord.gg/CdFcyQ * https://discord.gg/CdFcyQ
*/ */
import netneutrality.command.CommandContext; import netneutrality.core.context.CommandContext;
public abstract class CommandException extends RuntimeException { public abstract class CommandException extends RuntimeException {
@@ -7,7 +7,7 @@ package netneutrality.exceptions;
* https://discord.gg/CdFcyQ * https://discord.gg/CdFcyQ
*/ */
import netneutrality.command.CommandContext; import netneutrality.core.context.CommandContext;
/** /**
* Logs the error internally, without sending a message * Logs the error internally, without sending a message
@@ -7,7 +7,7 @@ package netneutrality.exceptions;
* https://discord.gg/CdFcyQ * https://discord.gg/CdFcyQ
*/ */
import netneutrality.handler.LogHandler; import netneutrality.core.LogHandler;
public class ExecutorException implements Thread.UncaughtExceptionHandler { public class ExecutorException implements Thread.UncaughtExceptionHandler {
@@ -1,38 +0,0 @@
/*
* Copyright 2017 github.com/kaaz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package netneutrality.exceptions;
import java.sql.SQLException;
public class UnimplementedParameterException extends SQLException {
private final String s;
public UnimplementedParameterException(Object parameter) {
s = "Parameter not implemented at for: " + parameter;
}
public UnimplementedParameterException(Object parameter, int pos) {
s = "Parameter not implemented! parameter:" + parameter + " - position:" + pos;
}
@Override
public String toString() {
return s;
}
}
@@ -7,19 +7,13 @@ package netneutrality.handler.hooks.guilds;
* https://discord.gg/CdFcyQ * https://discord.gg/CdFcyQ
*/ */
import net.dv8tion.jda.api.events.guild.GuildJoinEvent;
import net.dv8tion.jda.api.events.guild.GuildLeaveEvent; import net.dv8tion.jda.api.events.guild.GuildLeaveEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.hooks.ListenerAdapter;
import netneutrality.GuildManager; import netneutrality.core.GuildManager;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public class ServerJoinHandler extends ListenerAdapter { public class ServerJoinHandler extends ListenerAdapter {
@Override
public void onGuildJoin(@NotNull GuildJoinEvent event) {
GuildManager.getManager(event.getGuild()).handleJoinEvent();
}
@Override @Override
public void onGuildLeave(@NotNull GuildLeaveEvent event) { public void onGuildLeave(@NotNull GuildLeaveEvent event) {
GuildManager.getManager(event.getGuild()).removeFromDB(); GuildManager.getManager(event.getGuild()).removeFromDB();
@@ -7,14 +7,18 @@ package netneutrality.handler.hooks.message;
* https://discord.gg/CdFcyQ * https://discord.gg/CdFcyQ
*/ */
import java.awt.Color; import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.events.message.MessageUpdateEvent; import net.dv8tion.jda.api.events.message.MessageUpdateEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.hooks.ListenerAdapter;
import netneutrality.core.GuildManager;
import netneutrality.core.SessionManager;
import netneutrality.db.DBController; import netneutrality.db.DBController;
import netneutrality.db.controllers.DBMessage; import netneutrality.db.controllers.DBMessage;
import netneutrality.db.models.MTableModel; import netneutrality.db.entities.OGuild;
import netneutrality.utils.MessageFunction;
import org.hibernate.Session;
import java.util.stream.Collectors;
public class EditHandler extends ListenerAdapter { public class EditHandler extends ListenerAdapter {
@@ -23,37 +27,32 @@ public class EditHandler extends ListenerAdapter {
if (event.getAuthor().isBot()) return; if (event.getAuthor().isBot()) return;
MTableModel table = DBController.get().prepareAndExecuteAsync("SELECT channel_id, guild_id FROM logging WHERE guild_id = ? AND enabled = 1", event.getGuild().getId()).blocking(); GuildManager guildManager = GuildManager.getManager(event.getGuild());
Object logChannel = table.getRowModel(0).getItem(0); if (guildManager.getGuildEntity().getLogging()) {
Object guild = table.getRowModel(0).getItem(1); OGuild guildEntity = guildManager.getGuildEntity();
if (logChannel != null && guild != null) { if (guildEntity.getLogChannel() != null && !guildEntity.getLogChannel().isEmpty()) {
String originalMessage = ((DBMessage) DBController.get("message")).getMessageString(event.getMessage().getId()); Session session = SessionManager.getSessionFactory().openSession();
((DBMessage) DBController.get("message")).logEdit(event.getMessage().getId(), event.getMessage().getContentDisplay()); session.load(guildEntity, guildEntity.getGuildId());
EmbedBuilder editEmbed = new EmbedBuilder(); int size = guildEntity.getLoggings()
editEmbed.setColor(Color.RED); .stream()
editEmbed.setDescription(":pencil2: **Message edited by " + event.getAuthor().getName() + "**"); .filter(oLogging -> oLogging.getId().getChannelId().equals(event.getChannel().getId()) && oLogging.getEnabled())
try { .collect(Collectors.toSet())
editEmbed.addField("Original message", (originalMessage == null ? "Not available" : originalMessage), false); .size();
} catch (IllegalArgumentException ex) {
editEmbed.addField("Original message:", "Message too long.", false); if (size > 0) {
TextChannel channel = event.getGuild().getTextChannelById(guildEntity.getLogChannel());
if (channel != null) {
String originalMessage = DBController.get("message", DBMessage.class).getMessageString(event.getMessage().getId());
DBController.get("message", DBMessage.class).logEdit(event.getMessage().getId(), event.getMessage().getContentDisplay());
channel.sendMessageEmbeds(MessageFunction.buildEditMessage(event.getMember(), event.getMessage(), originalMessage)).queue();
}
}
} }
try {
editEmbed.addField("Edited to:", event.getMessage().getContentDisplay(), false);
} catch (IllegalArgumentException ex) {
editEmbed.addField("Edited to:", "Message too long.", false);
}
editEmbed.setFooter("ID : " + event.getMessageId(), null);
editEmbed.setTimestamp(event.getMessage().getTimeCreated());
event.getJDA().getGuildById((String) guild).getTextChannelById((String) logChannel).sendMessageEmbeds(editEmbed.build()).queue();
} }
} }
} }
@@ -6,13 +6,15 @@ package netneutrality.handler.hooks.message;
* https://discord.gg/CdFcyQ * https://discord.gg/CdFcyQ
*/ */
import io.sentry.Breadcrumb;
import io.sentry.Sentry;
import net.dv8tion.jda.api.entities.*; import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent; import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.hooks.ListenerAdapter;
import netneutrality.GuildManager;
import netneutrality.command.AbstractCommand; import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandManager; import netneutrality.command.CommandManager;
import netneutrality.core.GuildManager;
import netneutrality.core.context.CommandContext;
import netneutrality.utils.Settings; import netneutrality.utils.Settings;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@@ -29,6 +31,8 @@ public class MessageReceivedHandler extends ListenerAdapter {
if (user.isBot()) return; if (user.isBot()) return;
if (event.isWebhookMessage()) return; if (event.isWebhookMessage()) return;
Sentry.addBreadcrumb(Breadcrumb.info("New message from " + member.getEffectiveName()));
CommandContext context = CommandContext.createContext(event); CommandContext context = CommandContext.createContext(event);
GuildManager.getManager(guild).getRateLimiter().check(member, message, channel); GuildManager.getManager(guild).getRateLimiter().check(member, message, channel);
@@ -48,7 +52,7 @@ public class MessageReceivedHandler extends ListenerAdapter {
} }
} else { } else {
GuildManager.getManager(guild).checkBlacklist(message, member, channel); GuildManager.getManager(guild).checkBlacklist(message, channel);
} }
} }
} }
@@ -1,4 +1,5 @@
package netneutrality.handler;/* package netneutrality.handler.hooks.message;
/*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
* https://xtremcommunity.com/ * https://xtremcommunity.com/
+6 -6
View File
@@ -1,12 +1,12 @@
package netneutrality.http; package netneutrality.http;
/* /*
* Copyright (c) anthorob * Copyright (c) anthorob
* *
* This file is closed-source. It should not be distributed or copied in any way or form * https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/ */
import netneutrality.db.models.MSellyOrder; import netneutrality.db.entities.OSellyOrder;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
@@ -24,10 +24,10 @@ public class Selly {
encodedAuth = Base64.getEncoder().encode(concat.getBytes()); encodedAuth = Base64.getEncoder().encode(concat.getBytes());
} }
public Map<String, MSellyOrder> getOrders() { public Map<String, OSellyOrder> getOrders() {
WebModule sellyApi = new WebModule("https://selly.gg/api/v2/orders"); WebModule sellyApi = new WebModule("https://selly.gg/api/v2/orders");
Map<String, String> headers = new HashMap<>(); Map<String, String> headers = new HashMap<>();
Map<String, MSellyOrder> orders = new HashMap<>(); Map<String, OSellyOrder> orders = new HashMap<>();
headers.put("Authorization", "Basic " + new String(encodedAuth)); headers.put("Authorization", "Basic " + new String(encodedAuth));
JSONArray response = null; JSONArray response = null;
try { try {
@@ -40,7 +40,7 @@ public class Selly {
for (int i = 0; i < response.length(); i++) { for (int i = 0; i < response.length(); i++) {
JSONObject order = response.getJSONObject(i); JSONObject order = response.getJSONObject(i);
orders.put(order.getString("id"), new MSellyOrder(order.getString("id"), order.getString("product_id"), order.getString("email"), order.getString("ip_address"), orders.put(order.getString("id"), new OSellyOrder(order.getString("id"), order.getString("product_id"), order.getString("email"), order.getString("ip_address"),
Float.parseFloat(order.getString("value")), order.getString("currency"), order.getString("gateway"), order.getInt("risk_level"), order.getInt("status"), Float.parseFloat(order.getString("value")), order.getString("currency"), order.getString("gateway"), order.getInt("risk_level"), order.getInt("status"),
order.getInt("crypto_value"), order.getString("crypto_address"), Float.parseFloat(order.getString("usd_value")), order.getString("created_at"))); order.getInt("crypto_value"), order.getString("crypto_address"), Float.parseFloat(order.getString("usd_value")), order.getString("created_at")));
} }
+20 -32
View File
@@ -1,11 +1,12 @@
package netneutrality.http; package netneutrality.http;
import io.sentry.Breadcrumb;
import io.sentry.Sentry;
import okhttp3.*; import okhttp3.*;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -28,21 +29,22 @@ public class WebModule {
* @return an instance of the WebModule class with the Response of the Web Request * @return an instance of the WebModule class with the Response of the Web Request
*/ */
public WebModule request() { public WebModule request() {
Sentry.addBreadcrumb(Breadcrumb.http(url, "get"));
Request request = new Request.Builder().url(this.url) Request request = new Request.Builder().url(this.url)
.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 OPR/82.0.4227.43") .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 OPR/82.0.4227.43")
.build(); .build();
try { try {
response = client.newCall(request).execute(); response = client.newCall(request).execute();
Sentry.addBreadcrumb(Breadcrumb.http(url, "get", response.code()));
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); Sentry.captureException(e);
} }
return this; return this;
} }
public WebModule request(Map<String, String> headers) throws IOException { public WebModule request(Map<String, String> headers) throws IOException {
Sentry.addBreadcrumb(Breadcrumb.http(url, "get"));
Request.Builder builder = new Request.Builder().url(this.url) Request.Builder builder = new Request.Builder().url(this.url)
.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36"); .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36");
@@ -52,12 +54,18 @@ public class WebModule {
Request request = builder.build(); Request request = builder.build();
response = client.newCall(request).execute(); try {
response = client.newCall(request).execute();
Sentry.addBreadcrumb(Breadcrumb.http(url, "get", response.code()));
} catch (IOException e) {
Sentry.captureException(e);
}
return this; return this;
} }
public WebModule post(TreeMap<String, String> params, Map<String, String> headers) throws IOException { public WebModule post(TreeMap<String, String> params, Map<String, String> headers) {
Sentry.addBreadcrumb(Breadcrumb.http(url, "post"));
RequestBody body = RequestBody.create(createJson(params), MediaType.parse("application/json; charset=utf-8")); RequestBody body = RequestBody.create(createJson(params), MediaType.parse("application/json; charset=utf-8"));
Request.Builder builder = new Request.Builder().url(this.url) Request.Builder builder = new Request.Builder().url(this.url)
.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36"); .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36");
@@ -66,7 +74,12 @@ public class WebModule {
builder.addHeader(header.getKey(), header.getValue()); builder.addHeader(header.getKey(), header.getValue());
} }
Request request = builder.post(body).build(); Request request = builder.post(body).build();
response = client.newCall(request).execute(); try {
response = client.newCall(request).execute();
Sentry.addBreadcrumb(Breadcrumb.http(url, "post", response.code()));
} catch (IOException e) {
Sentry.captureException(e);
}
return this; return this;
} }
@@ -157,29 +170,4 @@ public class WebModule {
return response.body().string(); return response.body().string();
} }
public String getTextInHtmlTag(String tag) {
String body = "";
try {
body = getRawData();
} catch (IOException | RuntimeException e) {
e.printStackTrace();
}
int startOfTag = body.indexOf(tag);
int endOfTag = body.indexOf(getEndHtmlTag(tag));
if (startOfTag < 0 || endOfTag < 0) {
return "";
}
return body.substring(startOfTag + tag.length(), endOfTag - (tag.length() - 1));
}
private String getEndHtmlTag(String startingTag) {
String endingTag = "";
if (startingTag.charAt(0) == '<' && startingTag.charAt(1) != '/' ) {
endingTag = "</" + startingTag.substring(1, startingTag.length() - 1) + ">";
}
System.out.println("endingTag = " + endingTag);
return endingTag;
}
} }
@@ -7,11 +7,11 @@ package netneutrality.http.server;/*
import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpExchange;
import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Guild;
import netneutrality.GuildManager; import netneutrality.NetNeutrality;
import netneutrality.MusicBot; import netneutrality.core.GuildManager;
import netneutrality.http.WebModule; import netneutrality.http.WebModule;
import org.apache.logging.log4j.LogManager;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.util.Map; import java.util.Map;
@@ -24,9 +24,9 @@ public class ActionHandler extends AbstractHandler {
String path = exchange.getRequestURI().getRawPath(); String path = exchange.getRequestURI().getRawPath();
if (path.equals("/actions/shutdown")) { if (path.equals("/actions/shutdown")) {
LogManager.getLogger(MusicBot.class).info("Request to shutdown received"); LoggerFactory.getLogger(NetNeutrality.class).info("Request to shutdown received");
sendStringResponse(exchange, "Shutting down.."); sendStringResponse(exchange, "Shutting down..");
MusicBot.shutdown(); NetNeutrality.shutdown();
System.exit(0); System.exit(0);
return; return;
@@ -34,8 +34,8 @@ public class ActionHandler extends AbstractHandler {
if (path.equals("/actions/status")) { if (path.equals("/actions/status")) {
TreeMap<String, String> json = new TreeMap<>(); TreeMap<String, String> json = new TreeMap<>();
json.put("health", String.valueOf(MusicBot.getJDA().getStatus())); json.put("health", String.valueOf(NetNeutrality.getJDA().getStatus()));
json.put("ping", String.valueOf(MusicBot.getJDA().getGatewayPing())); json.put("ping", String.valueOf(NetNeutrality.getJDA().getGatewayPing()));
sendJsonResponse(exchange, WebModule.createJson(json)); sendJsonResponse(exchange, WebModule.createJson(json));
return; return;
@@ -46,10 +46,10 @@ public class ActionHandler extends AbstractHandler {
String[] args = exchange.getRequestURI().toString().split("/"); String[] args = exchange.getRequestURI().toString().split("/");
String guildId = args[args.length - 1]; String guildId = args[args.length - 1];
Guild guild = MusicBot.getJDA().getGuildById(guildId); Guild guild = NetNeutrality.getJDA().getGuildById(guildId);
if (guild != null) { if (guild != null) {
GuildManager manager = GuildManager.getManager(guild); GuildManager manager = GuildManager.getManager(guild);
Map<String, Object> settings = manager.getSettings(); Map<String, String> settings = manager.getSettings();
JSONObject setting = new JSONObject(settings); JSONObject setting = new JSONObject(settings);
json.put("status", "ok"); json.put("status", "ok");
@@ -67,13 +67,14 @@ public class ActionHandler extends AbstractHandler {
String[] args = exchange.getRequestURI().toString().split("/"); String[] args = exchange.getRequestURI().toString().split("/");
String guildId = args[args.length - 1]; String guildId = args[args.length - 1];
Guild guild = MusicBot.getJDA().getGuildById(guildId); Guild guild = NetNeutrality.getJDA().getGuildById(guildId);
boolean ok; boolean ok;
if (guild == null) if (guild == null)
ok = GuildManager.reloadSettingsForGuild(guildId); ok = GuildManager.reloadSettingsForGuild(guildId);
else else
ok = GuildManager.reloadSettingsForGuild(guild); ok = GuildManager.reloadSettingsForGuild(guild);
json.put("status", String.valueOf(ok)); json.put("status", String.valueOf(ok));
sendJsonResponse(exchange, WebModule.createJson(json)); sendJsonResponse(exchange, WebModule.createJson(json));
@@ -9,7 +9,7 @@ package netneutrality.http.server;
import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpExchange;
import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDA;
import netneutrality.MusicBot; import netneutrality.NetNeutrality;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
@@ -26,7 +26,7 @@ public class GuildHandler extends AbstractHandler {
JSONArray array = new JSONArray(); JSONArray array = new JSONArray();
JDA jda = MusicBot.getJDA(); JDA jda = NetNeutrality.getJDA();
jda.getGuilds().forEach(guild -> { jda.getGuilds().forEach(guild -> {
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
@@ -46,7 +46,7 @@ public class GuildHandler extends AbstractHandler {
String guild = args[args.length - 1]; String guild = args[args.length - 1];
JSONArray array = new JSONArray(); JSONArray array = new JSONArray();
JDA jda = MusicBot.getJDA(); JDA jda = NetNeutrality.getJDA();
if (jda.getGuildById(guild) == null) { if (jda.getGuildById(guild) == null) {
sendStringResponse(exchange, path); sendStringResponse(exchange, path);
@@ -70,7 +70,7 @@ public class GuildHandler extends AbstractHandler {
String[] args = exchange.getRequestURI().toString().split("/"); String[] args = exchange.getRequestURI().toString().split("/");
String guild = args[args.length - 1]; String guild = args[args.length - 1];
JSONArray array = new JSONArray(); JSONArray array = new JSONArray();
JDA jda = MusicBot.getJDA(); JDA jda = NetNeutrality.getJDA();
if (jda.getGuildById(guild) == null) { if (jda.getGuildById(guild) == null) {
sendStringResponse(exchange, path); sendStringResponse(exchange, path);
@@ -20,14 +20,13 @@ import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.entities.VoiceChannel; import net.dv8tion.jda.api.entities.VoiceChannel;
import netneutrality.GuildManager; import netneutrality.core.GuildManager;
import netneutrality.ThreadManager; import netneutrality.core.LogHandler;
import netneutrality.command.CommandContext; import netneutrality.core.context.CommandContext;
import netneutrality.exceptions.CommandErrorException; import netneutrality.exceptions.CommandErrorException;
import netneutrality.handler.LogHandler;
import netneutrality.thread.MusicPlayerAutoDisconnectThread; import netneutrality.thread.MusicPlayerAutoDisconnectThread;
import netneutrality.thread.ThreadManager;
import netneutrality.utils.MessageFunction; import netneutrality.utils.MessageFunction;
import netneutrality.utils.Settings;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -51,17 +50,18 @@ public class MusicManager {
private final AudioPlayerManager playerManager; private final AudioPlayerManager playerManager;
private final TrackScheduler scheduler; private final TrackScheduler scheduler;
private ScheduledFuture<?> autoDisconnectThread; private ScheduledFuture<?> autoDisconnectThread;
private final int baseVolume;
private MusicManager(Guild guild) { private MusicManager(Guild guild) {
this.guild = guild; this.guild = guild;
this.playerManager = new DefaultAudioPlayerManager(); this.playerManager = new DefaultAudioPlayerManager();
this.player = playerManager.createPlayer(); this.player = playerManager.createPlayer();
this.scheduler = new TrackScheduler(player); this.scheduler = new TrackScheduler(player);
this.baseVolume = Integer.parseInt(GuildManager.getManager(guild).getSetting(GuildManager.Settings.MUSIC_VOLUME));
AudioSourceManagers.registerRemoteSources(playerManager); AudioSourceManagers.registerRemoteSources(playerManager);
guild.getAudioManager().setSendingHandler(new AudioPlayerSendHandler(player)); guild.getAudioManager().setSendingHandler(new AudioPlayerSendHandler(player));
player.addListener(scheduler); player.addListener(scheduler);
player.setVolume((Integer) GuildManager.getManager(guild).getSetting(GuildManager.GuildSetting.MUSIC_VOLUME));
managers.put(guild.getId(), this); managers.put(guild.getId(), this);
} }
@@ -75,8 +75,8 @@ public class MusicManager {
} }
public static void initPlayerManager() { public static void initPlayerManager() {
YoutubeHttpContextFilter.setPAPISID(Settings.getInstance().get("BOT_PAPISID", "")); YoutubeHttpContextFilter.setPAPISID(netneutrality.utils.Settings.getInstance().get("BOT_PAPISID", ""));
YoutubeHttpContextFilter.setPSID(Settings.getInstance().get("BOT_PSID", "")); YoutubeHttpContextFilter.setPSID(netneutrality.utils.Settings.getInstance().get("BOT_PSID", ""));
} }
public boolean isConnectedTo(VoiceChannel vChannel) { public boolean isConnectedTo(VoiceChannel vChannel) {
@@ -87,6 +87,7 @@ public class MusicManager {
if (vChannel != null && !isConnectedTo(vChannel)) { if (vChannel != null && !isConnectedTo(vChannel)) {
guild.getAudioManager().openAudioConnection(vChannel); guild.getAudioManager().openAudioConnection(vChannel);
guild.getAudioManager().setSelfDeafened(true); guild.getAudioManager().setSelfDeafened(true);
player.setVolume(baseVolume);
if (autoDisconnectThread == null) if (autoDisconnectThread == null)
autoDisconnectThread = executor.scheduleWithFixedDelay(new MusicPlayerAutoDisconnectThread(this), 120, 120, TimeUnit.SECONDS); autoDisconnectThread = executor.scheduleWithFixedDelay(new MusicPlayerAutoDisconnectThread(this), 120, 120, TimeUnit.SECONDS);
@@ -142,7 +143,7 @@ public class MusicManager {
} }
public boolean restoreQueue(List<String> track) { public boolean restoreQueue(List<String> track) {
//TODO: todo
return false; return false;
} }
@@ -235,6 +236,10 @@ public class MusicManager {
} }
} }
public synchronized void stopTrack() {
player.stopTrack();
}
public synchronized void skip(int nbTrack) { public synchronized void skip(int nbTrack) {
if (!scheduler.getQueue().isEmpty()) { if (!scheduler.getQueue().isEmpty()) {
if (nbTrack >= scheduler.getQueue().size()) { if (nbTrack >= scheduler.getQueue().size()) {
@@ -17,7 +17,10 @@ import net.dv8tion.jda.api.entities.TextChannel;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.*; import java.util.ArrayList;
import java.util.HashSet;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
public class TrackScheduler extends AudioEventAdapter { public class TrackScheduler extends AudioEventAdapter {
@@ -8,7 +8,7 @@ package netneutrality.thread;/*
import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.VoiceChannel; import net.dv8tion.jda.api.entities.VoiceChannel;
import netneutrality.MusicBot; import netneutrality.NetNeutrality;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
import java.util.List; import java.util.List;
@@ -32,7 +32,7 @@ public class MusicPlayerAutoDisconnectThread implements Runnable {
} }
if (channel != null) { if (channel != null) {
List<Member> members = channel.getMembers().stream().filter(member -> !member.getId().equals(MusicBot.getSelf().getId())).toList(); List<Member> members = channel.getMembers().stream().filter(member -> !member.getId().equals(NetNeutrality.getSelf().getId())).toList();
if (members.size() == 0) if (members.size() == 0)
manager.leave(); manager.leave();
@@ -5,8 +5,7 @@ package netneutrality.thread;/*
* https://discord.gg/CdFcyQ * https://discord.gg/CdFcyQ
*/ */
import netneutrality.MusicBot; import netneutrality.NetNeutrality;
import netneutrality.utils.UnsafeShutdown;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configurator; import org.apache.logging.log4j.core.config.Configurator;
@@ -20,8 +19,8 @@ public class ShutdownThread implements Runnable {
Configurator.shutdown((LoggerContext) LogManager.getContext()); Configurator.shutdown((LoggerContext) LogManager.getContext());
} }
if (MusicBot.getJDA() != null) { if (NetNeutrality.getJDA() != null) {
MusicBot.shutdown(); NetNeutrality.shutdown();
} }
} }
@@ -1,11 +1,16 @@
package netneutrality; package netneutrality.thread;
/*
import netneutrality.thread.BaseThreadFactory; * Copyright (c) anthorob
import org.slf4j.Logger; *
import org.slf4j.LoggerFactory; * https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import java.util.Map; import java.util.Map;
import java.util.concurrent.*; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadManager { public class ThreadManager {
@@ -14,7 +19,6 @@ public class ThreadManager {
} }
private static final Map<String, ExecutorService> executors = new ConcurrentHashMap<>(); private static final Map<String, ExecutorService> executors = new ConcurrentHashMap<>();
private final static Logger logger = LoggerFactory.getLogger(ThreadManager.class);
public static ExecutorService getExecutor(String name) { public static ExecutorService getExecutor(String name) {
return executors.computeIfAbsent(name, s -> Executors.newSingleThreadExecutor(new BaseThreadFactory(name))); return executors.computeIfAbsent(name, s -> Executors.newSingleThreadExecutor(new BaseThreadFactory(name)));
@@ -1,14 +1,18 @@
package netneutrality.utils; package netneutrality.utils;
import io.sentry.ISpan;
import io.sentry.ITransaction;
import io.sentry.Sentry;
import io.sentry.SpanStatus;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.TextChannel;
import netneutrality.thread.ThreadManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.OffsetDateTime; import java.time.OffsetDateTime;
import java.util.List; import java.util.List;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.TextChannel;
import netneutrality.ThreadManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ChannelFunction { public class ChannelFunction {
private static final Logger logger = LoggerFactory.getLogger(ChannelFunction.class); private static final Logger logger = LoggerFactory.getLogger(ChannelFunction.class);
@@ -18,38 +22,74 @@ public class ChannelFunction {
if (toDelete >= 2500) return; if (toDelete >= 2500) return;
ThreadManager.getExecutor("bulk-delete", ThreadManager.ExecutorType.FIXED).submit(() -> { ThreadManager.getExecutor("bulk-delete", ThreadManager.ExecutorType.FIXED).submit(() -> {
ITransaction transaction = Sentry.startTransaction(String.format("bulkDeleteMessage(%s, %d)", channel.getId(), toDelete), "task");
transaction.setData("channel", channel.getId());
transaction.setData("toDelete", toDelete);
transaction.setTag("operation", "bulk-delete");
int toDeleteFinal = toDelete + 1; try {
int iteration = toDeleteFinal / 100;
for (int i = 0; i < iteration; i++) {
List<Message> messages = channel.getHistory().retrievePast(100).complete();
deleteFromList(messages, channel);
toDeleteFinal -= 100;
int toDeleteFinal = toDelete + 1;
int iteration = toDeleteFinal / 100;
for (int i = 0; i < iteration; i++) {
ISpan innerSpan = transaction.startChild("task", "Processing iteration " + (i + 1) + "/" + iteration);
try {
List<Message> messages = channel.getHistory().retrievePast(100).complete();
deleteFromList(messages, channel, innerSpan);
toDeleteFinal -= 100;
innerSpan.setStatus(SpanStatus.OK);
} catch (Exception e) {
innerSpan.setThrowable(e);
innerSpan.setStatus(SpanStatus.INTERNAL_ERROR);
throw e;
} finally {
innerSpan.finish();
}
}
if (toDeleteFinal > 0) {
ISpan innerSpan = transaction.startChild("task", String.format("Processing final iteration (%d messages)", toDeleteFinal));
try {
List<Message> messages = channel.getHistory().retrievePast(toDeleteFinal).complete();
deleteFromList(messages, channel, innerSpan);
innerSpan.setStatus(SpanStatus.OK);
} catch (Exception e) {
innerSpan.setThrowable(e);
innerSpan.setStatus(SpanStatus.INTERNAL_ERROR);
throw e;
} finally {
innerSpan.finish();
}
innerSpan.finish();
}
transaction.setStatus(SpanStatus.OK);
} catch (Exception e) {
transaction.setThrowable(e);
transaction.setStatus(SpanStatus.INTERNAL_ERROR);
} finally {
transaction.finish();
} }
if (toDeleteFinal > 0) {
List<Message> messages = channel.getHistory().retrievePast(toDeleteFinal).complete();
deleteFromList(messages, channel);
}
}); });
} }
private synchronized static void deleteFromList(List<Message> messages, TextChannel channel) { private synchronized static void deleteFromList(List<Message> messages, TextChannel channel, ISpan span) {
ISpan innerSpan = span.startChild("delete", "Executing delete of: " + messages.size() + " messages");
try { try {
channel.deleteMessages(messages).complete(); channel.deleteMessages(messages).complete();
logger.debug("Deleted {} messages from channel [{}] in guild [{}]", messages.size(), channel.getName(), channel.getGuild().getName()); innerSpan.setStatus(SpanStatus.OK);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
innerSpan.setThrowable(e);
innerSpan.setStatus(SpanStatus.OUT_OF_RANGE);
messages.forEach(m -> { messages.forEach(m -> {
if (!m.getTimeCreated().isBefore(OffsetDateTime.now().minusWeeks(2))) { if (!m.getTimeCreated().isBefore(OffsetDateTime.now().minusWeeks(2))) {
m.delete().queue(); m.delete().queue();
} }
}); });
} finally {
innerSpan.finish();
} }
} }
} }
@@ -0,0 +1,42 @@
package netneutrality.utils;/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import io.sentry.Breadcrumb;
import io.sentry.Sentry;
import io.sentry.SentryLevel;
import netneutrality.core.GuildManager;
import netneutrality.db.entities.OGuild;
import org.hibernate.HibernateException;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.Session;
import java.io.Serializable;
public class JpaUtils {
public static void tryLoad(Session session, Object object, Serializable id) {
try {
session.load(object, id);
} catch (HibernateException exception) {
if (object instanceof OGuild oGuild) {
if (exception instanceof ObjectNotFoundException) {
Sentry.addBreadcrumb(Breadcrumb.error("ObjectNotFoundException"));
String cachedId = oGuild.getGuildId();
Sentry.captureMessage("Trying to load Guild[" + cachedId + "] while deleted from database, reloading..", SentryLevel.ERROR);
GuildManager guildManager = GuildManager.getManager(cachedId);
guildManager.reloadEntity();
guildManager.getBlacklistCache().clear();
Sentry.captureMessage("Guild[" + cachedId + "] reloaded", SentryLevel.INFO);
}
}
session.close();
throw exception;
}
}
}
@@ -7,27 +7,24 @@ package netneutrality.utils;
* https://discord.gg/CdFcyQ * https://discord.gg/CdFcyQ
*/ */
import java.awt.*;
import java.time.OffsetDateTime;
import java.util.*;
import java.util.List;
import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist; import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.*; import net.dv8tion.jda.api.entities.*;
import netneutrality.command.AbstractCommand; import netneutrality.command.AbstractCommand;
import netneutrality.command.CommandContext;
import netneutrality.command.CommandType; import netneutrality.command.CommandType;
import netneutrality.db.DBController; import netneutrality.core.context.CommandContext;
import netneutrality.db.controllers.DBBlacklist;
import netneutrality.db.models.MBlacklist;
import netneutrality.exceptions.CommandExecutionException; import netneutrality.exceptions.CommandExecutionException;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
import org.apache.commons.lang3.time.DurationFormatUtils; import org.apache.commons.lang3.time.DurationFormatUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.awt.*;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.*;
public class MessageFunction { public class MessageFunction {
private final static Logger logger = LoggerFactory.getLogger(MessageFunction.class); private final static Logger logger = LoggerFactory.getLogger(MessageFunction.class);
@@ -89,7 +86,7 @@ public class MessageFunction {
message.addField("Track title: ", track.getInfo().title, false); message.addField("Track title: ", track.getInfo().title, false);
message.addField("Uploaded by: ", track.getInfo().author, false); message.addField("Uploaded by: ", track.getInfo().author, false);
message.addField("Duration: ", DurationFormatUtils.formatDuration(track.getDuration(), "**HH:mm:ss**", true), false); message.addField("Duration: ", DurationFormatUtils.formatDuration(track.getDuration(), "**HH:mm:ss**", true), false);
message.setFooter("Requested by " + user.getUser().getName(), user.getUser().getAvatarUrl()); message.setFooter("Requested by " + user.getEffectiveName(), user.getAvatarUrl());
message.setTimestamp(OffsetDateTime.now()); message.setTimestamp(OffsetDateTime.now());
return message.build(); return message.build();
@@ -103,7 +100,7 @@ public class MessageFunction {
message.setColor(Color.BLUE); message.setColor(Color.BLUE);
message.addField("Playlist: ", playlist.getName(), false); message.addField("Playlist: ", playlist.getName(), false);
message.addField("Number of tracks: ", String.valueOf(playlist.getTracks().size()), false); message.addField("Number of tracks: ", String.valueOf(playlist.getTracks().size()), false);
message.setFooter("Requested by " + user.getUser().getName(), user.getUser().getAvatarUrl()); message.setFooter("Requested by " + user.getEffectiveName(), user.getAvatarUrl());
message.setTimestamp(OffsetDateTime.now()); message.setTimestamp(OffsetDateTime.now());
return message.build(); return message.build();
@@ -118,7 +115,7 @@ public class MessageFunction {
message.setColor(Color.BLUE); message.setColor(Color.BLUE);
int index = 0; int index = 0;
for (AudioTrack track: tracks) { for (AudioTrack track : tracks) {
if (track.getInfo().title.equals(current.getInfo().title) && currentlyPlaying) { if (track.getInfo().title.equals(current.getInfo().title) && currentlyPlaying) {
message.addField("Track #" + ++index + " (Currently playing)", track.getInfo().title, false); message.addField("Track #" + ++index + " (Currently playing)", track.getInfo().title, false);
} else { } else {
@@ -128,7 +125,7 @@ public class MessageFunction {
if (index == 10) break; if (index == 10) break;
} }
message.setFooter("Requested by " + user.getUser().getName(), user.getUser().getAvatarUrl()); message.setFooter("Requested by " + user.getEffectiveName(), user.getAvatarUrl());
message.setTimestamp(OffsetDateTime.now()); message.setTimestamp(OffsetDateTime.now());
return message.build(); return message.build();
@@ -140,7 +137,7 @@ public class MessageFunction {
message.setColor(Color.BLUE); message.setColor(Color.BLUE);
message.addField("Command", command.getCommandName(), false); message.addField("Command", command.getCommandName(), false);
message.addField("Description", command.getDescription(), false); message.addField("Description", command.getDescription(), false);
message.addField("Aliases", ((command.getAlias() == null || command.getAlias().length == 0) ? "None": Arrays.toString(command.getAlias()).replaceAll("[\\[\\]]", "")), false); message.addField("Aliases", ((command.getAlias() == null || command.getAlias().length == 0) ? "None" : Arrays.toString(command.getAlias()).replaceAll("[\\[\\]]", "")), false);
message.addField("Usage", (command.getUsage() == null ? "No arguments defined" : command.getUsage().toString()), false); message.addField("Usage", (command.getUsage() == null ? "No arguments defined" : command.getUsage().toString()), false);
return message.build(); return message.build();
@@ -217,32 +214,47 @@ public class MessageFunction {
message.addField("Caused by:", cause, false); message.addField("Caused by:", cause, false);
} }
message.setFooter("Requested by " + context.getDiscordUser().getName(), context.getDiscordUser().getAvatarUrl()); message.setFooter("Requested by " + context.getGuildUser().getEffectiveName(), context.getGuildUser().getAvatarUrl());
message.setTimestamp(OffsetDateTime.now()); message.setTimestamp(OffsetDateTime.now());
return message.build(); return message.build();
} }
public static void checkBlacklist(Guild guild, Message message, TextChannel channel) { public static MessageEmbed buildEditMessage(Member member, Message message, String originalMessage) {
EmbedBuilder editEmbed = new EmbedBuilder();
editEmbed.setColor(Color.RED);
editEmbed.setDescription(":pencil2: **Message edited by " + member.getEffectiveName() + "**");
try {
editEmbed.addField("Original message", (originalMessage == null ? "Not available" : originalMessage), false);
} catch (IllegalArgumentException ex) {
editEmbed.addField("Original message:", "Message too long.", false);
}
ArrayList<MBlacklist> mBlacklists = ((DBBlacklist) DBController.get("blacklist")).getBlacklistFromServer(guild.getId()); try {
if (!mBlacklists.isEmpty()) { editEmbed.addField("Edited to:", message.getContentDisplay(), false);
} catch (IllegalArgumentException ex) {
editEmbed.addField("Edited to:", "Message too long.", false);
}
boolean found = false; editEmbed.setFooter("ID : " + message.getId(), null);
for (MBlacklist aBlacklist : mBlacklists) { editEmbed.setTimestamp(message.getTimeCreated());
if (message.getContentRaw().toLowerCase().contains(aBlacklist.getWord())) {
found = true;
break;
}
}
if (found) {
message.delete().queue();
channel.sendMessage("Not in my christian server").queue();
}
}
return editEmbed.build();
} }
public static void testMessageAgainstBlacklist(Message message, TextChannel channel, Set<String> cache) {
boolean found = false;
for (String word : cache) {
if (message.getContentRaw().toLowerCase().contains(word)) {
found = true;
break;
}
}
if (found) {
message.delete().queue();
channel.sendMessage("Not in my christian server").queue();
}
}
} }
@@ -6,29 +6,45 @@ package netneutrality.utils;/*
*/ */
import net.dv8tion.jda.api.entities.VoiceChannel; import net.dv8tion.jda.api.entities.VoiceChannel;
import netneutrality.command.CommandContext; import netneutrality.core.context.CommandContext;
import netneutrality.exceptions.CommandErrorException;
import netneutrality.exceptions.CommandExecutionException; import netneutrality.exceptions.CommandExecutionException;
import netneutrality.music.MusicManager; import netneutrality.music.MusicManager;
public class MusicUtils { public class MusicUtils {
public static void checkIfConnected(MusicManager manager, CommandContext context) { public static boolean checkIfConnected(MusicManager manager, CommandContext context) {
if (context.getGuildUser().getVoiceState() == null) { if (context.getGuildUser().getVoiceState() == null) {
throw new CommandExecutionException("Voice state is null", context, null); throw new CommandExecutionException("Voice state is null, this should not happen", context, null);
} }
if (!context.getGuildUser().getVoiceState().inVoiceChannel()) { if (!context.getGuildUser().getVoiceState().inVoiceChannel()) {
throw new CommandErrorException("You are not in a voice channel", context, null); context.reply("You are not in a voice channel");
return false;
} }
VoiceChannel vChannel = context.getGuildUser().getVoiceState().getChannel(); VoiceChannel vChannel = context.getGuildUser().getVoiceState().getChannel();
if (!manager.isConnected()) { if (!manager.isConnected()) {
throw new CommandErrorException("Player is not in a voice channel", context, null); context.reply("You are not in a voice channel");
return false;
} }
if (!manager.isConnectedTo(vChannel)) { if (!manager.isConnectedTo(vChannel)) {
throw new CommandErrorException("Player is not in your voice channel", context, null); context.reply("You are not in a voice channel");
return false;
} }
return true;
}
public static boolean checkIfDj(MusicManager manager, CommandContext context) {
if (manager.getCurrentlyPlaying() != null) {
if (!UserFunction.isAdmin(context.getGuildUser()) || !manager.getRequesterOfCurrentTrack().getId().equals(context.getGuildUser().getId())) {
context.reply("You are not powerful enough, scrub");
return false;
} else
return true;
}
return false;
} }
} }
@@ -1,6 +1,8 @@
package netneutrality.utils; package netneutrality.utils;
import java.io.*; import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map; import java.util.Map;
import java.util.Properties; import java.util.Properties;
@@ -10,7 +12,7 @@ public class Settings {
private final Properties prop = new Properties(); private final Properties prop = new Properties();
public Settings() { public Settings() {
File file = new File("bot.config"); File file = new File("bot.properties");
FileInputStream fis = null; FileInputStream fis = null;
try { try {
+1 -1
View File
@@ -1,3 +1,3 @@
Manifest-Version: 1.0 Manifest-Version: 1.0
Main-Class: netneutrality.MusicBot Main-Class: netneutrality.NetNeutrality
+19
View File
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.provider_class">org.hibernate.hikaricp.internal.HikariCPConnectionProvider</property>
<mapping class="netneutrality.db.entities.OGuild"/>
<mapping class="netneutrality.db.entities.OBlacklist"/>
<mapping class="netneutrality.db.entities.OGuildSetting"/>
<mapping class="netneutrality.db.entities.OLogMessage"/>
<mapping class="netneutrality.db.entities.OLogging"/>
<mapping class="netneutrality.db.entities.OLoggingId"/>
</session-factory>
</hibernate-configuration>
+34
View File
@@ -0,0 +1,34 @@
status = warn
appender.console.type = Console
appender.console.name = consoleLogger
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss.SSS} %p [%thread] %logger - %msg%n
# Rotate log file
appender.rolling.type = RollingFile
appender.rolling.name = LogToRollingFile
appender.rolling.fileName = logs/debug.log
appender.rolling.filePattern = logs/$${date:yyyy-MM}/debug-%d{MM-dd-yyyy}-%i.log.gz
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d{yyyy-MM-dd HH:mm:ss.SSS} %p [%thread] %logger - %msg%n
appender.rolling.policies.type = Policies
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling.policies.size.size=10MB
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.max = 5
logger.hibernate.name = org.hibernate
logger.hibernate.level = info
logger.hibernate.additivity = false
logger.hibernate.appenderRef.rolling.ref = LogToRollingFile
logger.app.name = netneutrality
logger.app.level = debug
logger.app.additivity = false
logger.app.appenderRef.rolling.ref = LogToRollingFile
logger.app.appenderRef.console.ref = consoleLogger
rootLogger.level = error
rootLogger.appenderRef.stdout.ref = consoleLogger
-16
View File
@@ -1,16 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" shutdownHook="disable">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %highlight{%-5level}{STYLE=Logback} %logger - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Logger name="netneutrality" level="trace" additivity="false">
<AppenderRef ref="Console"/>
</Logger>
<Root level="error">
<AppenderRef ref="Console" />
</Root>
</Loggers>
</Configuration>
+4
View File
@@ -0,0 +1,4 @@
driverlist=com.mysql.cj.jdbc.Driver
dateformat=yyyy-MM-dd hh:mm:ss a
appender=com.p6spy.engine.spy.appender.StdoutLogger
logMessageFormat=com.p6spy.engine.spy.appender.SingleLineFormat