Basic rewrite of MySQL statements

- Migrated MySQL to use https://github.com/odinfather/Database Instead of custom
- Closed all SQL statements (Hopefully, will have to double-check)
This commit is contained in:
Dalton 2017-09-23 03:48:04 -04:00
parent be2b7967a9
commit bd968d9bcb
22 changed files with 966 additions and 665 deletions

5
.gitignore vendored
View File

@ -116,3 +116,8 @@ gradle-app.setting
# gradle/wrapper/gradle-wrapper.properties # gradle/wrapper/gradle-wrapper.properties
# End of https://www.gitignore.io/api/gradle,intellij,intellij+iml # End of https://www.gitignore.io/api/gradle,intellij,intellij+iml
.idea/compiler.xml
.idea/inspectionProfiles/Project_Default.xml
.idea/vcs.xml
build.gradle
build.gradle

View File

@ -1,7 +1,7 @@
plugins { plugins {
id'java' id 'java'
id'application' id 'application'
id'com.github.johnrengelman.shadow' version '1.2.4' id 'com.github.johnrengelman.shadow' version '1.2.4'
} }
mainClassName = 'me.savvy.rixa.Rixa' mainClassName = 'me.savvy.rixa.Rixa'
@ -19,7 +19,7 @@ sourceCompatibility = 1.8
repositories { repositories {
mavenLocal() mavenLocal()
maven { url "https://oss.sonatype.org/content/repositories/snapshots" } maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
jcenter() jcenter()
} }
@ -31,6 +31,9 @@ dependencies {
compile 'org.twitter4j:twitter4j-stream:4.0.6' compile 'org.twitter4j:twitter4j-stream:4.0.6'
compile 'org.projectlombok:lombok:1.16.18' compile 'org.projectlombok:lombok:1.16.18'
compile 'ca.pjer:chatter-bot-api:1.4.7' compile 'ca.pjer:chatter-bot-api:1.4.7'
compile group: 'com.zaxxer', name: 'HikariCP-java6', version: '2.0.1'
} }
compileJava.options.encoding = 'UTF-8' compileJava.options.encoding = 'UTF-8'
compileJava.options.fork = true
compileJava.options.forkOptions.executable = 'C:\\Program Files\\Java\\jdk1.8.0_131\\bin\\javac.exe'

View File

@ -0,0 +1,324 @@
package me.majrly.database;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import me.majrly.database.params.Parameter;
import me.majrly.database.statements.Query;
import me.majrly.database.statements.Statement;
import java.sql.*;
import java.util.Map;
import java.util.Optional;
/**
* Database API
*
* @author Majrly
* @since 1.0.0
*/
public class Database {
// Variables
private String name;
private String hostname;
private String username;
private String password;
private String database;
private int port = 3306;
private int timeout = 60 * 1000;
private HikariDataSource source;
private HikariConfig config = new HikariConfig();
/**
* Database API
*
* @param name The name of this database instance
* @param hostname The ip to use when connecting
* @param username The username to authenticate as
* @param password The password to authenticate yourself
* @param database The name of the database to switch to
* @param port The port to use when connecting
* @since 1.0.0
*/
public Database(String name, String hostname, String username, String password, String database, int port, HikariConfig config) {
this.config = config;
this.config.setJdbcUrl("jdbc:" + (this.name = name) + "://" + (this.hostname = hostname) + ":" + (this.port = port) + "/" + (this.database = database));
this.config.setDriverClassName("com.mysql.jdbc.Driver");
this.config.setUsername(this.username = username);
this.config.setPassword(this.password = password);
this.source = new HikariDataSource(config);
}
/**
* Get the database options class
*
* @return A reference to {@link DatabaseOptions}
* @since 1.0.0
*/
public static DatabaseOptions options() {
return new DatabaseOptions();
}
/**
* Connects to the database
*
* @return Whether it connected or not
* @since 1.0.0
*/
public void init() {
}
/**
* Sends a query to the database
*
* @param statement The statement to send the database
* @return Either the int of an update, or the ResultSet of a query
* @since 1.0.0
*/
public Optional<?> send(Statement statement) {
Optional<PreparedStatement> optional = prepare(statement);
if (!optional.isPresent()) return Optional.empty();
PreparedStatement preparedStatement = optional.get();
try {
if (statement instanceof Query) {
return Optional.of(preparedStatement.executeQuery());
} else {
return Optional.of(preparedStatement.executeUpdate());
}
} catch (SQLException exception) {
exception.printStackTrace();
return Optional.empty();
}
}
/**
* Close a prepared statement
*
* @param preparedStatement The prepared statement you wish to close
* @since 1.0.0
*/
public void closeStatement(PreparedStatement preparedStatement) {
try {
if (preparedStatement != null && !preparedStatement.isClosed()) {
preparedStatement.close();
}
} catch (SQLException e) {
// Can't handle closing statement
e.printStackTrace();
}
}
/**
* Prepare a statement
*
* @param statement The statement with parameters you wish to prepare
* @return The optional value of {@link PreparedStatement}
* @since 1.0.0
*/
public Optional<PreparedStatement> prepare(Statement statement) {
try {
PreparedStatement preparedStatement = source.getConnection().prepareStatement(statement.getSQL());
for (Map.Entry<Integer, Parameter> parameter : statement.getParameters().entrySet()) {
switch (parameter.getValue().getType()) {
case STRING:
preparedStatement.setString(parameter.getKey(), (String) parameter.getValue().getData());
break;
case INTEGER:
preparedStatement.setInt(parameter.getKey(), (Integer) parameter.getValue().getData());
break;
case DOUBLE:
preparedStatement.setDouble(parameter.getKey(), (Double) parameter.getValue().getData());
break;
case LONG:
preparedStatement.setLong(parameter.getKey(), (Long) parameter.getValue().getData());
break;
case BLOB:
preparedStatement.setBlob(parameter.getKey(), (Blob) parameter.getValue().getData());
break;
case FLOAT:
preparedStatement.setFloat(parameter.getKey(), (Float) parameter.getValue().getData());
break;
case BOOLEAN:
preparedStatement.setBoolean(parameter.getKey(), (Boolean) parameter.getValue().getData());
break;
case DATE:
preparedStatement.setDate(parameter.getKey(), (Date) parameter.getValue().getData());
break;
case OBJECT:
preparedStatement.setObject(parameter.getKey(), parameter.getValue().getData());
break;
default:
preparedStatement.setObject(parameter.getKey(), parameter.getValue().getData());
break;
}
}
return Optional.of(preparedStatement);
} catch (SQLException exception) {
exception.printStackTrace();
return Optional.empty();
}
}
/**
* Prepare a statement
*
* @param sql The statement you want to prepare
* @return The optional value of {@link PreparedStatement}
* @since 1.0.0
*/
public Optional<PreparedStatement> prepare(String sql) {
try {
return Optional.of(source.getConnection().prepareStatement(sql));
} catch (SQLException exception) {
exception.printStackTrace();
return Optional.empty();
}
}
/**
* Get the connection of MySQL
*
* @return The optional value of {@link Connection}
* @since 1.0.0
*/
public Optional<Connection> getConnection() {
try {
return Optional.of(source.getConnection());
} catch (SQLException e) {
return Optional.empty();
}
}
/**
* Closes the database
*
* @since 1.0.0
*/
public void close() {
source.close();
}
public String getName() {
return name;
}
public HikariConfig getConfig() {
return config;
}
public HikariDataSource getSource() {
return source;
}
/**
* Database options used for {@link Database}
*
* @author Majrly
* @since 1.0.0
*/
public static class DatabaseOptions {
// Variables
private HikariConfig config = new HikariConfig();
private String name;
private String hostname = "127.0.0.1";
private String username = "root";
private String password;
private String database;
private int port = 3306;
private int timeout = 60 * 1000;
/**
* Set a key/value in the HikariConfig
*
* @param key The key you want to set a value to
* @param value The value you want to set
* @since 1.0.0
*/
public DatabaseOptions set(String key, String value) {
config.addDataSourceProperty(key, value);
return this;
}
/**
* Set the hostname / port to connect
*
* @param hostname The hostname of the database
* @param port The port of the database
* @return This object
* @since 1.0.0
*/
public DatabaseOptions hostname(String hostname, int port) {
this.database = database;
this.port = port;
return this;
}
/**
* Set the authentication username and password
*
* @param username The user you want to authenticate as
* @param password The password you want to authenticate with
* @return This object
* @since 1.0.0
*/
public DatabaseOptions auth(String username, String password) {
this.username = username;
this.password = password;
return this;
}
/**
* Set the database to switch to
*
* @param database The database you want to switch to
* @return This object
* @since 1.0.0
*/
public DatabaseOptions database(String database) {
this.database = database;
return this;
}
/**
* Set the name of the database connection
*
* @param name The name of the database connection
* @return This object
* @since 1.0.0
*/
public DatabaseOptions type(String name) {
this.name = name;
return this;
}
/**
* Set the timeout of the connection
*
* @param timeout The max amount of time to connect
* @return This object
* @since 1.0.0
*/
public DatabaseOptions timeout(int timeout) {
this.timeout = timeout;
return this;
}
/**
* Build this class
*
* @return The database object
* @since 1.0.0
*/
public Database build() {
if (username.isEmpty()) {
username = "root";
}
return new Database(name, hostname, username, password, database, port, config);
}
}
}

View File

@ -0,0 +1,40 @@
package me.majrly.database;
import java.util.HashMap;
/**
* Apart of the database api to manage all your databases
*
* @author Majrly
* @since 1.0.0
*/
public class DatabaseManager {
private static HashMap<String, Database> databases = new HashMap<>();
/**
* Add a database to {@link #databases}
*
* @param database The database you want to add
* @since 1.0.0
*/
public static void addDatabase(Database database) {
databases.put(database.getName(), database);
}
/**
* Get a database with specified name from {@link #databases}
*
* @param name The name of the database you want to obtain
* @return The database wrapper
* @since 1.0.0
*/
public static Database getDatabase(String name) {
return databases.get(name);
}
// Getters
public static HashMap<String, Database> getDatabases() {
return databases;
}
}

View File

@ -0,0 +1,54 @@
package me.majrly.database.params;
/**
* Apart of the Database API to set parameters (AKA those little question marks in sql statements)
*
* @author Majrly
* @since 1.0.0
*/
public class Parameter {
// Variables
private Object data;
private Type type = Type.OBJECT;
/**
* Used to set parameters
*
* @param type The type of data you want sent
* @param data The data
* @since 1.0.0
*/
public Parameter(Type type, Object data) {
this.type = type;
this.data = data;
}
/**
* Used to set parameters
*
* @param data The object data
* @since 1.0.0
*/
public Parameter(Object data) {
this.data = data;
}
/**
* The type of data you want sent
*
* @author Majrly
* @since 1.0.0
*/
public enum Type {
STRING, BLOB, INTEGER, DOUBLE, FLOAT, DATE, LONG, BOOLEAN, OBJECT;
}
public Object getData() {
return data;
}
public Type getType() {
return type;
}
}

View File

@ -0,0 +1,14 @@
package me.majrly.database.statements;
/**
* Apart of the Database API to differentiate between various Statements
*
* @author Majrly
* @since 1.0.0
*/
public class Query extends Statement {
public Query(String sql) {
super(sql);
}
}

View File

@ -0,0 +1,120 @@
package me.majrly.database.statements;
import me.majrly.database.params.Parameter;
import java.sql.Blob;
import java.sql.Date;
import java.util.HashMap;
/**
* Apart of the Database API to create MySQL statements
*
* @author Majrly
* @since 1.0.0
*/
public class Statement {
// Variables
private String sql;
private int amount = 1;
private HashMap<Integer, Parameter> parameters = new HashMap<Integer, Parameter>();
/**
* Used to create SQL statements
*
* @param sql The SQL string
* @since 1.0.0
*/
public Statement(String sql) {
this.sql = sql;
}
/**
* Escape a string
*
* @param data The string you want to escape
* @since 1.0.0
*/
public void setString(String data) {
this.parameters.put(amount++, new Parameter(Parameter.Type.STRING, data));
}
/**
* Escape a string
*
* @param data The Blob you want to escape
* @since 1.0.0
*/
public void setBlob(Blob data) {
this.parameters.put(amount++, new Parameter(Parameter.Type.BLOB, data));
}
/**
* Escape a double
*
* @param data The double you want to escape
* @since 1.0.0
*/
public void setDouble(double data) {
this.parameters.put(amount++, new Parameter(Parameter.Type.DOUBLE, data));
}
/**
* Escape an integer
*
* @param data The integer you want to escape
* @since 1.0.0
*/
public void setInteger(int data) {
this.parameters.put(amount++, new Parameter(Parameter.Type.INTEGER, data));
}
/**
* Escape a float
*
* @param data The float you want to escape
* @since 1.0.0
*/
public void setFloat(float data) {
this.parameters.put(amount++, new Parameter(Parameter.Type.FLOAT, data));
}
/**
* Escape a date
*
* @param data The date you want to escape
* @since 1.0.0
*/
public void setDate(Date data) {
this.parameters.put(amount++, new Parameter(Parameter.Type.DATE, data));
}
/**
* Escape a boolean
*
* @param data The boolean you want to escape
* @since 1.0.0
*/
public void setBoolean(boolean data) {
this.parameters.put(amount++, new Parameter(Parameter.Type.BOOLEAN, data));
}
/**
* Escape an object
*
* @param data The object you want to escape
* @since 1.0.0
*/
public void setObject(Object data) {
this.parameters.put(amount++, new Parameter(Parameter.Type.OBJECT, data));
}
// Getters
public String getSQL() {
return sql;
}
public HashMap<Integer, Parameter> getParameters() {
return parameters;
}
}

View File

@ -0,0 +1,14 @@
package me.majrly.database.statements;
/**
* Apart of the Database API to differentiate between various Statements
*
* @author Majrly
* @since 1.0.0
*/
public class Update extends Statement {
public Update(String sql) {
super(sql);
}
}

View File

@ -6,7 +6,12 @@ import com.google.code.chatterbotapi.ChatterBotSession;
import com.google.code.chatterbotapi.ChatterBotType; import com.google.code.chatterbotapi.ChatterBotType;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import me.savvy.rixa.commands.admin.*; import me.majrly.database.Database;
import me.majrly.database.statements.Update;
import me.savvy.rixa.commands.admin.AddRoleCommand;
import me.savvy.rixa.commands.admin.BatchMoveCommand;
import me.savvy.rixa.commands.admin.ConfigCommand;
import me.savvy.rixa.commands.admin.RemoveRoleCommand;
import me.savvy.rixa.commands.general.*; import me.savvy.rixa.commands.general.*;
import me.savvy.rixa.commands.handlers.CommandExec; import me.savvy.rixa.commands.handlers.CommandExec;
import me.savvy.rixa.commands.handlers.CommandHandler; import me.savvy.rixa.commands.handlers.CommandHandler;
@ -14,9 +19,6 @@ import me.savvy.rixa.commands.mod.DeleteMessagesCommand;
import me.savvy.rixa.commands.mod.MuteCommand; import me.savvy.rixa.commands.mod.MuteCommand;
import me.savvy.rixa.commands.mod.PurgeMessagesCommand; import me.savvy.rixa.commands.mod.PurgeMessagesCommand;
import me.savvy.rixa.commands.mod.RaidModeCommand; import me.savvy.rixa.commands.mod.RaidModeCommand;
import me.savvy.rixa.data.database.Data;
import me.savvy.rixa.data.database.DataType;
import me.savvy.rixa.data.database.sql.DatabaseManager;
import me.savvy.rixa.data.filemanager.ConfigManager; import me.savvy.rixa.data.filemanager.ConfigManager;
import me.savvy.rixa.data.filemanager.LanguageManager; import me.savvy.rixa.data.filemanager.LanguageManager;
import me.savvy.rixa.events.BotEvent; import me.savvy.rixa.events.BotEvent;
@ -33,13 +35,11 @@ import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.JDABuilder; import net.dv8tion.jda.core.JDABuilder;
import net.dv8tion.jda.core.OnlineStatus; import net.dv8tion.jda.core.OnlineStatus;
import net.dv8tion.jda.core.entities.Game; import net.dv8tion.jda.core.entities.Game;
import net.dv8tion.jda.core.entities.Invite;
import net.dv8tion.jda.core.exceptions.RateLimitedException; import net.dv8tion.jda.core.exceptions.RateLimitedException;
import net.dv8tion.jda.core.hooks.AnnotatedEventManager; import net.dv8tion.jda.core.hooks.AnnotatedEventManager;
import javax.security.auth.login.LoginException; import javax.security.auth.login.LoginException;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
@ -48,11 +48,10 @@ import java.util.logging.Logger;
/** /**
* Created by Timber on 5/7/2017. * Created by Timber on 5/7/2017.
* Edited by Majr on 9/22/2017
*/ */
public class Rixa { public class Rixa {
@Getter
private static Data data;
@Getter @Getter
private static long timeUp; private static long timeUp;
@Getter @Getter
@ -61,37 +60,44 @@ public class Rixa {
private static List<JDA> shardsList; private static List<JDA> shardsList;
@Getter @Getter
private static ConfigManager config; private static ConfigManager config;
@Getter @Setter @Getter
private static DatabaseManager dbManager; @Setter
private static Database database;
private static ChatterBotFactory factory; private static ChatterBotFactory factory;
private static ChatterBotSession chatBotSession; private static ChatterBotSession chatBotSession;
private static ChatterBot chatBot; private static ChatterBot chatBot;
@Getter @Setter @Getter
@Setter
private LanguageManager languageManager; private LanguageManager languageManager;
@Getter @Setter @Getter
@Setter
private ScheduledExecutorService executorService; private ScheduledExecutorService executorService;
// String search = event.getMessage().getContent().substring(event.getMessage().getContent().indexOf(" ") + 1); // String search = event.getMessage().getContent().substring(event.getMessage().getContent().indexOf(" ") + 1);
public static void main(String[] args) { public static void main(String[] args) {
instance = new Rixa(); instance = new Rixa();
shardsList = new LinkedList<>(); shardsList = new LinkedList<>();
// config = new ConfigManager(); // config = new ConfigManager();
config = new ConfigManager(new File("Rixa/config.json")); config = new ConfigManager(new File("Rixa/config.json"));
load(); load();
} }
private static void load() { private static void load() {
getInstance().setExecutorService(Executors.newSingleThreadScheduledExecutor()); getInstance().setExecutorService(Executors.newSingleThreadScheduledExecutor());
dbManager = new DatabaseManager( database = Database.options()
String.valueOf(config.getJsonObject().getJSONObject("sql").getString("hostName")), .type("mysql")
String.valueOf(config.getJsonObject().getJSONObject("sql").getString("portNumber")), .hostname(String.valueOf(config.getJsonObject().getJSONObject("sql").getString("hostName")), Integer.valueOf(config.getJsonObject().getJSONObject("sql").getInt("portNumber")))
String.valueOf(config.getJsonObject().getJSONObject("sql").getString("databaseName")), .database(String.valueOf(config.getJsonObject().getJSONObject("sql").getString("databaseName")))
String.valueOf(config.getJsonObject().getJSONObject("sql").getString("userName")), .auth(String.valueOf(config.getJsonObject().getJSONObject("sql").getString("userName")), String.valueOf(config.getJsonObject().getJSONObject("sql").getString("password")))
String.valueOf(config.getJsonObject().getJSONObject("sql").getString("password"))); .build();
dbManager.createTable(); Update update = new Update("CREATE TABLE IF NOT EXISTS `core` (`guild_id` varchar(255) NOT NULL, `guild_name` varchar(255) NOT NULL, PRIMARY KEY (`guild_id`));");
database.send(update);
Update modules = new Update("CREATE TABLE IF NOT EXISTS `modules` (`guild_id` varchar(255) NOT NULL, `levels` varchar(255) NOT NULL, `enabled` INT(11) NOT NULL, PRIMARY KEY (`guild_id`));");
database.send(modules);
getInstance().setLanguageManager(new LanguageManager(new File("Rixa/languages/language.json"))); getInstance().setLanguageManager(new LanguageManager(new File("Rixa/languages/language.json")));
try { try {
int shards = 5; int shards = 5;
for(int i = 0; i < shards; i++) { for (int i = 0; i < shards; i++) {
Logger.getLogger("Rixa").info("Loading shard #" + i); Logger.getLogger("Rixa").info("Loading shard #" + i);
JDABuilder jda = new JDABuilder(AccountType.BOT) JDABuilder jda = new JDABuilder(AccountType.BOT)
.setToken(config.getJsonObject().getString("secretToken")) .setToken(config.getJsonObject().getString("secretToken"))
@ -112,32 +118,31 @@ public class Rixa {
e.printStackTrace(); e.printStackTrace();
} }
timeUp = System.currentTimeMillis(); timeUp = System.currentTimeMillis();
register(new CommandExec[] { register(new CommandExec[]{
new InfoCommand(), new ServerInfoCommand(), new HelpCommand(), new InfoCommand(), new ServerInfoCommand(), new HelpCommand(),
new DeleteMessagesCommand(), new PingCommand(), new PurgeMessagesCommand(), new DeleteMessagesCommand(), new PingCommand(), new PurgeMessagesCommand(),
new BatchMoveCommand(), new MuteCommand(), new MusicCommand(), new BatchMoveCommand(), new MuteCommand(), new MusicCommand(),
new ConfigCommand(), new UrbanDictionaryCommand(), new YoutubeCommand(), new ConfigCommand(), new UrbanDictionaryCommand(), new YoutubeCommand(),
new AddRoleCommand(), new RemoveRoleCommand(), new LevelsCommand(), new AddRoleCommand(), new RemoveRoleCommand(), new LevelsCommand(),
new LeaderboardCommand(), new RaidModeCommand()}); new LeaderboardCommand(), new RaidModeCommand()});
register(new React[] {new HelpReaction(), new ConfigReaction(), new LeaderboardReaction() }); register(new React[]{new HelpReaction(), new ConfigReaction(), new LeaderboardReaction()});
data = new Data(DataType.SQL);
try { try {
factory = new ChatterBotFactory(); factory = new ChatterBotFactory();
chatBot = factory.create(ChatterBotType.PANDORABOTS, "b0dafd24ee35a477"); chatBot = factory.create(ChatterBotType.PANDORABOTS, "b0dafd24ee35a477");
chatBotSession = chatBot.createSession(); chatBotSession = chatBot.createSession();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
private static void register(CommandExec commandExecs[]) { private static void register(CommandExec commandExecs[]) {
for (CommandExec command: commandExecs) { for (CommandExec command : commandExecs) {
CommandHandler.registerCommand(command); CommandHandler.registerCommand(command);
} }
} }
private static void register(React react[]) { private static void register(React react[]) {
for (React reaction: react) { for (React reaction : react) {
ReactionManager.registerReaction(reaction); ReactionManager.registerReaction(reaction);
} }
} }

View File

@ -1,75 +0,0 @@
package me.savvy.rixa.data.database;
import me.savvy.rixa.Rixa;
import me.savvy.rixa.data.database.sql.DatabaseManager;
import me.savvy.rixa.enums.Result;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* Created by Timber on 5/31/2017.
*
* This class will be used to grab and put data into databases (SQL, FlatFile)
*/
public class Data {
private DataType dataType;
private DatabaseManager db;
public Data(DataType dataType) {
this.dataType = dataType;
this.db = Rixa.getDbManager();
}
public Object get(String key, String value, String objToGet, String table) throws SQLException {
switch (dataType) {
case SQL:
// SELECT objToGet FROM table WHERE key = value.
PreparedStatement ps =
db.getConnection().prepareStatement("SELECT `" + objToGet + "` FROM `" + table + "` WHERE `" + key + "` = ?");
ps.setString(1, value);
return db.getObject(ps).getObject(objToGet);
default:
return null;
}
}
public void put(String key, String value) {
switch (dataType) {
}
}
public Result update(String table, String setting, String key, Object placeholder, Object placeholder2) {
switch (dataType) {
case SQL:
try {
PreparedStatement ps = db.getConnection().prepareStatement("UPDATE `" + table +"` SET `" + setting + "` = ? WHERE `" + key + "` = ?;");
ps.setObject(1, placeholder);
ps.setObject(2, placeholder2);
return db.executeUpdate(ps);
} catch (SQLException ex) {
ex.printStackTrace();
return Result.ERROR;
}
}
return Result.FALSE;
}
public void delete(String key, String value) {
switch (dataType) {
}
}
public Result exists(String check) {
switch(dataType) {
case SQL:
try {
return db.checkExists(check);
} catch (SQLException e) {
e.printStackTrace();
}
}
return Result.FALSE;
}
}

View File

@ -1,10 +0,0 @@
package me.savvy.rixa.data.database;
/**
* Created by Timber on 6/4/2017.
*/
public enum DataType {
SQL,
FLAT_FILE
}

View File

@ -1,138 +0,0 @@
package me.savvy.rixa.data.database.sql;
import me.savvy.rixa.Rixa;
import me.savvy.rixa.data.database.sql.mysql.mysql.MySQL;
import me.savvy.rixa.enums.Result;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DatabaseManager {
private Connection connection;
private MySQL MYSQL = null;
public DatabaseManager(String hostName, String port, String databaseName, String userName, String password) {
MYSQL = new MySQL(hostName, port, databaseName, userName, password);
}
public Connection getConnection() {
return connection;
}
public void createTable() {
checkConnection();
try {
PreparedStatement ps = connection.prepareStatement(
"CREATE TABLE IF NOT EXISTS `core` (`guild_id` varchar(255) NOT NULL, `guild_name` varchar(255) NOT NULL, PRIMARY KEY (`guild_id`));");
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
Rixa.getInstance().getLogger().severe("Could not check if table exists, stopping server.");
e.printStackTrace();
// Redirect to 500
}
}
private void checkConnection() {
try {
if (!MYSQL.checkConnection()) {
connection = MYSQL.openConnection();
Rixa.getInstance().getLogger().info("Mysql database connected");
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
public Result executeUpdate(PreparedStatement ps) throws SQLException {
checkConnection();
try {
ps.executeUpdate();
return Result.SUCCESS;
} catch (SQLException e) {
e.printStackTrace();
return Result.ERROR;
}
}
public Object getObject(String string, String objToGet) throws SQLException {
checkConnection();
PreparedStatement ps = connection.prepareStatement(string);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
return rs.getString(objToGet);
} else {
return null;
}
}
public ResultSet getObject(PreparedStatement ps) throws SQLException {
checkConnection();
ResultSet rs = ps.executeQuery();
if (rs.next()) {
return rs;
}
return null;
}
public ResultSet executeQuery(String query) {
checkConnection();
try {
PreparedStatement ps = connection.prepareStatement(query);
return ps.executeQuery();
} catch (SQLException ex) {
ex.printStackTrace();
}
return null;
}
public int getCount(String table) {
checkConnection();
try {
PreparedStatement preparedStatement = connection.prepareStatement("SELECT count(*) FROM '" + table + "';");
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return resultSet.getInt(1);
}
preparedStatement.close();
resultSet.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
return 0;
}
public Result checkExists(String string) throws SQLException {
checkConnection();
try {
PreparedStatement ps = connection.prepareStatement(string);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
rs.close();
return Result.TRUE;
} else {
rs.close();
return Result.FALSE;
}
} catch (SQLException e) {
return Result.ERROR;
}
}
public Result insert(String string) {
checkConnection();
try {
PreparedStatement preparedStatement = connection.prepareStatement(string);
preparedStatement.executeUpdate();
preparedStatement.close();
return Result.SUCCESS;
} catch (SQLException e) {
e.printStackTrace();
return Result.ERROR;
}
}
}

View File

@ -1,117 +0,0 @@
package me.savvy.rixa.data.database.sql.mysql;
import lombok.Getter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Abstract Database class, serves as a base for any connection method (MySQL,
* SQLite, etc.)
*
* @author -_Husky_-
* @author tips48
*/
public abstract class Database {
@Getter
protected Connection connection;
/**
* Creates a new Database
*
*/
protected Database() {
this.connection = null;
}
/**
* Opens a connection with the database
*
* @return Opened connection
* @throws SQLException
* if the connection can not be opened
* @throws ClassNotFoundException
* if the driver cannot be found
*/
protected abstract Connection openConnection() throws SQLException,
ClassNotFoundException;
/**
* Checks if a connection is open with the database
*
* @return true if the connection is open
* @throws SQLException
* if the connection cannot be checked
*/
public boolean checkConnection() throws SQLException {
return connection != null && !connection.isClosed();
}
/**
* Closes the connection with the database
*
* @return true if successful
* @throws SQLException
* if the connection cannot be closed
*/
public boolean closeConnection() throws SQLException {
if (connection == null) {
return false;
}
connection.close();
return true;
}
/**
* Executes a SQL Query<br>
*
* If the connection is closed, it will be opened
*
* @param query
* Query to be run
* @return the results of the query
* @throws SQLException
* If the query cannot be executed
* @throws ClassNotFoundException
* If the driver cannot be found; see {@link #openConnection()}
*/
public ResultSet querySQL(String query) throws SQLException,
ClassNotFoundException {
if (!checkConnection()) {
openConnection();
}
Statement statement = connection.createStatement();
return statement.executeQuery(query);
}
/**
* Executes an Update SQL Query<br>
* See {@link Statement#executeUpdate(String)}<br>
* If the connection is closed, it will be opened
*
* @param query
* Query to be run
* @return Result Code, see {@link Statement#executeUpdate(String)}
* @throws SQLException
* If the query cannot be executed
* @throws ClassNotFoundException
* If the driver cannot be found; see {@link #openConnection()}
*/
public int updateSQL(String query) throws SQLException,
ClassNotFoundException {
if (!checkConnection()) {
openConnection();
}
Statement statement = connection.createStatement();
return statement.executeUpdate(query);
}
}

View File

@ -1,80 +0,0 @@
package me.savvy.rixa.data.database.sql.mysql.mysql;
import me.savvy.rixa.data.database.sql.mysql.Database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* Connects to and uses a MySQL database
*
* @author -_Husky_-
* @author tips48
*/
public class MySQL extends Database {
private final String user;
private final String database;
private final String password;
private final String port;
private final String hostname;
/**
* Creates a new MySQL instance
*
* @param hostname
* Name of the host
* @param port
* Port number
* @param username
* Username
* @param password
* Password
*/
public MySQL(String hostname, String port, String username,
String password) {
this(hostname, port, null, username, password);
}
/**
* Creates a new MySQL instance for a specific database
*
* @param hostname
* Name of the host
* @param port
* Port number
* @param database
* Database name
* @param username
* Username
* @param password
* Password
*/
public MySQL(String hostname, String port, String database,
String username, String password) {
this.hostname = hostname;
this.port = port;
this.database = database;
this.user = username;
this.password = password;
}
@Override
public Connection openConnection() throws SQLException,
ClassNotFoundException {
if (checkConnection()) {
return connection;
}
String connectionURL = "jdbc:mysql://"
+ this.hostname + ":" + this.port;
if (database != null) {
connectionURL = connectionURL + "/" + this.database;
}
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(connectionURL,
this.user, this.password);
return connection;
}
}

View File

@ -2,9 +2,11 @@ package me.savvy.rixa.guild;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import me.majrly.database.Database;
import me.majrly.database.statements.Query;
import me.majrly.database.statements.Update;
import me.savvy.rixa.Rixa; import me.savvy.rixa.Rixa;
import me.savvy.rixa.commands.handlers.RixaPermission; import me.savvy.rixa.commands.handlers.RixaPermission;
import me.savvy.rixa.data.database.sql.DatabaseManager;
import me.savvy.rixa.enums.Result; import me.savvy.rixa.enums.Result;
import me.savvy.rixa.guild.management.GuildSettings; import me.savvy.rixa.guild.management.GuildSettings;
import me.savvy.rixa.modules.levels.LevelsModule; import me.savvy.rixa.modules.levels.LevelsModule;
@ -15,41 +17,47 @@ import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.Role; import net.dv8tion.jda.core.entities.Role;
import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.entities.User;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** /**
* Created by Timber on 5/23/2017. * Created by Timber on 5/23/2017.
* Edited by Majr on 9/22/2017
*/ */
public class RixaGuild { public class RixaGuild {
@Getter private Guild guild; @Getter
private DatabaseManager db; private Guild guild;
@Setter private GuildSettings guildSettings; private Database db;
@Getter @Setter private MusicModule musicModule; @Setter
@Getter @Setter private TwitterModule twitterModule; private GuildSettings guildSettings;
@Getter private List<String> mutedMembers = new ArrayList<>(); @Getter
@Getter @Setter private LevelsModule levelsModule; @Setter
private MusicModule musicModule;
@Getter
@Setter
private TwitterModule twitterModule;
@Getter
private List<String> mutedMembers = new ArrayList<>();
@Getter
@Setter
private LevelsModule levelsModule;
public RixaGuild(Guild guild) { public RixaGuild(Guild guild) {
this.guild = guild; this.guild = guild;
this.db = Rixa.getDbManager(); this.db = Rixa.getDatabase();
setMusicModule(new MusicModule(guild)); setMusicModule(new MusicModule(guild));
setLevelsModule(new LevelsModule(this)); setLevelsModule(new LevelsModule(this));
load(); load();
} }
private void load() { private void load() {
if(!(checkExists())) { if (!(checkExists())) {
Rixa.getDbManager() Update update = new Update("INSERT INTO `core` (`guild_id`, `guild_name`, `description`, `keywords`) VALUES (?, ?, 'Description not set.', 'No Keywords Found.')");
.insert("INSERT INTO `core` (`guild_id`, `guild_name`, `description`, `keywords`) VALUES ('%id%', '%name%', 'Description not set.', 'No Keywords Found.')" update.setString(guild.getId());
.replace("%id%", guild.getId()) update.setString(guild.getName());
.replace("%name%", guild.getName().replace("'", "\\'"))); db.send(update);
} }
setGuildSettings(new GuildSettings(this.guild)); setGuildSettings(new GuildSettings(this.guild));
addGuild(this); addGuild(this);
@ -61,21 +69,35 @@ public class RixaGuild {
private boolean checkExists() { private boolean checkExists() {
Result r = Result.ERROR; Result r = Result.ERROR;
try { try {
r = Rixa.getDbManager().checkExists("SELECT `guild_name` FROM `core` WHERE `guild_id` = '" + guild.getId() + "';"); Query query = new Query("SELECT `guild_name` FROM `core` WHERE `guild_id` = '" + guild.getId() + "';");
Optional<?> optional = db.send(query);
if (!optional.isPresent()) r = Result.ERROR;
if (!(optional.get() instanceof ResultSet)) r = Result.ERROR;
if (r != Result.ERROR) {
ResultSet set = (ResultSet) optional.get();
if (set.next()) {
r = Result.TRUE;
} else {
r = Result.FALSE;
}
set.close();
}
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
return r == Result.TRUE; return r == Result.TRUE;
} }
public boolean hasPermission(Member member, RixaPermission permission) { public boolean hasPermission(Member member, RixaPermission permission) {
if(Rixa.getConfig().getJsonObject().getJSONArray("botAdmins").toList().contains(member.getUser().getId()) || if (Rixa.getConfig().getJsonObject().getJSONArray("botAdmins").toList().contains(member.getUser().getId()) ||
member.getUser().getId().equals(guild.getOwner().getUser().getId())) { member.getUser().getId().equals(guild.getOwner().getUser().getId())) {
return true; return true;
} }
for(Role role: member.getRoles()) { for (Role role : member.getRoles()) {
if(hasPermission(role, permission)) { if (hasPermission(role, permission)) {
return true; return true;
} }
} }
@ -83,21 +105,20 @@ public class RixaGuild {
} }
public boolean hasPermission(Role role, RixaPermission permission) { public boolean hasPermission(Role role, RixaPermission permission) {
if(!permissionExists(role)) { if (!permissionExists(role)) {
return false; return false;
} }
boolean b = false; boolean b = false;
try { try {
PreparedStatement ps = Query query = new Query("SELECT `" + permission.toString().toUpperCase() + "` FROM `permissions` WHERE `role_id` = ?");
db.getConnection().prepareStatement query.setString(role.getId());
("SELECT `" + permission.toString().toUpperCase() + "` FROM `permissions` WHERE `role_id` = ?"); Optional<?> optional = db.send(query);
ps.setString(1, role.getId()); if (!optional.isPresent()) return b;
ResultSet rs = db.getObject(ps); if (!(optional.get() instanceof ResultSet)) return b;
ResultSet set = (ResultSet) optional.get();
b = rs.getBoolean(permission.toString().toUpperCase()); b = set.getBoolean(permission.toString().toUpperCase());
ps.close(); set.close();
rs.close();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -105,33 +126,41 @@ public class RixaGuild {
} }
public void setPermission(Role role, RixaPermission permission, boolean value) { public void setPermission(Role role, RixaPermission permission, boolean value) {
if(!permissionExists(role)) { if (!permissionExists(role)) {
db Update update = new Update("INSERT INTO `permissions` " +
.insert("INSERT INTO `permissions` " + "(`role_id`, `guild_id`, `MUTE`, `ADD_ROLE`, `REMOVE_ROLE`, `CLEAR_CHAT`, " +
"(`role_id`, `guild_id`, `MUTE`, `ADD_ROLE`, `REMOVE_ROLE`, `CLEAR_CHAT`, " + "`ACCESS_CONFIG`, `PM_MESSAGE`, `KICK_MEMBER`, `BAN_MEMBER`)" +
"`ACCESS_CONFIG`, `PM_MESSAGE`, `KICK_MEMBER`, `BAN_MEMBER`)" + " VALUES (?, ?, '0', '0', '0', '0', '0', '0', '0', '0');");
" VALUES ('" + role.getId() + "', '" + guild.getId() + "', '0', '0', '0', '0', '0', '0', '0', '0');"); update.setString(role.getId());
} update.setString(guild.getId());
try { db.send(update);
PreparedStatement ps = db.getConnection().prepareStatement
("UPDATE `permissions` SET `" + permission.toString().toUpperCase() + "` = ? WHERE `guild_id` = ? AND `role_id` = ?;");
ps.setBoolean(1, value);
ps.setString(2, guild.getId());
ps.setString(3, role.getId());
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} }
Update update = new Update("UPDATE `permissions` SET `" + permission.toString().toUpperCase() + "` = ? WHERE `guild_id` = ? AND `role_id` = ?;");
update.setBoolean(value);
update.setString(guild.getId());
update.setString(role.getId());
db.send(update);
} }
private boolean permissionExists(Role role) { private boolean permissionExists(Role role) {
ResultSet rs = db.executeQuery Query query = new Query("SELECT `" + RixaPermission.values()[0] + "` FROM `permissions` WHERE `guild_id` = ? AND `role_id` = ?");
("SELECT `" + RixaPermission.values()[0] + "` FROM `permissions` WHERE `guild_id` = '" + guild.getId() + "' AND `role_id` = '" + role.getId() + "'"); query.setString(guild.getId());
query.setString(role.getId());
Optional<?> optional = db.send(query);
if (!optional.isPresent()) return false;
if (!(optional.get() instanceof ResultSet)) return false;
ResultSet set = (ResultSet) optional.get();
try { try {
return rs.next(); return set.next();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
return false; return false;
} finally {
try {
set.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
} }
@ -144,27 +173,27 @@ public class RixaGuild {
} }
public void muteMember(User user) { public void muteMember(User user) {
if(!isUserMuted(user)) if (!isUserMuted(user))
mutedMembers.add(user.getId()); mutedMembers.add(user.getId());
} }
@Getter @Getter
private static Map<String, RixaGuild> guilds = new HashMap<>(); private static Map<String, RixaGuild> guilds = new HashMap<>();
private static void addGuild(RixaGuild guild) { private static void addGuild(RixaGuild guild) {
if(check(guild.getGuild())) return; if (check(guild.getGuild())) return;
guilds.put(guild.getGuild().getId(), guild); guilds.put(guild.getGuild().getId(), guild);
} }
public static RixaGuild getGuild(Guild guild) { public static RixaGuild getGuild(Guild guild) {
if(!check(guild)) { if (!check(guild)) {
addGuild(new RixaGuild(guild)); addGuild(new RixaGuild(guild));
} }
return guilds.get(guild.getId()); return guilds.get(guild.getId());
} }
public static void removeGuild(RixaGuild guild) { public static void removeGuild(RixaGuild guild) {
if(!check(guild.getGuild())) return; if (!check(guild.getGuild())) return;
guilds.remove(guild.getGuild().getId()); guilds.remove(guild.getGuild().getId());
} }

View File

@ -2,14 +2,16 @@ package me.savvy.rixa.guild.management;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import me.majrly.database.statements.Query;
import me.majrly.database.statements.Update;
import me.savvy.rixa.Rixa; import me.savvy.rixa.Rixa;
import me.savvy.rixa.enums.Result; import me.savvy.rixa.enums.Result;
import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.TextChannel; import net.dv8tion.jda.core.entities.TextChannel;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Optional;
import java.util.TimerTask; import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -26,8 +28,12 @@ public class GuildSettings {
private String prefix = "/", defaultRole, muteRole, joinMessage, quitMessage, joinPrivateMessage, description; private String prefix = "/", defaultRole, muteRole, joinMessage, quitMessage, joinPrivateMessage, description;
@Getter @Getter
private TextChannel joinMessageChannel, quitMessageChannel; private TextChannel joinMessageChannel, quitMessageChannel;
@Getter @Setter Guild.VerificationLevel defaultVerificationLevel; @Getter
@Getter @Setter long lastJoin; @Setter
Guild.VerificationLevel defaultVerificationLevel;
@Getter
@Setter
long lastJoin;
private boolean raidMode; private boolean raidMode;
public GuildSettings(Guild guild) { public GuildSettings(Guild guild) {
@ -40,17 +46,20 @@ public class GuildSettings {
} }
private void load() throws SQLException { private void load() throws SQLException {
if(!checkExists()) { if (!checkExists()) {
Rixa.getDbManager().insert("INSERT INTO `settings` (`guild_id`, `log_enabled`, `log_channel`, `joinMessage`, `quitMessage`, `greetings`, `farewell`," + Update update = new Update("INSERT INTO `settings` (`guild_id`, `log_enabled`, `log_channel`, `joinMessage`, `quitMessage`, `greetings`, `farewell`," +
" `prefix`, `joinPm`, `joinVerification`, `defaultRole`, `muteRole`)" + " `prefix`, `joinPm`, `joinVerification`, `defaultRole`, `muteRole`)" +
" VALUES ('" + guild.getId() + "', '0', 'default_value', 'default_value', 'default_value', 'default_value', 'default_value', '/'," + " VALUES ('" + guild.getId() + "', '0', 'default_value', 'default_value', 'default_value', 'default_value', 'default_value', '/'," +
" 'default', '0', 'default_value', 'default_value');"); " 'default', '0', 'default_value', 'default_value');");
Rixa.getDatabase().send(update);
return; return;
} }
PreparedStatement ps = Rixa.getDbManager() Query query = new Query("SELECT * FROM `settings` WHERE `guild_id` = ?");
.getConnection().prepareStatement("SELECT * FROM `settings` WHERE `guild_id` = ?"); query.setString(guild.getId());
ps.setString(1, guild.getId()); Optional<?> optional = Rixa.getDatabase().send(query);
ResultSet set = Rixa.getDbManager().getObject(ps); if (!optional.isPresent()) return;
if (!(optional.get() instanceof ResultSet)) return;
ResultSet set = (ResultSet) optional.get();
this.prefix = (set.getString("prefix")); this.prefix = (set.getString("prefix"));
this.defaultRole = (set.getString("defaultRole")); this.defaultRole = (set.getString("defaultRole"));
this.joinMessage = (set.getString("joinMessage")); this.joinMessage = (set.getString("joinMessage"));
@ -58,28 +67,44 @@ public class GuildSettings {
this.joinPrivateMessage = (set.getString("joinPM")); this.joinPrivateMessage = (set.getString("joinPM"));
this.muteRole = (set.getString("muteRole")); this.muteRole = (set.getString("muteRole"));
this.joinVerification = (set.getBoolean("joinVerification")); this.joinVerification = (set.getBoolean("joinVerification"));
if(!set.getString("greetings").equalsIgnoreCase("default_value")) { if (!set.getString("greetings").equalsIgnoreCase("default_value")) {
joinMessageChannel = guild.getTextChannelById(set.getString("greetings")); joinMessageChannel = guild.getTextChannelById(set.getString("greetings"));
} }
if(!set.getString("farewell").equalsIgnoreCase("default_value")) { if (!set.getString("farewell").equalsIgnoreCase("default_value")) {
quitMessageChannel = guild.getTextChannelById(set.getString("farewell")); quitMessageChannel = guild.getTextChannelById(set.getString("farewell"));
} }
ps = Rixa.getDbManager() query = new Query("SELECT * FROM `core` WHERE `guild_id` = ?");
.getConnection().prepareStatement("SELECT * FROM `core` WHERE `guild_id` = ?"); query.setString(guild.getId());
ps.setString(1, guild.getId()); optional = Rixa.getDatabase().send(query);
set = Rixa.getDbManager().getObject(ps); if (!optional.isPresent()) return;
if (!(optional.get() instanceof ResultSet)) return;
set = (ResultSet) optional.get();
this.description = (set.getString("description")); this.description = (set.getString("description"));
this.enlisted = (set.getBoolean("enlisted")); this.enlisted = (set.getBoolean("enlisted"));
this.raidMode = false; this.raidMode = false;
} }
private boolean checkExists() { private boolean checkExists() {
Result r = Result.FALSE;
try { try {
return Rixa.getDbManager().checkExists("SELECT `guild_id` FROM `settings` WHERE `guild_id` = '" + guild.getId() + "'") == Result.TRUE; Query query = new Query("SELECT `guild_id` FROM `settings` WHERE `guild_id` = '" + guild.getId() + "'");
Optional<?> optional = Rixa.getDatabase().send(query);
if (!optional.isPresent()) r = Result.ERROR;
if (!(optional.get() instanceof ResultSet)) r = Result.ERROR;
ResultSet set = (ResultSet) optional.get();
if (r != Result.ERROR) {
if (set.next()) {
r = Result.TRUE;
} else {
r = Result.FALSE;
}
}
set.close();
return r == Result.TRUE;
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
return false;
} }
return false;
} }
public void unload() { public void unload() {
@ -88,67 +113,74 @@ public class GuildSettings {
public void setJoinMessage(String joinMessage) { public void setJoinMessage(String joinMessage) {
this.joinMessage = joinMessage; this.joinMessage = joinMessage;
Rixa.getData().update("settings", "joinMessage", "guild_id", joinMessage, guild.getId()); update("settings", "joinMessage", "guild_id", joinMessage, guild.getId());
} }
public void setQuitMessage(String quitMessage) { public void setQuitMessage(String quitMessage) {
this.quitMessage = quitMessage; this.quitMessage = quitMessage;
Rixa.getData().update("settings", "quitMessage", "guild_id", quitMessage, guild.getId()); update("settings", "quitMessage", "guild_id", quitMessage, guild.getId());
} }
public void setJoinPrivateMessage(String joinPrivateMessage) { public void setJoinPrivateMessage(String joinPrivateMessage) {
this.joinPrivateMessage = joinPrivateMessage; this.joinPrivateMessage = joinPrivateMessage;
Rixa.getData().update("settings", "joinPM", "guild_id", joinPrivateMessage, guild.getId()); update("settings", "joinPM", "guild_id", joinPrivateMessage, guild.getId());
} }
public void setJoinMessageChannel(TextChannel joinMessageChannel) { public void setJoinMessageChannel(TextChannel joinMessageChannel) {
this.joinMessageChannel = joinMessageChannel; this.joinMessageChannel = joinMessageChannel;
Rixa.getData().update("settings", "greetings", "guild_id", joinMessageChannel.getId(), guild.getId()); update("settings", "greetings", "guild_id", joinMessageChannel.getId(), guild.getId());
} }
public void setJoinMessageChannel(String joinMessageChannel) { public void setJoinMessageChannel(String joinMessageChannel) {
if (joinMessageChannel.equalsIgnoreCase("default_value"))this.joinMessageChannel = null; if (joinMessageChannel.equalsIgnoreCase("default_value")) this.joinMessageChannel = null;
Rixa.getData().update("settings", "greetings", "guild_id", joinMessageChannel, guild.getId()); update("settings", "greetings", "guild_id", joinMessageChannel, guild.getId());
}
private void update(String table, String setting, String key, Object placeholder, Object placeholder2) {
Update update = new Update("UPDATE `" + table + "` SET `" + setting + "` = ? WHERE `" + key + "` = ?;");
update.setObject(placeholder);
update.setObject(placeholder2);
Rixa.getDatabase().send(update);
} }
public void setQuitMessageChannel(TextChannel quitMessageChannel) { public void setQuitMessageChannel(TextChannel quitMessageChannel) {
this.quitMessageChannel = quitMessageChannel; this.quitMessageChannel = quitMessageChannel;
Rixa.getData().update("settings", "farewell", "guild_id", quitMessageChannel.getId(), guild.getId()); update("settings", "farewell", "guild_id", quitMessageChannel.getId(), guild.getId());
} }
public void setQuitMessageChannel(String quitMessageChannel) { public void setQuitMessageChannel(String quitMessageChannel) {
if (quitMessageChannel.equalsIgnoreCase("default_value"))this.quitMessageChannel = null; if (quitMessageChannel.equalsIgnoreCase("default_value")) this.quitMessageChannel = null;
Rixa.getData().update("settings", "greetings", "guild_id", quitMessageChannel, guild.getId()); update("settings", "greetings", "guild_id", quitMessageChannel, guild.getId());
} }
public void setDefaultRole(String defaultRole) { public void setDefaultRole(String defaultRole) {
this.defaultRole = defaultRole; this.defaultRole = defaultRole;
Rixa.getData().update("settings", "defaultRole", "guild_id", defaultRole, guild.getId()); update("settings", "defaultRole", "guild_id", defaultRole, guild.getId());
} }
public void setPrefix(String prefix) { public void setPrefix(String prefix) {
this.prefix = prefix; this.prefix = prefix;
Rixa.getData().update("settings", "prefix", "guild_id", prefix, guild.getId()); update("settings", "prefix", "guild_id", prefix, guild.getId());
} }
public void setDescription(String description) { public void setDescription(String description) {
this.description = description; this.description = description;
Rixa.getData().update("core", "description", "guild_id", description, guild.getId()); update("core", "description", "guild_id", description, guild.getId());
} }
public void setEnlisted(boolean enlisted) { public void setEnlisted(boolean enlisted) {
this.enlisted = enlisted; this.enlisted = enlisted;
Rixa.getData().update("core", "enlisted", "guild_id", enlisted, guild.getId()); update("core", "enlisted", "guild_id", enlisted, guild.getId());
} }
public void setMuteRole(String muteRole) { public void setMuteRole(String muteRole) {
this.muteRole = muteRole; this.muteRole = muteRole;
Rixa.getData().update("settings", "muteRole", "guild_id", muteRole, guild.getId()); update("settings", "muteRole", "guild_id", muteRole, guild.getId());
} }
public void setJoinVerification(boolean joinVerification) { public void setJoinVerification(boolean joinVerification) {
this.joinVerification = joinVerification; this.joinVerification = joinVerification;
Rixa.getData().update("settings", "joinVerification", "guild_id", joinVerification, guild.getId()); update("settings", "joinVerification", "guild_id", joinVerification, guild.getId());
} }
public void startRaidMode() { public void startRaidMode() {
@ -170,7 +202,7 @@ public class GuildSettings {
@Override @Override
public void run() { public void run() {
if (isRaidMode()) { if (isRaidMode()) {
endRaidMode(); endRaidMode();
} }
this.cancel(); this.cancel();
} }

View File

@ -1,25 +1,31 @@
package me.savvy.rixa.guild.user; package me.savvy.rixa.guild.user;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import me.majrly.database.statements.Query;
import me.majrly.database.statements.Update;
import me.savvy.rixa.Rixa; import me.savvy.rixa.Rixa;
import me.savvy.rixa.enums.Result; import me.savvy.rixa.enums.Result;
import me.savvy.rixa.guild.RixaGuild; import me.savvy.rixa.guild.RixaGuild;
import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.User; import net.dv8tion.jda.core.entities.User;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.*; import java.util.Optional;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
/** /**
* Created by savit on 7/14/2017. * Created by savit on 7/14/2017.
*/ */
public class UserData { public class UserData {
@Getter private final Guild guild; @Getter
@Getter private User user; private final Guild guild;
@Getter private int experience; @Getter
private User user;
@Getter
private int experience;
private boolean awardedLast; private boolean awardedLast;
private Random random; private Random random;
@ -37,21 +43,21 @@ public class UserData {
} }
private void load() { private void load() {
if(!checkExists()) { if (!checkExists()) {
insert(); insert();
setExperience(0); setExperience(0);
return; return;
} }
String query = "SELECT * FROM `%s` WHERE `%s` = '%s' AND `%s` = '%s';"; try {
PreparedStatement ps; Query query = new Query("SELECT * FROM `levels` WHERE `guild_id` = ? AND `user_id` = ?;");
ResultSet rs; query.setString("levels");
try { query.setString(guild.getId());
ps = Rixa.getDbManager().getConnection().prepareStatement(String.format query.setString(user.getId());
(query, "levels", "guild_id", Optional<?> optional = Rixa.getDatabase().send(query);
guild.getId(), "user_id", if (!optional.isPresent()) return;
user.getId())); if (!(optional.get() instanceof ResultSet)) return;
rs = Rixa.getDbManager().getObject(ps); ResultSet set = (ResultSet) optional.get();
setExperience(rs.getInt("experience")); setExperience(set.getInt("experience"));
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -62,7 +68,7 @@ public class UserData {
} }
public boolean awardIfCan() { public boolean awardIfCan() {
if(awardedLast) { if (awardedLast) {
return false; return false;
} }
int amountAdding = getRandom(); int amountAdding = getRandom();
@ -103,39 +109,46 @@ public class UserData {
} }
private boolean checkExists() { private boolean checkExists() {
String query = "SELECT `%s` FROM `%s` WHERE `%s` = '%s' AND `%s` = '%s';"; Result r = Result.FALSE;
Result r;
try { try {
r = Rixa.getDbManager().checkExists(String.format Query query = new Query("SELECT `user_id` FROM `levels` WHERE `guild_id` = ? AND `user_id` = ?;");
(query, "user_id", "levels", "guild_id", query.setString(guild.getId());
guild.getId(), "user_id", query.setString(user.getId());
user.getId())); Optional<?> optional = Rixa.getDatabase().send(query);
return r == Result.TRUE; if (!optional.isPresent()) r = Result.ERROR;
if (!(optional.get() instanceof ResultSet)) r = Result.ERROR;
ResultSet set = (ResultSet) optional.get();
if (r != Result.ERROR) {
if (set.next()) {
r = Result.TRUE;
} else {
r = Result.FALSE;
}
}
set.close();
return r == Result.TRUE;
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
return false;
} }
return false;
} }
private void insert() { private void insert() {
String query = "INSERT INTO `%s` (`%s`,`%s`,`%s`) VALUES ('%s', '%s', '%s');"; Update update = new Update("INSERT INTO `levels` (guild_id, user_id, experience) VALUES (?, ?, ?);");
Rixa.getDbManager() update.setString(guild.getId());
.insert(String.format(query, "levels", "guild_id", "user_id", "experience", update.setString(user.getId());
guild.getId(), user.getId(), "0")); update.setInteger(0);
Rixa.getDatabase().send(update);
} }
private void setExperience(int experience) { private void setExperience(int experience) {
this.experience = experience; this.experience = experience;
String query = "UPDATE `%s` SET `%s` = '%s' WHERE `%s` = '%s' AND `%s` = '%s';"; String query = "UPDATE `levels` SET `experience` = ? WHERE `guild_id` = ? AND `user_id` = ?;";
try { Update update = new Update(query);
PreparedStatement ps = Rixa.getDbManager().getConnection().prepareStatement(String.format update.setInteger(experience);
(query, "levels", "experience", experience, "guild_id", update.setString(guild.getId());
guild.getId(), "user_id", update.setString(user.getId());
user.getId())); Rixa.getDatabase().send(update);
Rixa.getDbManager().executeUpdate(ps);
} catch (SQLException e) {
e.printStackTrace();
}
} }
private int getRandom() { private int getRandom() {

View File

@ -14,34 +14,34 @@ public class RixaAudioReceiveHandler implements AudioReceiveHandler {
private Guild guild; private Guild guild;
public void start(Guild guild, VoiceChannel channel){ public void start(Guild guild, VoiceChannel channel) {
this.guild = guild; this.guild = guild;
AudioManager manager = guild.getAudioManager(); AudioManager manager = guild.getAudioManager();
manager.openAudioConnection(channel); manager.openAudioConnection(channel);
manager.setReceivingHandler(this); manager.setReceivingHandler(this);
} }
@Override @Override
public boolean canReceiveCombined() { public boolean canReceiveCombined() {
//Lets JDA know that it's OK to send audio to this class //Lets JDA know that it's OK to send audio to this class
return true; return true;
} }
@Override @Override
public boolean canReceiveUser() { public boolean canReceiveUser() {
//Lets JDA know that it's OK to send audio to this class //Lets JDA know that it's OK to send audio to this class
return true; return true;
} }
@Override @Override
public void handleCombinedAudio(CombinedAudio audio) { public void handleCombinedAudio(CombinedAudio audio) {
//This will give you audio from all users, packet by packet. //This will give you audio from all users, packet by packet.
//You can do with this whatever you want, pass it onto a sending handler, write it to a file etc //You can do with this whatever you want, pass it onto a sending handler, write it to a file etc
} }
@Override @Override
public void handleUserAudio(UserAudio audio) { public void handleUserAudio(UserAudio audio) {
//This will give you audio from a single user, packet by packet //This will give you audio from a single user, packet by packet
guild.getTextChannelById("301790750327308290").sendMessage(audio.getUser().getAsMention() + " is talking").queue(); guild.getTextChannelById("301790750327308290").sendMessage(audio.getUser().getAsMention() + " is talking").queue();
} }
} }

View File

@ -1,12 +1,15 @@
package me.savvy.rixa.modules.levels; package me.savvy.rixa.modules.levels;
import lombok.Getter; import lombok.Getter;
import me.majrly.database.Database;
import me.majrly.database.statements.Query;
import me.majrly.database.statements.Update;
import me.savvy.rixa.Rixa; import me.savvy.rixa.Rixa;
import me.savvy.rixa.data.database.sql.DatabaseManager;
import me.savvy.rixa.enums.Result; import me.savvy.rixa.enums.Result;
import me.savvy.rixa.guild.RixaGuild; import me.savvy.rixa.guild.RixaGuild;
import me.savvy.rixa.guild.user.UserData; import me.savvy.rixa.guild.user.UserData;
import me.savvy.rixa.modules.RixaModule; import me.savvy.rixa.modules.RixaModule;
import me.savvy.rixa.utils.DatabaseUtils;
import me.savvy.rixa.utils.MessageBuilder; import me.savvy.rixa.utils.MessageBuilder;
import net.dv8tion.jda.core.entities.Member; import net.dv8tion.jda.core.entities.Member;
@ -20,9 +23,12 @@ import java.util.*;
*/ */
public class LevelsModule implements RixaModule { public class LevelsModule implements RixaModule {
@Getter private final RixaGuild rixaGuild; @Getter
@Getter private Map<String, UserData> userData = new HashMap<>(); private final RixaGuild rixaGuild;
@Getter private boolean enabled; @Getter
private Map<String, UserData> userData = new HashMap<>();
@Getter
private boolean enabled;
public LevelsModule(RixaGuild rixaGuild) { public LevelsModule(RixaGuild rixaGuild) {
this.rixaGuild = rixaGuild; this.rixaGuild = rixaGuild;
@ -30,14 +36,19 @@ public class LevelsModule implements RixaModule {
load(); load();
} }
private List<UserData> leaderboard(Member member) { private List<UserData> leaderboard(Member member) {
DatabaseManager db = Rixa.getDbManager(); Database db = Rixa.getDatabase();
ResultSet rs = db.executeQuery(String.format ResultSet rs = null;
("SELECT * FROM `levels` WHERE `guild_id` = '%s' ORDER BY `experience` DESC;", member.getGuild().getId()));
try {
rs = db.getConnection().get().prepareStatement(String.format("SELECT * FROM `levels` WHERE `guild_id` = '%s' ORDER BY `experience` DESC;", member.getGuild().getId())).executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
List<UserData> userDataList = new LinkedList<>(); List<UserData> userDataList = new LinkedList<>();
try { try {
while (rs.next()) { while (rs != null && rs.next()) {
if (member.getGuild().getMemberById(rs.getString("user_id")) == null) continue; if (member.getGuild().getMemberById(rs.getString("user_id")) == null) continue;
UserData userData = rixaGuild.getLevelsModule().getUserData(rs.getString("user_id")); UserData userData = rixaGuild.getLevelsModule().getUserData(rs.getString("user_id"));
userDataList.add(userData); userDataList.add(userData);
@ -52,7 +63,7 @@ public class LevelsModule implements RixaModule {
public MessageBuilder leaderboard(Member member, int page) { public MessageBuilder leaderboard(Member member, int page) {
int sizePerPage = 10; int sizePerPage = 10;
if(page < 1) { if (page < 1) {
page = 1; page = 1;
} }
List<UserData> userData = leaderboard(member); List<UserData> userData = leaderboard(member);
@ -71,7 +82,7 @@ public class LevelsModule implements RixaModule {
if (user == null) continue; if (user == null) continue;
stringBuilder stringBuilder
.append("`") .append("`")
.append( i + start + 1/*(page > 1) ? ((i + 1) * 10) : i + 1*/) .append(i + start + 1/*(page > 1) ? ((i + 1) * 10) : i + 1*/)
.append(")` ") .append(")` ")
.append( .append(
user.getUser().getName()) user.getUser().getName())
@ -124,10 +135,12 @@ public class LevelsModule implements RixaModule {
PreparedStatement ps = null; PreparedStatement ps = null;
ResultSet rs = null; ResultSet rs = null;
try { try {
ps = Rixa.getDbManager().getConnection().prepareStatement(query); ps = Rixa.getDatabase().getConnection().get().prepareStatement(query);
ps.setString(1, getRixaGuild().getGuild().getId()); ps.setString(1, getRixaGuild().getGuild().getId());
rs = Rixa.getDbManager().getObject(ps); rs = ps.executeQuery();
this.enabled = rs.getBoolean("levels"); if (rs.next()) {
this.enabled = rs.getBoolean("levels");
}
ps.close(); ps.close();
rs.close(); rs.close();
} catch (SQLException e) { } catch (SQLException e) {
@ -136,25 +149,38 @@ public class LevelsModule implements RixaModule {
} }
private boolean checkExists() { private boolean checkExists() {
String query = "SELECT `%s` FROM `%s` WHERE `%s` = '%s';"; Result r = Result.FALSE;
Result r = Result.ERROR;
try { try {
r = Rixa.getDbManager().checkExists(String.format Query query = new Query("SELECT `guild_id` FROM `modules` WHERE `guild_id` = ?;");
(query, "guild_id", "modules", "guild_id", rixaGuild.getGuild().getId())); query.setString(rixaGuild.getGuild().getId());
Optional<?> optional = Rixa.getDatabase().send(query);
if (!optional.isPresent()) r = Result.ERROR;
if (!(optional.get() instanceof ResultSet)) r = Result.ERROR;
ResultSet set = (ResultSet) optional.get();
if (r != Result.ERROR) {
if (set.next()) {
r = Result.TRUE;
} else {
r = Result.FALSE;
}
}
set.close();
return r == Result.TRUE;
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
return false;
} }
return r == Result.TRUE;
} }
private void insert() { private void insert() {
String query = "INSERT INTO `%s` (`%s`) VALUES ('%s');"; String query = "INSERT INTO `modules` (`guild_id`) VALUES (?);";
Rixa.getDbManager() Update update = new Update(query);
.insert(String.format(query, "modules", "guild_id", rixaGuild.getGuild().getId())); update.setString(rixaGuild.getGuild().getId());
Rixa.getDatabase().send(update);
} }
public void setEnabled(boolean enabled) { public void setEnabled(boolean enabled) {
this.enabled = enabled; this.enabled = enabled;
Rixa.getData().update("modules", "levels", "guild_id", enabled, rixaGuild.getGuild().getId()); DatabaseUtils.update("modules", "levels", "guild_id", enabled, rixaGuild.getGuild().getId());
} }
} }

View File

@ -22,6 +22,7 @@ public class MusicManager {
/** /**
* Creates a player and a track scheduler. * Creates a player and a track scheduler.
*
* @param manager Audio player manager to use for creating the player. * @param manager Audio player manager to use for creating the player.
*/ */
public MusicManager(AudioPlayerManager manager) { public MusicManager(AudioPlayerManager manager) {

View File

@ -1,21 +1,25 @@
package me.savvy.rixa.modules.music; package me.savvy.rixa.modules.music;
import lombok.Getter; import lombok.Getter;
import me.majrly.database.Database;
import me.majrly.database.statements.Query;
import me.majrly.database.statements.Update;
import me.savvy.rixa.Rixa; import me.savvy.rixa.Rixa;
import me.savvy.rixa.data.database.sql.DatabaseManager;
import me.savvy.rixa.enums.Result; import me.savvy.rixa.enums.Result;
import me.savvy.rixa.modules.RixaModule; import me.savvy.rixa.modules.RixaModule;
import me.savvy.rixa.utils.DatabaseUtils;
import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.Guild;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Optional;
/** /**
* Created by Timber on 5/23/2017. * Created by Timber on 5/23/2017.
*/ */
public class MusicModule implements RixaModule { public class MusicModule implements RixaModule {
private DatabaseManager db; private Database db;
@Getter @Getter
private boolean enabled; private boolean enabled;
@Getter @Getter
@ -27,22 +31,30 @@ public class MusicModule implements RixaModule {
this.guild = guild; this.guild = guild;
this.enabled = false; this.enabled = false;
this.musicRole = "default_value"; this.musicRole = "default_value";
db = Rixa.getDbManager(); db = Rixa.getDatabase();
load(); load();
} }
public void load() { public void load() {
if(!checkExists()) { Update music = new Update("CREATE TABLE IF NOT EXISTS `music` (`guild_id` varchar(255) NOT NULL, `music_role` varchar(255) NOT NULL, `enabled` INT(11) NOT NULL, PRIMARY KEY (`guild_id`));");
db.insert("INSERT INTO `music` (`guild_id`, `music_role`, `enabled`)" + db.send(music);
if (!checkExists()) {
Update update = new Update("INSERT INTO `music` (`guild_id`, `music_role`, `enabled`)" +
" VALUES ('" + guild.getId() + "', 'default_value', '0');"); " VALUES ('" + guild.getId() + "', 'default_value', '0');");
db.send(update);
} }
try { try {
PreparedStatement ps = db.getConnection().prepareStatement Query query = new Query("SELECT * FROM `modules` WHERE `guild_id` = ?");
("SELECT * FROM `music` WHERE `guild_id` = ?;"); query.setString(guild.getId());
ps.setString(1, guild.getId()); Optional<?> optional = Rixa.getDatabase().send(query);
ResultSet rs = db.getObject(ps); if (!optional.isPresent()) return;
this.musicRole = rs.getString("music_role"); if (!(optional.get() instanceof ResultSet)) return;
this.enabled = rs.getBoolean("enabled"); ResultSet set = (ResultSet) optional.get();
if (set.next()) {
this.musicRole = set.getString("music_role");
this.enabled = set.getBoolean("enabled");
}
set.close();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -61,7 +73,7 @@ public class MusicModule implements RixaModule {
public Result setEnabled(boolean val) { public Result setEnabled(boolean val) {
this.enabled = val; this.enabled = val;
return Rixa.getData().update("music", "enabled", "guild_id", val, guild.getId()); return DatabaseUtils.update("music", "enabled", "guild_id", val, guild.getId());
} }
public boolean isRoleRequired() { public boolean isRoleRequired() {
@ -71,17 +83,30 @@ public class MusicModule implements RixaModule {
public Result setRole(String newRole) { public Result setRole(String newRole) {
this.musicRole = newRole; this.musicRole = newRole;
return Rixa.getData().update("music", "music_role", "guild_id", newRole, guild.getId()); return DatabaseUtils.update("music", "music_role", "guild_id", newRole, guild.getId());
} }
public boolean checkExists() { public boolean checkExists() {
Result r = Result.ERROR; Result r = Result.FALSE;
try { try {
r = Rixa.getDbManager().checkExists("SELECT `guild_id` FROM `music` WHERE `guild_id` = '" + Query query = new Query("SELECT `guild_id` FROM `music` WHERE `guild_id` = '" +
guild.getId() + "';"); guild.getId() + "';");
Optional<?> optional = Rixa.getDatabase().send(query);
if (!optional.isPresent()) r = Result.ERROR;
if (!(optional.get() instanceof ResultSet)) r = Result.ERROR;
ResultSet set = (ResultSet) optional.get();
if (r != Result.ERROR) {
if (set.next()) {
r = Result.TRUE;
} else {
r = Result.FALSE;
}
}
set.close();
return r == Result.TRUE;
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
return false;
} }
return r == Result.TRUE;
} }
} }

View File

@ -0,0 +1,16 @@
package me.savvy.rixa.utils;
import me.majrly.database.statements.Update;
import me.savvy.rixa.Rixa;
import me.savvy.rixa.enums.Result;
public class DatabaseUtils {
public static Result update(String table, String setting, String key, Object placeholder, Object placeholder2) {
Update update = new Update("UPDATE `" + table + "` SET `" + setting + "` = ? WHERE `" + key + "` = ?;");
update.setObject(placeholder);
update.setObject(placeholder2);
Rixa.getDatabase().send(update);
return Result.TRUE;
}
}