commit c242f587a84768384c38d57d235e33f5a785cf89 Author: Anthony Date: Fri Feb 9 22:19:39 2018 -0500 Initial commit diff --git a/src/main/java/netneutrality/MusicBot.java b/src/main/java/netneutrality/MusicBot.java new file mode 100644 index 0000000..92e658f --- /dev/null +++ b/src/main/java/netneutrality/MusicBot.java @@ -0,0 +1,72 @@ +package netneutrality; + +import java.io.IOException; + +import javax.security.auth.login.LoginException; + +import net.dv8tion.jda.core.AccountType; +import net.dv8tion.jda.core.JDA; +import net.dv8tion.jda.core.JDABuilder; +import net.dv8tion.jda.core.entities.Game; +import netneutrality.db.DBController; +import netneutrality.db.controllers.DBSettings; +import netneutrality.handler.ConsoleHandler; +import netneutrality.handler.EditHandler; +import netneutrality.handler.LogHandler; +import netneutrality.handler.NewCommandListener; +import netneutrality.http.server.WebApi; +import netneutrality.utils.Settings; + +public class MusicBot { + + private static JDA jda; + + public static void main(String[] args) { + DBController.init(); + String token = ((DBSettings) DBController.get("settings")).getToken(); + try { + jda = new JDABuilder(AccountType.BOT).setToken(token).buildBlocking(); + } catch (LoginException | IllegalArgumentException | InterruptedException e) { + LogHandler.log(e); + } + jda.getPresence().setGame(Game.watching("me load...")); + jda.addEventListener(new NewCommandListener(), new EditHandler()); + + Settings.setCreator(jda.getUserById("194270171727265792")); + Settings.setOwnerGuild(jda.getGuildById("195386426400047105")); + + WebApi webserver = new WebApi(); + + jda.getPresence().setGame(Game.watching("rape")); + Thread status = new Thread(new StatusThread(jda.getPresence())); + // status.start(); + + ConsoleHandler consoleInput = new ConsoleHandler(); + + try { + switch (consoleInput.init()) { + + case "quit": + System.out.println("Shutting down..."); + jda.shutdown(); + System.out.println("Shutdown complete"); + System.exit(0); + break; + + } + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public static JDA getJDA() { + return jda; + } + + public static void disconnect() { + jda.shutdown(); + } + + +} diff --git a/src/main/java/netneutrality/StatusThread.java b/src/main/java/netneutrality/StatusThread.java new file mode 100644 index 0000000..e2a9487 --- /dev/null +++ b/src/main/java/netneutrality/StatusThread.java @@ -0,0 +1,33 @@ +package netneutrality; + +import net.dv8tion.jda.core.OnlineStatus; +import net.dv8tion.jda.core.managers.Presence; + +public class StatusThread implements Runnable { + + private Presence status; + + public StatusThread(Presence pr) { + this.status = pr; + } + + @Override + public void run() { + try { + while (true) { + status.setStatus(OnlineStatus.ONLINE); + Thread.sleep(10000); + status.setStatus(OnlineStatus.IDLE); + Thread.sleep(10000); + status.setStatus(OnlineStatus.DO_NOT_DISTURB); + Thread.sleep(10000); + } + + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + +} diff --git a/src/main/java/netneutrality/command/AbstractCommand.java b/src/main/java/netneutrality/command/AbstractCommand.java new file mode 100644 index 0000000..c3c00f6 --- /dev/null +++ b/src/main/java/netneutrality/command/AbstractCommand.java @@ -0,0 +1,62 @@ +package netneutrality.command; + +import java.util.Arrays; +import java.util.List; + +import net.dv8tion.jda.core.events.message.MessageReceivedEvent; + +public abstract class AbstractCommand { + + public AbstractCommand() { + + } + + /** + * @return if the command needs administrator privilege + */ + public abstract boolean needAdmin(); + + /** + * @return if the command is enabled + */ + public abstract boolean isEnabled(); + + /** + * The command name that a user will write in a channel + * + * @return the name of the command. + */ + public abstract String getCommand(); + + /** + * @return all the aliases the command has + */ + public abstract String[] getAlias(); + + public abstract String getUsage(); + + public abstract Visibility getVisibility(); + + /** + * @param event + * @param args the arguments to the command + * @return + */ + public abstract String execute(MessageReceivedEvent event, String args); + + public int countArgs(String command) { + if (command.isEmpty()) + return 0; + + List args = Arrays.asList(command.split(" ")); + return args.size(); + } + + public String parseArgs(String command, int arg) { + if (command.isEmpty()) + return ""; + + List args = Arrays.asList(command.split(" ")); + return args.get(arg); + } +} diff --git a/src/main/java/netneutrality/command/Visibility.java b/src/main/java/netneutrality/command/Visibility.java new file mode 100644 index 0000000..03723e6 --- /dev/null +++ b/src/main/java/netneutrality/command/Visibility.java @@ -0,0 +1,29 @@ +package netneutrality.command; + +/* + * Copyright (c) anthorob + * + * This file is closed-source. It should not be distributed or copied in any way or form + */ + +import net.dv8tion.jda.core.entities.MessageChannel; +import net.dv8tion.jda.core.entities.PrivateChannel; +import net.dv8tion.jda.core.entities.TextChannel; + +public enum Visibility { + + PRIVATE, CHANNEL, BOTH; + + public static boolean check(MessageChannel channel, Visibility v) { + if (v == BOTH && channel instanceof TextChannel || channel instanceof PrivateChannel) + return true; + + if (v == PRIVATE && channel instanceof PrivateChannel) + return true; + + if (v == CHANNEL && channel instanceof TextChannel) + return true; + + return false; + } +} diff --git a/src/main/java/netneutrality/command/basic/HelpCommand.java b/src/main/java/netneutrality/command/basic/HelpCommand.java new file mode 100644 index 0000000..f637acd --- /dev/null +++ b/src/main/java/netneutrality/command/basic/HelpCommand.java @@ -0,0 +1,89 @@ +package netneutrality.command.basic; + +import java.awt.Color; +import java.util.HashMap; +import java.util.function.Consumer; + +import net.dv8tion.jda.core.EmbedBuilder; +import net.dv8tion.jda.core.MessageBuilder; +import net.dv8tion.jda.core.entities.MessageChannel; +import net.dv8tion.jda.core.entities.PrivateChannel; +import net.dv8tion.jda.core.entities.TextChannel; +import net.dv8tion.jda.core.entities.User; +import net.dv8tion.jda.core.events.message.MessageReceivedEvent; +import netneutrality.command.AbstractCommand; +import netneutrality.command.Visibility; +import netneutrality.utils.Settings; + +public class HelpCommand extends AbstractCommand { + + private String help = ""; + + public HelpCommand() { + + } + + @Override + public String execute(MessageReceivedEvent event, String args) { + EmbedBuilder embed = new EmbedBuilder(); + embed.setColor(Color.green); + embed.addField("Commands for Net Neutrality", help, false); + + event.getTextChannel().sendMessage(new MessageBuilder().append(event.getAuthor()).append(" help has been sent your way!").build()).queue(); + + event.getAuthor().openPrivateChannel().queue(t -> t.sendMessage(embed.build()).queue()); + return null; + } + + public void sendHelp(HashMap commands, HashMap alias, User user, MessageChannel channel) { + for (AbstractCommand command : commands.values()) { + if (command.getUsage() != null) + help += Settings.PREFIX + command.getCommand() + " (: " + command.getUsage() + "\n"; + } + + + EmbedBuilder embed = new EmbedBuilder(); + embed.setColor(Color.green); + embed.addField("Commands for Net Neutrality", help, false); + + if (channel instanceof TextChannel) + channel.sendMessage(new MessageBuilder().append(user).append(" help has been sent your way!").build()).queue(); + user.openPrivateChannel().queue(t -> t.sendMessage(embed.build()).queue()); + } + + @Override + public boolean needAdmin() { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean isEnabled() { + // TODO Auto-generated method stub + return true; + } + + @Override + public String getCommand() { + // TODO Auto-generated method stub + return "help"; + } + + @Override + public String[] getAlias() { + // TODO Auto-generated method stub + return new String[0]; + } + + @Override + public String getUsage() { + return "Get every command with its usage"; + } + + @Override + public Visibility getVisibility() { + return Visibility.BOTH; + } + + +} diff --git a/src/main/java/netneutrality/command/basic/PingCommand.java b/src/main/java/netneutrality/command/basic/PingCommand.java new file mode 100644 index 0000000..c2a6986 --- /dev/null +++ b/src/main/java/netneutrality/command/basic/PingCommand.java @@ -0,0 +1,55 @@ +package netneutrality.command.basic; + +import net.dv8tion.jda.core.events.message.MessageReceivedEvent; +import netneutrality.command.AbstractCommand; +import netneutrality.command.Visibility; + +public class PingCommand extends AbstractCommand { + + public PingCommand() { + } + + @Override + public String execute(MessageReceivedEvent event, String args) { + if (countArgs(args) == 0) + event.getChannel().sendMessage("Pong!").queue(); + + return null; + + } + + @Override + public boolean needAdmin() { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean isEnabled() { + // TODO Auto-generated method stub + return true; + } + + @Override + public String getCommand() { + // TODO Auto-generated method stub + return "ping"; + } + + @Override + public String[] getAlias() { + // TODO Auto-generated method stub + return new String[0]; + } + + @Override + public String getUsage() { + return "Pong!"; + } + + @Override + public Visibility getVisibility() { + return Visibility.BOTH; + } + +} diff --git a/src/main/java/netneutrality/command/crypto/BitcoinPriceCommand.java b/src/main/java/netneutrality/command/crypto/BitcoinPriceCommand.java new file mode 100644 index 0000000..1156a69 --- /dev/null +++ b/src/main/java/netneutrality/command/crypto/BitcoinPriceCommand.java @@ -0,0 +1,103 @@ +package netneutrality.command.crypto; + +import java.io.IOException; +import java.util.function.Consumer; + +import netneutrality.command.Visibility; +import org.json.JSONException; +import org.json.JSONObject; + +import net.dv8tion.jda.core.entities.Message; +import net.dv8tion.jda.core.events.message.MessageReceivedEvent; +import netneutrality.command.AbstractCommand; +import netneutrality.http.WebModule; + +public class BitcoinPriceCommand extends AbstractCommand { + + private String currency = "USD"; + private String currencyUrl = "https://api.coindesk.com/v1/bpi/currentprice/"; + private String price; + + public BitcoinPriceCommand() { + this.currency = "USD"; + } + + private String messageBuilder(String price) { + String newPrice = price.substring(0, price.indexOf(".")); + + return "The current bitcoin price in " + this.currency + " is " + newPrice + "$"; + } + + @Override + public String execute(MessageReceivedEvent event, String args) throws JSONException, ArrayIndexOutOfBoundsException { + + if (countArgs(args) == 1) { + if (Currency.isCurrency(args.toUpperCase())) + this.currency = args.toUpperCase(); + else { + event.getTextChannel().sendMessage("Please enter a valid currency").queue(); + return null; + } + + } + + event.getTextChannel().sendMessage("Retreiving price, please wait...").queue(new Consumer() { + + @Override + public void accept(Message t) { + try { + + WebModule bitcoinHttp = new WebModule(currencyUrl + currency + ".json").request(); + JSONObject bpi = bitcoinHttp.getAsObject().getJSONObject("bpi"); + price = bpi.getJSONObject(currency.toUpperCase()).getString("rate"); + + } catch (IOException | RuntimeException e) { + e.printStackTrace(); + t.editMessage("Error getting bitcoin price!").queue(); + } + + t.editMessage(messageBuilder(price)).queue(); + + } + }); + + + + return null; + } + + @Override + public boolean needAdmin() { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean isEnabled() { + // TODO Auto-generated method stub + return true; + } + + @Override + public String getCommand() { + // TODO Auto-generated method stub + return "bitcoin"; + } + + @Override + public String[] getAlias() { + // TODO Auto-generated method stub + return new String[] {"btc"}; + } + + @Override + public String getUsage() { + return "Get the bitcoin price"; + } + + @Override + public Visibility getVisibility() { + return Visibility.BOTH; + } + +} diff --git a/src/main/java/netneutrality/command/crypto/Currency.java b/src/main/java/netneutrality/command/crypto/Currency.java new file mode 100644 index 0000000..8447223 --- /dev/null +++ b/src/main/java/netneutrality/command/crypto/Currency.java @@ -0,0 +1,40 @@ +package netneutrality.command.crypto; + +public enum Currency { + + AED("AED"), AFN("AFN"), ALL("ALL"), AMD("AMD"), ANG("ANG"), AOA("AOA"), ARS("ARS"), AUD("AUD"), AWG("AWG"), AZN("AZN"), BAM("BAM"), BBD("BBD"), + BDT("BDT"), BGN("BGN"), BHD("BHD"), BIF("BIF"), BMD("BMD"), BND("BND"), BOB("BOB"), BOV("BOV"), BRL("BRL"), BSD("BSD"), BTN("BTN"), BWP("BWP"), + BYN("BYN"), BYR("BYR"), BZD("BZD"), CAD("CAD"), CDF("CDF"), CHE("CHE"), CHF("CHF"), CHW("CHW"), CLF("CLF"), CLP("CLP"), CNY("CNY"), COP("COP"), + COU("COU"), CRC("CRC"), CUC("CUC"), CUP("CUP"), CVE("CVE"), CZK("CZK"), DJF("DJF"), DKK("DKK"), DOP("DOP"), DZD("DZD"), EGP("EGP"), ERN("ERN"), + ETB("ETB"), EUR("EUR"), FJD("FJD"), FKP("FKP"), GBP("GBP"), GEL("GEL"), GHS("GHS"), GIP("GIP"), GMD("GMD"), GNF("GNF"), GTQ("GTQ"), GYD("GYD"), + HKD("HKD"), HNL("HNL"), HRK("HRK"), HTG("HTG"), HUF("HUF"), IDR("IDR"), ILS("ILS"), INR("INR"), IQD("IQD"), IRR("IRR"), ISK("ISK"), JMD("JMD"), + JOD("JOD"), JPY("JPY"), KES("KES"), KGS("KGS"), KHR("KHR"), KMF("KMF"), KPW("KPW"), KRW("KRW"), KWD("KWD"), KYD("KYD"), KZT("KZT"), LAK("LAK"), + LBP("LBP"), LKR("LKR"), LRD("LRD"), LSL("LSL"), LYD("LYD"), MAD("MAD"), MDL("MDL"), MGA("MGA"), MKD("MKD"), MMK("MMK"), MNT("MNT"), MOP("MOP"), + MRO("MRO"), MUR("MUR"), MVR("MVR"), MWK("MWK"), MXN("MXN"), MXV("MXV"), MYR("MYR"), MZN("MZN"), NAD("NAD"), NGN("NGN"), NIO("NIO"), NOK("NOK"), + NPR("NPR"), NZD("NZD"), OMR("OMR"), PAB("PAB"), PEN("PEN"), PGK("PGK"), PHP("PHP"), PKR("PKR"), PLN("PLN"), PYG("PYG"), QAR("QAR"), RON("RON"), + RSD("RSD"), RUB("RUB"), RWF("RWF"), SAR("SAR"), SBD("SBD"), SCR("SCR"), SDG("SDG"), SEK("SEK"), SGD("SGD"), SHP("SHP"), SLL("SLL"), SOS("SOS"), + SRD("SRD"), SSP("SSP"), STD("STD"), SYP("SYP"), SZL("SZL"), THB("THB"), TJS("TJS"), TMT("TMT"), TND("TND"), TOP("TOP"), TRY("TRY"), TTD("TTD"), + TWD("TWD"), TZS("TZS"), UAH("UAH"), UGX("UGX"), USD("USD"), USN("USN"), UYI("UYI"), UYU("UYU"), UZS("UZS"), VEF("VEF"), VND("VND"), VUV("VUV"), + WST("WST"), XAF("XAF"), XAG("XAG"), XAU("XAU"), XBA("XBA"), XBB("XBB"), XBC("XBC"), XBD("XBD"), XCD("XCD"), XDR("XDR"), XFU("XFU"), XOF("XOF"), + XPD("XPD"), XPF("XPF"), XPT("XPT"), XSU("XSU"), XTS("XTS"), XUA("XUA"), XXX("XXX"), YER("YER"), ZAR("ZAR"), ZMW("ZMW"); + + private String iso4217Code; + + Currency(String code) { + this.iso4217Code = code; + } + + @Override + public String toString() { + return iso4217Code; + } + + public static boolean isCurrency(String str) { + for (Currency c : Currency.values()) { + if (c.name().equals(str.toUpperCase())) + return true; + } + + return false; + } +} diff --git a/src/main/java/netneutrality/command/crypto/EthereumPriceCommand.java b/src/main/java/netneutrality/command/crypto/EthereumPriceCommand.java new file mode 100644 index 0000000..5852dc3 --- /dev/null +++ b/src/main/java/netneutrality/command/crypto/EthereumPriceCommand.java @@ -0,0 +1,95 @@ +package netneutrality.command.crypto; + +import java.io.IOException; +import java.util.function.Consumer; + +import netneutrality.command.Visibility; +import org.json.JSONException; + +import net.dv8tion.jda.core.entities.Message; +import net.dv8tion.jda.core.events.message.MessageReceivedEvent; +import netneutrality.command.AbstractCommand; +import netneutrality.http.WebModule; + +public class EthereumPriceCommand extends AbstractCommand { + + private String currency = "USD"; + private String currencyUrl = "https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms="; + private String price = ""; + + public EthereumPriceCommand() { + this.currency = "USD"; + } + + private String messageBuilder(String price) { + return "The current ethereum price in " + this.currency + " is " + price + "$"; + } + + @Override + public String execute(MessageReceivedEvent event, String args) throws JSONException, ArrayIndexOutOfBoundsException { + + if (countArgs(args) == 1) { + if (Currency.isCurrency(args.toUpperCase())) + this.currency = args.toUpperCase(); + else { + event.getTextChannel().sendMessage("Please enter a valid currency").queue(); + return null; + } + + } + + event.getTextChannel().sendMessage("Retreiving price, please wait...").queue(new Consumer() { + + @Override + public void accept(Message t) { + + try { + WebModule ethereumHttp = new WebModule(currencyUrl + currency.toUpperCase()).request(); + price = Double.toString(ethereumHttp.getAsObject().getDouble(currency)); + + } catch (IOException | RuntimeException e) { + e.printStackTrace(); + t.editMessage("Error getting ethereum price!").queue(); + } + t.editMessage(messageBuilder(price)).queue(); + } + }); + + return null; + } + + @Override + public boolean needAdmin() { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean isEnabled() { + // TODO Auto-generated method stub + return true; + } + + @Override + public String getCommand() { + // TODO Auto-generated method stub + return "ethereum"; + } + + @Override + public String[] getAlias() { + // TODO Auto-generated method stub + return new String[] {"eth"}; + } + + @Override + public String getUsage() { + return "Get the ethereum price"; + } + + @Override + public Visibility getVisibility() { + return Visibility.BOTH; + } + +} diff --git a/src/main/java/netneutrality/command/crypto/LitecoinPriceCommand.java b/src/main/java/netneutrality/command/crypto/LitecoinPriceCommand.java new file mode 100644 index 0000000..5636395 --- /dev/null +++ b/src/main/java/netneutrality/command/crypto/LitecoinPriceCommand.java @@ -0,0 +1,94 @@ +package netneutrality.command.crypto; + +import java.io.IOException; +import java.util.function.Consumer; + +import netneutrality.command.Visibility; +import org.json.JSONException; + +import net.dv8tion.jda.core.entities.Message; +import net.dv8tion.jda.core.events.message.MessageReceivedEvent; +import netneutrality.command.AbstractCommand; +import netneutrality.http.WebModule; + +public class LitecoinPriceCommand extends AbstractCommand { + + private String currency = "USD"; + private String currencyUrl = "https://api.coinmarketcap.com/v1/ticker/litecoin/?convert="; + private String price; + + public LitecoinPriceCommand() { + this.currency = "USD"; + } + + private String messageBuilder(String price) { + return "The current litecoin price in " + this.currency + " is " + price + "$"; + } + + @Override + public String execute(MessageReceivedEvent event, String args) throws ArrayIndexOutOfBoundsException, JSONException { + + if (countArgs(args) == 1) { + if (Currency.isCurrency(args.toUpperCase())) + this.currency = args; + else { + event.getTextChannel().sendMessage("Please enter a valid currency").queue(); + return null; + } + + } + + event.getTextChannel().sendMessage("Retreiving price, please wait...").queue(new Consumer() { + + @Override + public void accept(Message t) { + + try { + WebModule litecoinHttp = new WebModule(currencyUrl + currency).request(); + price = litecoinHttp.getAsArray().getJSONObject(0).getString("price_" + currency.toLowerCase()); + } catch (IOException | RuntimeException e) { + e.printStackTrace(); + t.editMessage("Error getting litecoin price!").queue(); + } + t.editMessage(messageBuilder(price)).queue(); + + } + }); + + return null; + } + + @Override + public boolean needAdmin() { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean isEnabled() { + // TODO Auto-generated method stub + return true; + } + + @Override + public String getCommand() { + // TODO Auto-generated method stub + return "litecoin"; + } + + @Override + public String[] getAlias() { + // TODO Auto-generated method stub + return new String[] {"ltc"}; + } + + @Override + public String getUsage() { + return "Get the litecoin price"; + } + + @Override + public Visibility getVisibility() { + return Visibility.BOTH; + } +} diff --git a/src/main/java/netneutrality/command/message/BlacklistCommand.java b/src/main/java/netneutrality/command/message/BlacklistCommand.java new file mode 100644 index 0000000..839d6eb --- /dev/null +++ b/src/main/java/netneutrality/command/message/BlacklistCommand.java @@ -0,0 +1,135 @@ +package netneutrality.command.message; + +import java.util.ArrayList; +import java.util.function.Consumer; + +import net.dv8tion.jda.core.entities.Message; +import net.dv8tion.jda.core.events.message.MessageReceivedEvent; +import netneutrality.command.AbstractCommand; +import netneutrality.command.Visibility; +import netneutrality.db.DBController; +import netneutrality.db.controllers.DBBlacklist; +import netneutrality.db.models.MBlacklist; +import netneutrality.handler.LogHandler; + +public class BlacklistCommand extends AbstractCommand { + + public BlacklistCommand() { + // TODO Auto-generated constructor stub + } + + @Override + public boolean needAdmin() { + // TODO Auto-generated method stub + return true; + } + + @Override + public boolean isEnabled() { + // TODO Auto-generated method stub + return true; + } + + @Override + public String getCommand() { + // TODO Auto-generated method stub + return "blacklist"; + } + + @Override + public String[] getAlias() { + return new String[] {"bl"}; + } + + @Override + public String getUsage() { + return "Manages the blacklist of your server."; + } + + @Override + public Visibility getVisibility() { + return Visibility.CHANNEL; + } + + @Override + public String execute(MessageReceivedEvent event, String args) { + + if (countArgs(args) > 0 && countArgs(args) < 3) { + String word = (countArgs(args) == 2 ? parseArgs(args, 1) : ""); + + switch (parseArgs(args, 0)) { + + case "get": + event.getTextChannel().sendMessage("Retreiving list, please wait...").queue(t -> { + String out = ""; + + ArrayList blacklist = null; + try { + blacklist = ((DBBlacklist) DBController.get("blacklist")).getBlacklistFromServer(event.getGuild().getId()); + for (MBlacklist bl : blacklist) { + out += bl.getWord() + " -> " + (bl.isEnabled() ? "enabled" : "disabled") + "\n"; + } + } catch (RuntimeException e) { + e.printStackTrace(); + } + t.editMessage("List of blacklisted words for this server [" + event.getGuild().getName() + "] :\n" + (blacklist.isEmpty() ? "No word found" : out)).queue(); + + }); + + break; + + case "add": + + try { + ((DBBlacklist) DBController.get("blacklist")).add(new MBlacklist(word, true, event.getAuthor().getId(), event.getGuild().getId())); + event.getTextChannel().sendMessage("Added the word \"" + word + "\" to the blacklist.").queue(); + } catch (RuntimeException e) { + event.getTextChannel().sendMessage("Error adding \"" + word + "\" to the blacklist. It's already blacklisted!").queue(); + LogHandler.log(e); + } + + break; + + case "remove": + + try { + ((DBBlacklist) DBController.get("blacklist")).delete(word, event.getGuild().getId()); + event.getTextChannel().sendMessage("Removed the word \"" + word + "\" from the blacklist.").queue(); + } catch (RuntimeException e) { + LogHandler.log(e); + event.getTextChannel().sendMessage("Error removing \"" + word + "\" from the blacklist").queue(); + } + + break; + + case "disable": + + try { + ((DBBlacklist) DBController.get("blacklist")).disable(word, event.getGuild().getId()); + event.getTextChannel().sendMessage("Succesfully disabled the word \"" + word + "\" from the blacklist!").queue(); + } catch (NullPointerException e) { + LogHandler.log(e); + event.getTextChannel().sendMessage("Error disabling \"" + word + "\", it's not blacklisted!").queue(); + } + + break; + + case "enable": + + try { + ((DBBlacklist) DBController.get("blacklist")).enable(word, event.getGuild().getId()); + event.getTextChannel().sendMessage("Succesfully enabled the word \"" + word + "\" from the blacklist!").queue(); + } catch (NullPointerException e) { + event.getTextChannel().sendMessage("Error enabling \"" + word + "\", it's not blacklisted!").queue(); + LogHandler.log(e); + } + + break; + + } + } + + return null; + } + +} diff --git a/src/main/java/netneutrality/command/message/PruneCommand.java b/src/main/java/netneutrality/command/message/PruneCommand.java new file mode 100644 index 0000000..21d84d1 --- /dev/null +++ b/src/main/java/netneutrality/command/message/PruneCommand.java @@ -0,0 +1,58 @@ +package netneutrality.command.message; + +import net.dv8tion.jda.core.events.message.MessageReceivedEvent; +import netneutrality.command.AbstractCommand; +import netneutrality.command.Visibility; +import netneutrality.utils.ChannelFunction; + +public class PruneCommand extends AbstractCommand { + + public PruneCommand() { + // TODO Auto-generated constructor stub + } + + @Override + public boolean needAdmin() { + // TODO Auto-generated method stub + return true; + } + + @Override + public boolean isEnabled() { + // TODO Auto-generated method stub + return true; + } + + @Override + public String getCommand() { + // TODO Auto-generated method stub + return "prune"; + } + + @Override + public String[] getAlias() { + // TODO Auto-generated method stub + return new String[] {"purge"}; + } + + @Override + public String getUsage() { + return "Prune n messages from the channel you are currently on"; + } + + @Override + public Visibility getVisibility() { + return Visibility.CHANNEL; + } + + @Override + public String execute(MessageReceivedEvent event, String args) { + if (countArgs(args) == 1) + ChannelFunction.bulkDeleteMessage(event.getTextChannel(), Integer.parseInt(args)); + else + event.getTextChannel().sendMessage("Failed to delete messages!").queue(); + + return null; + } + +} diff --git a/src/main/java/netneutrality/command/specific/DatabaseCommand.java b/src/main/java/netneutrality/command/specific/DatabaseCommand.java new file mode 100644 index 0000000..7702ca1 --- /dev/null +++ b/src/main/java/netneutrality/command/specific/DatabaseCommand.java @@ -0,0 +1,120 @@ +package netneutrality.command.specific; + +import java.awt.Color; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.function.Consumer; + +import net.dv8tion.jda.core.EmbedBuilder; +import net.dv8tion.jda.core.entities.PrivateChannel; +import net.dv8tion.jda.core.entities.User; +import net.dv8tion.jda.core.events.message.MessageReceivedEvent; +import netneutrality.command.AbstractCommand; +import netneutrality.command.Visibility; +import netneutrality.db.DBController; +import netneutrality.db.controllers.DBMessage; +import netneutrality.db.models.MMessage; +import netneutrality.utils.Settings; + +public class DatabaseCommand extends AbstractCommand { + + public DatabaseCommand() { + // TODO Auto-generated constructor stub + } + + @Override + public boolean needAdmin() { + // TODO Auto-generated method stub + return true; + } + + @Override + public boolean isEnabled() { + // TODO Auto-generated method stub + return true; + } + + @Override + public String getCommand() { + // TODO Auto-generated method stub + return "database"; + } + + @Override + public String[] getAlias() { + // TODO Auto-generated method stub + return new String[] { "db" }; + } + + @Override + public String getUsage() { + return null; + } + + @Override + public Visibility getVisibility() { + return Visibility.CHANNEL; + } + + @Override + public String execute(MessageReceivedEvent event, String args) { + + if (!event.getAuthor().getDiscriminator().equals(Settings.getCreator().getDiscriminator())) + return null; + + if (countArgs(args) > 0) { + switch (parseArgs(args, 0)) { + + case "message": + + if (countArgs(args) > 1) { + event.getMessage().delete().queue(); + MMessage message = ((DBMessage) DBController.get("message")).getMessage(parseArgs(args, 1)); + if (message != null) { + EmbedBuilder embed = new EmbedBuilder(); + embed.setColor(Color.BLUE); + embed.setTimestamp( + DateTimeFormatter.ofPattern(Settings.DATETIMEFORMAT).parse(message.getDateSent())); + embed.setFooter("Guild : " + message.getServerName() + " | ID : " + message.getMessageId(), null); + embed.setDescription( + "Message from " + message.getSender() + " on the channel " + message.getChannelName()); + embed.addField("Message: ", "" + message.getMessage(), false); + event.getTextChannel().sendMessage(embed.build()).queue(); + } else { + User user = event.getJDA().getUserById(parseArgs(args, 1)); + if (user != null) { + ArrayList messages = ((DBMessage) DBController.get("message")) + .getMessagesFromUser(user.getName(), event.getGuild().getName(), 10); + EmbedBuilder embed = new EmbedBuilder(); + embed.setColor(Color.BLUE); + embed.setTimestamp(OffsetDateTime.now()); + for (int i = 0; i < messages.size(); i++) { + embed.addField( + "Message in channel \"" + messages.get(i).getChannelName() + "\" sent on " + + messages.get(i).getDateSent(), + "" + messages.get(i).getMessage(), false); + } + embed.setFooter("Guild : " + event.getGuild().getName(), null); + + event.getAuthor().openPrivateChannel().queue(new Consumer() { + + @Override + public void accept(PrivateChannel t) { + t.sendMessage(embed.build()).queue(); + + } + }); + } + } + + } + + break; + } + } + + return null; + } + +} diff --git a/src/main/java/netneutrality/command/specific/LoggingCommand.java b/src/main/java/netneutrality/command/specific/LoggingCommand.java new file mode 100644 index 0000000..a275657 --- /dev/null +++ b/src/main/java/netneutrality/command/specific/LoggingCommand.java @@ -0,0 +1,49 @@ +package netneutrality.command.specific; + +import net.dv8tion.jda.core.events.message.MessageReceivedEvent; +import netneutrality.command.AbstractCommand; +import netneutrality.command.Visibility; + +public class LoggingCommand extends AbstractCommand { + + public LoggingCommand() { + + } + + @Override + public boolean needAdmin() { + return true; + } + + @Override + public boolean isEnabled() { + return false; + } + + @Override + public String getCommand() { + return "logging"; + } + + @Override + public String[] getAlias() { + return new String[0]; + } + + @Override + public String getUsage() { + return null; + } + + @Override + public Visibility getVisibility() { + return Visibility.CHANNEL; + } + + @Override + public String execute(MessageReceivedEvent event, String args) { + + + return null; + } +} diff --git a/src/main/java/netneutrality/command/specific/NiggerCommand.java b/src/main/java/netneutrality/command/specific/NiggerCommand.java new file mode 100644 index 0000000..9d33f19 --- /dev/null +++ b/src/main/java/netneutrality/command/specific/NiggerCommand.java @@ -0,0 +1,55 @@ +package netneutrality.command.specific; + +import net.dv8tion.jda.core.events.message.MessageReceivedEvent; +import netneutrality.command.AbstractCommand; +import netneutrality.command.Visibility; + +public class NiggerCommand extends AbstractCommand { + + public NiggerCommand() { + + } + + @Override + public String execute(MessageReceivedEvent event, String args) { + event.getMessage().delete().queue(); + event.getTextChannel().sendMessage("Not in my christian server").queue(); + return null; + + } + + @Override + public boolean needAdmin() { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean isEnabled() { + // TODO Auto-generated method stub + return true; + } + + @Override + public String getCommand() { + // TODO Auto-generated method stub + return "nigger"; + } + + @Override + public String[] getAlias() { + // TODO Auto-generated method stub + return new String[0]; + } + + @Override + public String getUsage() { + return null; + } + + @Override + public Visibility getVisibility() { + return Visibility.BOTH; + } + +} diff --git a/src/main/java/netneutrality/command/specific/SellyCommand.java b/src/main/java/netneutrality/command/specific/SellyCommand.java new file mode 100644 index 0000000..0ce74df --- /dev/null +++ b/src/main/java/netneutrality/command/specific/SellyCommand.java @@ -0,0 +1,103 @@ +package netneutrality.command.specific; + +/* + * Copyright (c) anthorob + * + * This file is closed-source. It should not be distributed or copied in any way or form + */ + +import net.dv8tion.jda.core.events.message.MessageReceivedEvent; +import netneutrality.command.AbstractCommand; +import netneutrality.command.Visibility; +import netneutrality.db.DBController; +import netneutrality.db.controllers.DBSettings; +import netneutrality.db.models.SellyOrder; +import netneutrality.http.Selly; +import org.json.JSONArray; +import org.json.JSONObject; + +import java.util.HashMap; +import java.util.Map; + +public class SellyCommand extends AbstractCommand { + + public SellyCommand() { + + } + + @Override + public boolean needAdmin() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } + + @Override + public String getCommand() { + return "selly"; + } + + @Override + public String[] getAlias() { + return new String[0]; + } + + @Override + public String getUsage() { + return null; + } + + @Override + public Visibility getVisibility() { + return Visibility.PRIVATE; + } + + @Override + public String execute(MessageReceivedEvent event, String args) { + + Map orders = new HashMap<>(); + String sellyEmail = ((DBSettings) DBController.get("settings")).getSellyEmail(); + String sellyKey = ((DBSettings) DBController.get("settings")).getSellyKey(); + Selly selly = new Selly(sellyEmail, sellyKey); + + JSONArray ordersArray = selly.getOrders(); + + for (int i = 0; i < ordersArray.length(); i++) { + JSONObject order = ordersArray.getJSONObject(i); + orders.put(order.getString("id"), new SellyOrder(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"), + order.getInt("crypto_value"), order.getString("crypto_address"), Float.parseFloat(order.getString("usd_value")), order.getString("created_at"))); + } + + System.out.println(selly.getProducts().toString()); + + if (countArgs(args) > 1) { + String email = parseArgs(args, 0); + String id = parseArgs(args, 1); + + if (orders.containsKey(id)) { + SellyOrder order = orders.get(id); + if (email.equals(order.getEmail())) { + if (order.getStatus() == 100) { + event.getAuthor().openPrivateChannel().queue(t -> t.sendMessage("success").queue()); + } else + event.getAuthor().openPrivateChannel().queue(t -> t.sendMessage("not completed").queue()); + } else + event.getAuthor().openPrivateChannel().queue(t -> t.sendMessage("wrong email").queue()); + } else + event.getAuthor().openPrivateChannel().queue(t -> t.sendMessage("order doesn't exist").queue()); + } else + event.getAuthor().openPrivateChannel().queue(t -> t.sendMessage("usage : $selly ").queue()); + + + + + + + + return null; + } +} diff --git a/src/main/java/netneutrality/command/specific/ShutdownCommand.java b/src/main/java/netneutrality/command/specific/ShutdownCommand.java new file mode 100644 index 0000000..8536f2e --- /dev/null +++ b/src/main/java/netneutrality/command/specific/ShutdownCommand.java @@ -0,0 +1,54 @@ +package netneutrality.command.specific; + +import net.dv8tion.jda.core.events.message.MessageReceivedEvent; +import netneutrality.command.AbstractCommand; +import netneutrality.command.Visibility; + +public class ShutdownCommand extends AbstractCommand { + + public ShutdownCommand() { + // TODO Auto-generated constructor stub + } + + @Override + public boolean needAdmin() { + // TODO Auto-generated method stub + return true; + } + + @Override + public boolean isEnabled() { + // TODO Auto-generated method stub + return false; + } + + @Override + public String getCommand() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String[] getAlias() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getUsage() { + return null; + } + + @Override + public Visibility getVisibility() { + return Visibility.BOTH; + } + + @Override + public String execute(MessageReceivedEvent event, String args) { + event.getJDA().shutdown(); + System.exit(0); + return null; + } + +} diff --git a/src/main/java/netneutrality/command/specific/TestCommand.java b/src/main/java/netneutrality/command/specific/TestCommand.java new file mode 100644 index 0000000..15b616e --- /dev/null +++ b/src/main/java/netneutrality/command/specific/TestCommand.java @@ -0,0 +1,59 @@ +package netneutrality.command.specific; + +/* + * Copyright (c) anthorob + * + * This file is closed-source. It should not be distributed or copied in any way or form + */ + +import net.dv8tion.jda.core.events.message.MessageReceivedEvent; +import netneutrality.command.AbstractCommand; +import netneutrality.command.Visibility; +import netneutrality.utils.MessageFunction; +import netneutrality.utils.Settings; + +public class TestCommand extends AbstractCommand { + + public TestCommand() { + + } + + @Override + public boolean needAdmin() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } + + @Override + public String getCommand() { + return "test"; + } + + @Override + public String[] getAlias() { + return new String[0]; + } + + @Override + public String getUsage() { + return null; + } + + @Override + public Visibility getVisibility() { + return Visibility.BOTH; + } + + @Override + public String execute(MessageReceivedEvent event, String args) { + if (event.getAuthor().getDiscriminator().equals(Settings.getCreator().getDiscriminator())) { + MessageFunction.isStartingWithMention(event.getMessage()); + } + + return null; + } +} diff --git a/src/main/java/netneutrality/db/AbstractController.java b/src/main/java/netneutrality/db/AbstractController.java new file mode 100644 index 0000000..80026fa --- /dev/null +++ b/src/main/java/netneutrality/db/AbstractController.java @@ -0,0 +1,27 @@ +package netneutrality.db; + +import java.sql.SQLException; + +public abstract class AbstractController { + + protected MysqlDatabase database; + + /** + * The controller name to be used in {@link DBController} get(String controller) method + * + * @return String + */ + public abstract String getControllerName(); + + public void reconnect() throws SQLException { + database.reconnect(); + } + + public boolean isClosed() throws SQLException { + return database.isClosed(); + } + + protected void setDatabase(MysqlDatabase database) { + this.database = database; + } +} diff --git a/src/main/java/netneutrality/db/DBController.java b/src/main/java/netneutrality/db/DBController.java new file mode 100644 index 0000000..f6e4597 --- /dev/null +++ b/src/main/java/netneutrality/db/DBController.java @@ -0,0 +1,105 @@ +package netneutrality.db; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Modifier; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.Set; + +import org.reflections.Reflections; + +public class DBController { + + /** + * A map that contains all the controllers currently loaded + */ + private static HashMap controllers = new HashMap<>(); + private static MysqlDatabase database = new MysqlDatabase("discord"); + + /** + * @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 + */ + public static AbstractController get(String controller) { + if (controllers.isEmpty()) + init(); + + + if (controllers.containsKey(controller)) { + try { + if (controllers.get(controller).isClosed()) { + System.out.println("Reconnecting to database.."); + controllers.get(controller).reconnect(); + } + } catch (SQLException e) { + e.printStackTrace(); + } + return controllers.get(controller); + } + + return null; + } + + public static MysqlDatabase get() { + try { + if (database.isClosed()) { + System.out.println("Reconnecting to database.."); + database.reconnect(); + } + } catch (SQLException e) { + e.printStackTrace(); + } + + + return database; + } + + public static void shutdown() throws SQLException { + database.close(); + controllers.forEach((k,v) -> { + try { + v.database.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + }); + } + + /** + * Optional, will be called if the method {@link #get(String) get()} is used + */ + public static void init() { + loadControllers(); + } + + /** + * Loads all the controllers which extends {@link AbstractController} + */ + public static void loadControllers() { + System.out.println("Loading databases controllers.."); + + Reflections reflections = new Reflections("netneutrality.db.controllers"); + Set> classes = reflections.getSubTypesOf(AbstractController.class); + + for (Class s : classes) { + try { + if (Modifier.isAbstract(s.getModifiers())) { + continue; + } + + AbstractController c = s.getConstructor().newInstance(); + c.setDatabase(database); + + if (!controllers.containsKey(c.getControllerName())) { + controllers.put(c.getControllerName(), c); + System.out.println("Loaded controller: " + c.getControllerName()); + } + + } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException e) { + e.printStackTrace(); + } + } + } + + +} diff --git a/src/main/java/netneutrality/db/MysqlConnector.java b/src/main/java/netneutrality/db/MysqlConnector.java new file mode 100644 index 0000000..e6424f6 --- /dev/null +++ b/src/main/java/netneutrality/db/MysqlConnector.java @@ -0,0 +1,51 @@ +package netneutrality.db; + +import java.sql.Connection; +import java.sql.SQLException; + +import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource; + +public class MysqlConnector { + + protected String dbName; + protected String dbUser; + protected String dbHost; + protected String dbPass; + private Connection c; + + public 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 informations + * + * @return {@link MysqlConnector} + * @throws SQLException + */ + public MysqlConnector connect() throws SQLException { + MysqlConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource(); + dataSource.setUser(dbUser); + dataSource.setPassword(dbPass); + dataSource.setServerName(dbHost); + dataSource.setPort(3306); + dataSource.setDatabaseName(dbName); + dataSource.setAutoReconnect(true); + dataSource.setAutoReconnectForConnectionPools(true); + c = dataSource.getConnection(); + return this; + } + + /** + * Get the MySQL connection. Must call {@link #connect()} beforehand. + * + * @return {@link Connection} + */ + public Connection getConnection() { + return c; + } + +} diff --git a/src/main/java/netneutrality/db/MysqlDatabase.java b/src/main/java/netneutrality/db/MysqlDatabase.java new file mode 100644 index 0000000..0c1807e --- /dev/null +++ b/src/main/java/netneutrality/db/MysqlDatabase.java @@ -0,0 +1,269 @@ +package netneutrality.db; + +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.MusicBot; +import netneutrality.db.models.RowModel; +import netneutrality.db.models.TableModel; +import netneutrality.exceptions.UnimplementedParameterException; + +public class MysqlDatabase { + + private Connection connection; + private PreparedStatement query = null; + private String prepareString; + private int nbRow; + private String dbName; + + public MysqlDatabase(String dbName) { + this.dbName = dbName; + try { + System.out.println("Connecting to database..."); + connection = new MysqlConnector(dbName, "root", "localhost", "").connect().getConnection(); + } catch (SQLException e) { + System.err.println("Error connecting to database. Shutting down.."); + MusicBot.disconnect(); + System.exit(0); + } + } + + /** + * Execute a simple query without any parameters. + * Example : SELECT * FROM table + * + * @param query The SQL query to execute + * @return {@link ResultSet} + * @throws SQLException + */ + public ResultSet query(String query) throws SQLException { + Statement stmt = connection.createStatement(); + return stmt.executeQuery(query); + } + + /** + * 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 + * @return an integer of how many row were affected + * @throws SQLException + */ + public int update(String sql, Object... params) throws SQLException { + prepareString = sql; + query = connection.prepareStatement(sql); + resolveParameters(query, params); + return query.executeUpdate(); + } + + /** + * 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 + * @throws SQLException + */ + public int insert(String sql, Object... params) throws SQLException { + prepareString = sql; + query = connection.prepareStatement(sql); + resolveParameters(query, params); + return query.executeUpdate(); + } + + /** + * 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 + * @throws SQLException + */ + public int delete(String sql, Object... params) throws SQLException { + prepareString = sql; + query = connection.prepareStatement(sql); + resolveParameters(query, params); + return query.executeUpdate(); + } + + /** + * 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 an array using {@link #convertToArray(ResultSet)} + * @throws SQLException + */ + public ResultSet prepareAndExecute(String sql, Object... params) throws SQLException { + prepareString = sql; + query = connection.prepareStatement(sql); + resolveParameters(query, params); + return query.executeQuery(); + } + + // https://github.com/Kaaz/DiscordBot/blob/master/src/main/java/emily/db/MySQLAdapter.java#resolveParameters + 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) { + java.sql.Date d = (java.sql.Date) p; + query.setDate(index, d); + } else if (p instanceof java.util.Date) { + java.util.Date d = (java.util.Date) p; + Timestamp ts = new Timestamp(d.getTime()); + query.setTimestamp(index, ts); + } else if (p instanceof Calendar) { + Calendar cal = (Calendar) p; + 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 + * + * @throws SQLException + */ + public void close() throws SQLException { + connection.close(); + } + + /** + * Recreate the MySQL connection. + * + * @throws SQLException + */ + public void reconnect() throws SQLException { + connection = new MysqlConnector(dbName, "root", "localhost", "").connect().getConnection(); + } + + /** + * Check if the database is closed. + * + * @return the connection status + * @throws SQLException + */ + public boolean isClosed() throws SQLException { + return connection.isClosed(); + } + + /** + * Convert a ResultSet object into an array. + *
+ *
The first row of the array is the names of the columns. + *
The other rows are their corresponding value + * + * + * @param rs The ResultSet returned by the SELECT query + * @return an array of Object with the table structure + * @throws SQLException + */ + public Object[][] convertToArray(ResultSet rs) throws SQLException { + nbRow = getNbRowFromTable(prepareString); + + ResultSetMetaData metadata = rs.getMetaData(); + Object array[][] = new Object[nbRow + 1][metadata.getColumnCount()]; + + for (int i = 1; i < metadata.getColumnCount() + 1; i++) { + array[0][i - 1] = metadata.getColumnName(i); + } + + int pos = 1; + while (rs.next()) { + for (int i = 1; i < rs.getMetaData().getColumnCount() + 1; i++) { + array[pos][i - 1] = rs.getObject(i); + } + + pos++; + } + + try { + if (array[1][0] == null) + nbRow = 0; + } catch (ArrayIndexOutOfBoundsException e) { + + } + + rs.getStatement().close(); + + return array; + + } + + public TableModel convertToTableModel(ResultSet rs) throws SQLException { + TableModel table = new TableModel(); + nbRow = getNbRowFromTable(prepareString); + + ResultSetMetaData metadata = rs.getMetaData(); + for (int i = 1; i < metadata.getColumnCount() + 1; i++) { + table.addColumn(metadata.getColumnName(i)); + } + + while (rs.next()) { + RowModel row = new RowModel(); + for (int i = 0; i < metadata.getColumnCount(); i++) { + row.addColumnToRow(rs.getObject(i + 1)); + } + table.addRow(row); + } + + return table; + } + + + + /** + * Only usable when @link {@link #prepareAndExecute(String, Object...) prepareAndExecute()} is called + * + * @return the number of row + */ + public int getNbRow() { + return nbRow; + } + + private String findTable(String sql) { + int indexFrom = sql.indexOf("FROM") + 5; + int indexWhere = sql.indexOf("WHERE") - 1; + + if (indexWhere < 0) { + return sql.substring(indexFrom, indexFrom + 4); + } + return sql.substring(indexFrom, indexWhere); + } + + private int getNbRowFromTable(String sql) throws SQLException { + ResultSet nbRowRs = query("SELECT COUNT(*) FROM " + findTable(sql)); + if (nbRowRs.next()) + return nbRowRs.getInt(1); + + return 0; + } + +} diff --git a/src/main/java/netneutrality/db/controllers/DBBlacklist.java b/src/main/java/netneutrality/db/controllers/DBBlacklist.java new file mode 100644 index 0000000..f05efdd --- /dev/null +++ b/src/main/java/netneutrality/db/controllers/DBBlacklist.java @@ -0,0 +1,148 @@ +package netneutrality.db.controllers; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; + +import netneutrality.db.AbstractController; +import netneutrality.db.DBController; +import netneutrality.db.MysqlDatabase; +import netneutrality.db.models.MBlacklist; +import netneutrality.db.models.TableModel; + +public class DBBlacklist extends AbstractController { + + public DBBlacklist() { + + } + + /** + * Returns an instance of {@link MysqlDatabase} with the database name as set in the {@link DBController} class + * + * @return {@link MysqlDatabase} + */ + public MysqlDatabase getDatabase() { + return database; + } + + public int add(MBlacklist obj) { + try { + if (!isAlreadyBlacklisted(obj.getWord(), obj.getServerId())) { + int result = database.insert("INSERT INTO blacklist VALUES(?,?,?,?)", obj.getWord(), obj.getServerId(), + obj.isEnabled(), obj.getCreatorId()); + return result; + } else + throw new RuntimeException("Word is already blacklisted"); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return -1; + } + + public int delete(String word, String serverId) { + try { + if (isAlreadyBlacklisted(word, serverId)) { + int result = database.delete("DELETE FROM blacklist WHERE word = ? AND serverId = ?", word, serverId); + return result; + } else + throw new RuntimeException("Is not blacklisted"); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return -1; + } + + public int enable(String word, String serverId) { + try { + if (isAlreadyBlacklisted(word, serverId)) { + int result = database.update("UPDATE blacklist SET isEnabled = 1 WHERE word = ? AND serverId = ?", word, serverId); + return result; + } else + throw new RuntimeException("Is not blacklisted"); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return -1; + } + + public int disable(String word, String serverId) { + try { + if (isAlreadyBlacklisted(word, serverId)) { + int result = database.update("UPDATE blacklist SET isEnabled = 0 WHERE word = ? AND serverId = ?", word, serverId); + return result; + } else + throw new RuntimeException("Is not blacklisted"); + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return -1; + } + + public MBlacklist getBlacklistForWord(String word, String serverId) { + try { + if (isAlreadyBlacklisted(word, serverId)) { + ResultSet rs = database.prepareAndExecute("SELECT * FROM blacklist WHERE word = ? AND serverId = ?", word, serverId); + Object array[][] = database.convertToArray(rs); + if (database.getNbRow() != 0) { + return new MBlacklist((String) array[1][0], (Boolean) array[1][2], (String) array[1][3], + (String) array[1][1]); + } + } else + throw new RuntimeException("Is not blacklisted"); + } catch (SQLException e) { + e.printStackTrace(); + } + + return null; + } + + public ArrayList getBlacklistFromServer(String serverId) { + ArrayList output = new ArrayList<>(); + + try { + ResultSet rs = database.prepareAndExecute("SELECT * FROM blacklist WHERE serverId = ? AND isEnabled = 1", serverId); + TableModel model = database.convertToTableModel(rs); + + if (model.getNbRows() != 0) { + for (int row = 0; row < database.getNbRow(); row++) { + output.add(new MBlacklist((String) model.getRow(row).get(0), (Boolean) model.getRow(row).get(2), (String) model.getRow(row).get(3), + (String) model.getRow(row).get(1))); + } + } else + throw new RuntimeException("Blacklist is empty"); + + } catch (SQLException e) { + e.printStackTrace(); + } catch (NullPointerException e) { + + } catch (IndexOutOfBoundsException i) { + throw new RuntimeException("Blacklist is empty"); + } + + return output; + } + + public boolean isAlreadyBlacklisted(String word, String serverId) throws SQLException { + ResultSet rs = database.prepareAndExecute("SELECT COUNT(*) FROM blacklist WHERE word = ? AND serverId = ?", word, serverId); + if (rs.next()) { + if (rs.getInt(1) == 0) + return false; + } + + return true; + } + + @Override + public String getControllerName() { + // TODO Auto-generated method stub + return "blacklist"; + } +} diff --git a/src/main/java/netneutrality/db/controllers/DBMessage.java b/src/main/java/netneutrality/db/controllers/DBMessage.java new file mode 100644 index 0000000..006a5b7 --- /dev/null +++ b/src/main/java/netneutrality/db/controllers/DBMessage.java @@ -0,0 +1,139 @@ +package netneutrality.db.controllers; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.sql.ResultSet; + +import netneutrality.db.AbstractController; +import netneutrality.db.DBController; +import netneutrality.db.MysqlDatabase; +import netneutrality.db.models.MMessage; +import netneutrality.handler.LogHandler; + +public class DBMessage extends AbstractController { + + public DBMessage() { } + + /** + * Returns an instance of {@link MysqlDatabase} with the database name as set in the {@link DBController} class + * + * @return {@link MysqlDatabase} + */ + public MysqlDatabase getDatabase() { + return database; + } + + public int log(String servername, String channelname, String username, String datesent, String messageId, String message) { + + try { + return database.insert("INSERT INTO log_message VALUES(?,?,?,?,?,?,?)", servername, channelname, username, datesent, messageId, message, null); + } catch (SQLException e) { + LogHandler.log(e); + } + + return -1; + + } + + public int logEdit(String messageId, String newMessage) { + + try { + return database.update("UPDATE log_message SET editedMessage = ? WHERE messageId = ?", newMessage, messageId); + } catch (SQLException e) { + LogHandler.log(e); + } + + return -1; + + } + + public MMessage getMessage(String messageId) { + try { + ResultSet rs = database.prepareAndExecute("SELECT * FROM log_message WHERE messageId = ?", messageId); + Object[][] array = database.convertToArray(rs); + if (database.getNbRow() != 0) + return new MMessage(array[1][0], array[1][1], array[1][2], array[1][3], array[1][4], array[1][5]); + + } catch (SQLException e) { + LogHandler.log(e); + } + + return null; + } + + public ArrayList getMessagesFromUser(String username, String serverName, int max) { + ArrayList messages = new ArrayList(); + + try { + ResultSet rs = database.prepareAndExecute("SELECT * FROM log_message WHERE userName = ? AND serverName = ? ORDER BY dateSent DESC", username, serverName); + Object[][] array = database.convertToArray(rs); + if (database.getNbRow() != 0) { + for (int row = 1; row <= max; row++) { + messages.add(new MMessage(array[row][0], array[row][1], array[row][2], array[row][3], array[row][4], array[row][5])); + } + } + + } catch (SQLException e) { + LogHandler.log(e); + } + + return messages; + } + + public String getMessageString(String messageId) { + + try { + ResultSet rs = database.prepareAndExecute("SELECT message FROM log_message WHERE messageId = ?", messageId); + if (rs.next()) + return rs.getString(1); + } catch (SQLException e) { + LogHandler.log(e); + } + + return "No message found"; + } + + public boolean setupLog(String serverId, String channelId) { + + try { + int result = database.insert("INSERT INTO logging VALUES(?,?,?)", serverId, channelId, true); + if (result == 1) + return true; + } catch (SQLException e) { + LogHandler.log(e); + } + + return false; + } + + public boolean toggleLog(String serverId, String channelId) { + + try { + int result = database.update("UPDATE logging SET enabled = NOT enabled"); + if (result == 1) + return true; + } catch (SQLException e) { + LogHandler.log(e); + } + + return false; + } + + public boolean isLoggingEnabled(String serverId, String channelId) { + + try { + ResultSet rs = database.prepareAndExecute("SELECT enabled FROM logging WHERE serverId = ? AND channelId = ?", serverId, channelId); + if (rs.next()) + return rs.getBoolean(1); + } catch (SQLException e) { + e.printStackTrace(); + } + + return false; + } + + @Override + public String getControllerName() { + return "message"; + } +} diff --git a/src/main/java/netneutrality/db/controllers/DBSettings.java b/src/main/java/netneutrality/db/controllers/DBSettings.java new file mode 100644 index 0000000..0a7cb7c --- /dev/null +++ b/src/main/java/netneutrality/db/controllers/DBSettings.java @@ -0,0 +1,81 @@ +package netneutrality.db.controllers; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.Map; + +import netneutrality.db.AbstractController; + +public class DBSettings extends AbstractController { + + public DBSettings() { + // TODO Auto-generated constructor stub + } + + public String getLoggingChannel(String serverId) { + if (serverId.isEmpty() || serverId == null) + return null; + + try { + ResultSet rs = database.prepareAndExecute("SELECT channelId FROM logging WHERE serverId = ? AND enabled = 1", serverId); + if (rs.next()) { + return rs.getString(1); + } + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return null; + } + + public String getToken() { + try { + ResultSet rs = database.prepareAndExecute("SELECT token FROM settings"); + if (rs.next()) { + return rs.getString(1); + } + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return null; + } + + public String getSellyEmail() { + try { + ResultSet rs = database.prepareAndExecute("SELECT selly_email FROM settings"); + if (rs.next()) { + return rs.getString(1); + } + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return null; + } + + public String getSellyKey() { + try { + ResultSet rs = database.prepareAndExecute("SELECT selly_key FROM settings"); + if (rs.next()) { + return rs.getString(1); + } + } catch (SQLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return null; + } + + @Override + public String getControllerName() { + // TODO Auto-generated method stub + return "settings"; + } + +} diff --git a/src/main/java/netneutrality/db/models/ColumnModel.java b/src/main/java/netneutrality/db/models/ColumnModel.java new file mode 100644 index 0000000..ddfa646 --- /dev/null +++ b/src/main/java/netneutrality/db/models/ColumnModel.java @@ -0,0 +1,34 @@ +package netneutrality.db.models; + +/* + * Copyright (c) anthorob + * + * This file is closed-source. It should not be distributed or copied in any way or form + */ + +import java.util.Arrays; +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; + +public class ColumnModel { + private List columns; + + public ColumnModel() { + columns = new LinkedList<>(); + } + + public void addColumn(String name) { + columns.add(name); + } + + public void addAll(Collection columns) { + columns.addAll(columns); + + } + + @Override + public String toString() { + return Arrays.toString(columns.toArray()); + } +} diff --git a/src/main/java/netneutrality/db/models/MBlacklist.java b/src/main/java/netneutrality/db/models/MBlacklist.java new file mode 100644 index 0000000..3dad482 --- /dev/null +++ b/src/main/java/netneutrality/db/models/MBlacklist.java @@ -0,0 +1,59 @@ +package netneutrality.db.models; + +public class MBlacklist { + + protected String word; + protected boolean enabled; + protected String creatorId; + protected String serverId; + + public MBlacklist(String word, boolean enabled, String creatorId, String serverId) { + this.word = word; + this.enabled = enabled; + this.creatorId = creatorId; + this.serverId = serverId; + } + + /** + * @return String The blacklisted word + */ + public String getWord() { + return word; + } + + public void setWord(String word) { + this.word = word; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public String getCreatorId() { + return creatorId; + } + + public void setCreatorId(String creatorId) { + this.creatorId = creatorId; + } + + public String getServerId() { + return serverId; + } + + public void setServerId(String serverId) { + this.serverId = serverId; + } + + @Override + public String toString() { + return "[word=" + word + ", enabled=" + enabled + "]"; + } + + + +} diff --git a/src/main/java/netneutrality/db/models/MMessage.java b/src/main/java/netneutrality/db/models/MMessage.java new file mode 100644 index 0000000..a2b22b3 --- /dev/null +++ b/src/main/java/netneutrality/db/models/MMessage.java @@ -0,0 +1,102 @@ +package netneutrality.db.models; + +public class MMessage { + + private String serverName; + private String channelName; + private String sender; + private String dateSent; + private String messageId; + private String message; + private String editedMessage; + + public MMessage(String serverName, String channelName, String sender, String dateSent, String messageId, + String message) { + this.serverName = serverName; + this.channelName = channelName; + this.sender = sender; + this.dateSent = dateSent; + this.messageId = messageId; + this.message = message; + this.editedMessage = ""; + } + + public MMessage() { + + } + + public MMessage(Object serverName, Object channelName, Object sender, Object dateSent, Object messageId, Object message) { + this.serverName = (String) serverName; + this.channelName = (String) channelName; + this.sender = (String) sender; + this.dateSent = (String) dateSent; + this.messageId = (String) messageId; + this.message = (String) message; + this.editedMessage = ""; + } + + public String getServerName() { + return serverName; + } + + public void setServerName(String serverName) { + this.serverName = serverName; + } + + public String getChannelName() { + return channelName; + } + + public void setChannelName(String channelName) { + this.channelName = channelName; + } + + public String getSender() { + return sender; + } + + public void setSender(String sender) { + this.sender = sender; + } + + public String getDateSent() { + return dateSent; + } + + public void setDateSent(String dateSent) { + this.dateSent = dateSent; + } + + public String getMessageId() { + return messageId; + } + + public void setMessageId(String messageId) { + this.messageId = messageId; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getEditedMessage() { + return editedMessage; + } + + public void setEditedMessage(String editedMessage) { + this.editedMessage = editedMessage; + } + + @Override + public String toString() { + return "MMessage [serverName=" + serverName + ", channelName=" + channelName + ", sender=" + sender + + ", dateSent=" + dateSent + ", messageId=" + messageId + ", message=" + message + ", editedMessage=" + + editedMessage + "]"; + } + + +} diff --git a/src/main/java/netneutrality/db/models/RowModel.java b/src/main/java/netneutrality/db/models/RowModel.java new file mode 100644 index 0000000..bc76de6 --- /dev/null +++ b/src/main/java/netneutrality/db/models/RowModel.java @@ -0,0 +1,37 @@ +package netneutrality.db.models; + +/* + * Copyright (c) anthorob + * + * This file is closed-source. It should not be distributed or copied in any way or form + */ + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class RowModel { + private ArrayList row; + + public RowModel() { + row = new ArrayList<>(); + } + + public RowModel(Object... objs) { + row = new ArrayList<>(); + row.addAll(Arrays.asList(objs)); + } + + public void addColumnToRow(Object obj) { + row.add(obj); + } + + public List getRow() { + return row; + } + + @Override + public String toString() { + return row.toString(); + } +} diff --git a/src/main/java/netneutrality/db/models/RowsModel.java b/src/main/java/netneutrality/db/models/RowsModel.java new file mode 100644 index 0000000..575e7e8 --- /dev/null +++ b/src/main/java/netneutrality/db/models/RowsModel.java @@ -0,0 +1,41 @@ +package netneutrality.db.models; + +/* + * Copyright (c) anthorob + * + * This file is closed-source. It should not be distributed or copied in any way or form + */ + +import java.util.ArrayList; + +public class RowsModel { + private ArrayList rows; + + public RowsModel() { + rows = new ArrayList<>(); + } + + public void addRow(RowModel row) { + rows.add(row); + } + + public RowModel getRowModel(int index) { + if (!rows.isEmpty()) + return rows.get(index); + + return null; + } + + public void addColumnInRow(int index, Object obj) { + rows.get(index).addColumnToRow(obj); + } + + public ArrayList getRows() { + return rows; + } + + @Override + public String toString() { + return rows.toString(); + } +} diff --git a/src/main/java/netneutrality/db/models/SellyOrder.java b/src/main/java/netneutrality/db/models/SellyOrder.java new file mode 100644 index 0000000..ae7cea8 --- /dev/null +++ b/src/main/java/netneutrality/db/models/SellyOrder.java @@ -0,0 +1,112 @@ +package netneutrality.db.models; + +/* + * Copyright (c) anthorob + * + * This file is closed-source. It should not be distributed or copied in any way or form + */ + +public class SellyOrder { + + private String id; + private String product_id; + private String email; + private String ip; + private float value; + private String currency; + private String gateway; + private int risk; + private int status; + private int cryptoValue; + private String cryptoAddress; + private float usdValue; + private String createdAt; + + public SellyOrder(String id, String product_id, 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.product_id = product_id; + this.email = email; + this.ip = ip; + this.value = value; + this.currency = currency; + this.gateway = gateway; + this.risk = risk; + this.status = status; + this.cryptoValue = cryptoValue; + this.cryptoAddress = cryptoAddress; + this.usdValue = usdValue; + this.createdAt = createdAt; + } + + public String getId() { + + return id; + } + + public String getProduct_id() { + return product_id; + } + + public String getEmail() { + return email; + } + + public String getIp() { + return ip; + } + + public float getValue() { + return value; + } + + public String getCurrency() { + return currency; + } + + public String getGateway() { + return gateway; + } + + public int getRisk() { + return risk; + } + + public int getStatus() { + return status; + } + + public int getCryptoValue() { + return cryptoValue; + } + + public String getCryptoAddress() { + return cryptoAddress; + } + + public float getUsdValue() { + return usdValue; + } + + public String getCreatedAt() { + return createdAt; + } + + @Override + public String toString() { + return "SellyOrder{" + + "id='" + id + '\'' + + ", product_id='" + product_id + '\'' + + ", email='" + email + '\'' + + ", ip='" + ip + '\'' + + ", value='" + value + '\'' + + ", currency='" + currency + '\'' + + ", gateway='" + gateway + '\'' + + ", risk='" + risk + '\'' + + ", status='" + status + '\'' + + ", cryptoValue='" + cryptoValue + '\'' + + ", cryptoAddress='" + cryptoAddress + '\'' + + ", usdValue='" + usdValue + '\'' + + ", createdAt='" + createdAt + '\'' + + '}'; + } +} diff --git a/src/main/java/netneutrality/db/models/SellyProduct.java b/src/main/java/netneutrality/db/models/SellyProduct.java new file mode 100644 index 0000000..901e5f6 --- /dev/null +++ b/src/main/java/netneutrality/db/models/SellyProduct.java @@ -0,0 +1,18 @@ +package netneutrality.db.models; + +/* + * Copyright (c) anthorob + * + * This file is closed-source. It should not be distributed or copied in any way or form + */ + +public class SellyProduct { + + private String id; + private String title; + private String description; + private String stock; + private float price; + private String currency; + private boolean isPrivate; +} diff --git a/src/main/java/netneutrality/db/models/TableModel.java b/src/main/java/netneutrality/db/models/TableModel.java new file mode 100644 index 0000000..84fdd61 --- /dev/null +++ b/src/main/java/netneutrality/db/models/TableModel.java @@ -0,0 +1,64 @@ +package netneutrality.db.models; + +/* + * Copyright (c) anthorob + * + * This file is closed-source. It should not be distributed or copied in any way or form + */ + + +import java.util.Arrays; +import java.util.List; + +public class TableModel { + private ColumnModel columns; + private RowsModel rows; + + + + public TableModel() { + this.columns = new ColumnModel(); + this.rows = new RowsModel(); + } + + public TableModel(String... columns) { + this.columns = new ColumnModel(); + this.rows = new RowsModel(); + + this.columns.addAll(Arrays.asList(columns)); + } + + public void addColumn(String name) { + columns.addColumn(name); + } + + public RowsModel addRow(RowModel row) { + rows.addRow(row); + return rows; + } + + public RowsModel getRows() { + return rows; + } + + public List getRow(int index) { + return rows.getRowModel(index).getRow(); + } + + public ColumnModel getColumns() { + return columns; + } + + public boolean isEmpty() { + return rows.getRows().isEmpty(); + } + + public int getNbRows() { + return rows.getRows().size(); + } + + @Override + public String toString() { + return "Columns: [" + columns + "], Rows: [" + rows + "]"; + } +} diff --git a/src/main/java/netneutrality/exceptions/UnimplementedParameterException.java b/src/main/java/netneutrality/exceptions/UnimplementedParameterException.java new file mode 100644 index 0000000..71b1ae6 --- /dev/null +++ b/src/main/java/netneutrality/exceptions/UnimplementedParameterException.java @@ -0,0 +1,39 @@ +/* + * 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 static final long serialVersionUID = 4721555678157694115L; + private 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; + } + +} diff --git a/src/main/java/netneutrality/handler/CommandHandler.java b/src/main/java/netneutrality/handler/CommandHandler.java new file mode 100644 index 0000000..b7291d8 --- /dev/null +++ b/src/main/java/netneutrality/handler/CommandHandler.java @@ -0,0 +1,284 @@ +package netneutrality.handler; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.Consumer; + +import net.dv8tion.jda.core.entities.ChannelType; +import net.dv8tion.jda.core.entities.Message; +import net.dv8tion.jda.core.events.message.MessageReceivedEvent; +import net.dv8tion.jda.core.hooks.ListenerAdapter; +import netneutrality.command.basic.HelpCommand; +import netneutrality.command.basic.PingCommand; +import netneutrality.command.crypto.BitcoinPriceCommand; +import netneutrality.command.crypto.EthereumPriceCommand; +import netneutrality.command.crypto.LitecoinPriceCommand; +import netneutrality.command.specific.NiggerCommand; +import netneutrality.db.DBController; +import netneutrality.db.controllers.DBBlacklist; +import netneutrality.db.controllers.DBMessage; +import netneutrality.db.models.MBlacklist; +import netneutrality.utils.*; + +public class CommandHandler extends ListenerAdapter { + + private String prefix = "$"; + + + @Override + public void onMessageReceived(MessageReceivedEvent event) { + + if (event.getAuthor().isBot()) return; + if (event.isWebhookMessage()) return; + if (MessageRateLimit.check(event)) return; + + // event.getChannel().sendMessage("Message id : " + event.getMessage().getId()).queue(); + + ((DBMessage) DBController.get("message")).log(event.getGuild().getName(), event.getTextChannel().getName(), + event.getMember().getUser().getName(), + event.getMessage().getCreationTime().toInstant().toString(), event.getMessage().getId(), + event.getMessage().getContentDisplay().trim()); + + if (event.isFromType(ChannelType.PRIVATE)) { + System.out.printf("[PM] %s: %s\n>", event.getAuthor().getName(), event.getMessage().getContentDisplay()); + } else { + System.out.printf("[%s][%s] %s: %s\n>", event.getGuild().getName(), event.getTextChannel().getName(), + event.getMember().getEffectiveName(), event.getMessage().getContentDisplay()); + + + if (event.getMessage().getContentStripped().startsWith(prefix)) { + String command = event.getMessage().getContentStripped().substring(1).split(" ")[0]; + String args = event.getMessage().getContentStripped(); + + + switch (command) { + + case "ping": + new PingCommand().execute(event, null); + break; + + case "help": + new HelpCommand().execute(event, null); + break; + + case "nigger": + new NiggerCommand().execute(event, null); + break; + + case "setuplog": + ((DBMessage) DBController.get("message")).setupLog(event.getGuild().getId(), event.getTextChannel().getId()); + + event.getTextChannel().sendMessage("Logging has been enabled on the #" + event.getTextChannel().getName() + " text channnel for the server " + event.getGuild().getName()).queue(); + break; + + case "togglelog": + + break; + + case "shutdown": + if (event.getAuthor().getDiscriminator().equals("5337")) { + event.getTextChannel().sendMessage("Shutting down...").queue(); + + event.getJDA().shutdown(); + System.exit(0); + } + + break; + + case "bitcoin": + case "btc": + if (countArgs(event.getMessage().getContentStripped()) == 2) { + event.getTextChannel().sendMessage("In maintenance.").queue(); + } else { + new BitcoinPriceCommand().execute(event, null); + } + + break; + + case "ethereum": + case "eth": + if (countArgs(event.getMessage().getContentStripped()) == 2) { + event.getTextChannel().sendMessage("In maintenance.").queue(); + } else { + new EthereumPriceCommand().execute(event, null); + } + + break; + + case "litecoin": + case "ltc": + if (countArgs(event.getMessage().getContentStripped()) == 2) { + event.getTextChannel().sendMessage("In maintenance.").queue(); + } else { + new LitecoinPriceCommand().execute(event, null); + } + + break; + + // prune command + case "prune": + case "purge": + + if (UserFunction.isAdmin(event.getMember())) { + + try { + int toDelete = Integer.parseInt(parseArgs(event.getMessage().getContentStripped(), 1)); + ChannelFunction.bulkDeleteMessage(event.getTextChannel(), toDelete); + } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) { + event.getTextChannel().sendMessage("Failed to delete message!").queue(); + } + + } + break; + + + case "blacklist": + + if (UserFunction.isAdmin(event.getMember())) { + + + + if (countArgs(args) >= 2) { + switch (parseArgs(args, 1)) { + + case "get": + + event.getTextChannel().sendMessage("Retreiving list, please wait...").queue(new Consumer() { + + @Override + public void accept(Message t) { + String out = ""; + + ArrayList blacklist = null; + try { + blacklist = ((DBBlacklist) DBController.get("blacklist")).getBlacklistFromServer(event.getGuild().getId()); + for (MBlacklist bl : blacklist) { + out += bl.getWord() + " -> " + (bl.isEnabled() ? "enabled" : "disabled") + "\n"; + } + } catch (RuntimeException e) { + LogHandler.log(e); + } + t.editMessage("List of blacklisted words for this server [" + event.getGuild().getName() + "] :\n" + (blacklist.isEmpty() ? "No word found" : out)).queue(); + + } + }); + + break; + + case "add": + if (UserFunction.isAdmin(event.getMember())) { + String word = parseArgs(event.getMessage().getContentStripped(), 2); + + try { + ((DBBlacklist) DBController.get("blacklist")).add(new MBlacklist(word, true, event.getAuthor().getId(), event.getGuild().getId())); + event.getTextChannel().sendMessage("Added the word \"" + word + "\" to the blacklist.").queue(); + } catch (RuntimeException e) { + event.getTextChannel().sendMessage("Error adding \"" + word + "\" to the blacklist. It's already blacklisted!").queue(); + LogHandler.log(e); + } + } + + break; + + case "remove": + if (UserFunction.isAdmin(event.getMember())) { + String word = parseArgs(event.getMessage().getContentStripped(), 2); + + try { + ((DBBlacklist) DBController.get("blacklist")).delete(word, event.getGuild().getId()); + event.getTextChannel().sendMessage("Removed the word \"" + word + "\" from the blacklist.").queue(); + } catch (RuntimeException e) { + LogHandler.log(e); + event.getTextChannel().sendMessage("Error removing \"" + word + "\" from the blacklist").queue(); + } + } + + break; + + case "disable": + + if (event.getAuthor().getDiscriminator().equals("5337")) { + String word = parseArgs(event.getMessage().getContentStripped(), 2); + + try { + ((DBBlacklist) DBController.get("blacklist")).disable(word, event.getGuild().getId()); + event.getTextChannel().sendMessage("Succesfully disabled the word \"" + word + "\" from the blacklist!").queue(); + } catch (NullPointerException e) { + LogHandler.log(e); + event.getTextChannel().sendMessage("Error disabling \"" + word + "\", it's not blacklisted!").queue(); + } + } + + break; + + case "enable": + + if (event.getAuthor().getDiscriminator().equals("5337")) { + String word = parseArgs(event.getMessage().getContentStripped(), 2); + + try { + ((DBBlacklist) DBController.get("blacklist")).enable(word, event.getGuild().getId()); + event.getTextChannel().sendMessage("Succesfully enabled the word \"" + word + "\" from the blacklist!").queue(); + } catch (NullPointerException e) { + event.getTextChannel().sendMessage("Error enabling \"" + word + "\", it's not blacklisted!").queue(); + LogHandler.log(e); + } + } + + break; + + } + } + + + } + + break; + + case "test": + if (event.getAuthor().getDiscriminator().equals("5337")) { + event.getMessage().delete().queue(); + event.getTextChannel().sendMessage("```JF est gay```").queue(); + } + + + break; + + + + } + + + } + else { + ArrayList blacklist = ((DBBlacklist) DBController.get("blacklist")).getBlacklistFromServer(event.getGuild().getId()); + + if (!blacklist.isEmpty()) { + boolean found = false; + for (int i = 0; i < blacklist.size(); i++) { + if (blacklist.get(i).isEnabled()) { + if (event.getMessage().getContentStripped().toLowerCase().contains(blacklist.get(i).getWord())) + found = true; + } + + } + if (found) { + event.getMessage().delete().queue(); + event.getTextChannel().sendMessage("Not in my christian server").queue(); + } + } + } + } + } + + private int countArgs(String command) { + List args = Arrays.asList(command.split(" ")); + return args.size(); + } + + private String parseArgs(String command, int arg) { + List args = Arrays.asList(command.split(" ")); + return args.get(arg); + } +} diff --git a/src/main/java/netneutrality/handler/ConsoleHandler.java b/src/main/java/netneutrality/handler/ConsoleHandler.java new file mode 100644 index 0000000..b43b33d --- /dev/null +++ b/src/main/java/netneutrality/handler/ConsoleHandler.java @@ -0,0 +1,27 @@ +package netneutrality.handler; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class ConsoleHandler { + + + private BufferedReader br; + private String input = ""; + + public ConsoleHandler() { + System.out.println("Console input ready!"); + } + + public String init() throws IOException { + this.br = new BufferedReader(new InputStreamReader(System.in)); + + do { + System.out.print(">"); + this.input = this.br.readLine(); + } while (!this.input.equalsIgnoreCase("quit")); + + return this.input; + } +} diff --git a/src/main/java/netneutrality/handler/EditHandler.java b/src/main/java/netneutrality/handler/EditHandler.java new file mode 100644 index 0000000..16b264c --- /dev/null +++ b/src/main/java/netneutrality/handler/EditHandler.java @@ -0,0 +1,47 @@ +package netneutrality.handler; + +import java.awt.Color; + +import net.dv8tion.jda.core.EmbedBuilder; +import net.dv8tion.jda.core.events.message.MessageUpdateEvent; +import net.dv8tion.jda.core.hooks.ListenerAdapter; +import netneutrality.db.DBController; +import netneutrality.db.controllers.DBMessage; +import netneutrality.db.controllers.DBSettings; + +public class EditHandler extends ListenerAdapter { + + @Override + public void onMessageUpdate(MessageUpdateEvent event) { + + if (event.getAuthor().isBot()) return; + + String logChannel = ((DBSettings) DBController.get("settings")).getLoggingChannel(event.getGuild().getId()); + if (logChannel != null) { + String originalMessage = ((DBMessage) DBController.get("message")).getMessageString(event.getMessage().getId()); + ((DBMessage) DBController.get("message")).logEdit(event.getMessage().getId(), event.getMessage().getContentDisplay()); + + EmbedBuilder editEmbed = new EmbedBuilder(); + editEmbed.setColor(Color.RED); + editEmbed.setDescription(":pencil2: **Message edited by " + event.getAuthor().getName() + "**"); + try { + editEmbed.addField("Original message", (originalMessage == null ? "Not available" : originalMessage), false); + } catch (IllegalArgumentException ex) { + editEmbed.addField("Original message :", "Message too long. Check db for full message", false); + } + + try { + editEmbed.addField("Edited to :", event.getMessage().getContentDisplay(), false); + } catch (IllegalArgumentException ex) { + editEmbed.addField("Edited to :", "Message too long. Check db for full message", false); + } + + editEmbed.setFooter("ID : " + event.getMessageId(), null); + editEmbed.setTimestamp(event.getMessage().getCreationTime()); + event.getJDA().getTextChannelById(logChannel).sendMessage(editEmbed.build()).queue(); + } + + + } + +} diff --git a/src/main/java/netneutrality/handler/LogHandler.java b/src/main/java/netneutrality/handler/LogHandler.java new file mode 100644 index 0000000..7ea6da8 --- /dev/null +++ b/src/main/java/netneutrality/handler/LogHandler.java @@ -0,0 +1,17 @@ +package netneutrality.handler; + +import netneutrality.utils.Settings; + +public class LogHandler { + + /** + * Log the exception to the owner's log TextChannel as defined in {@link Settings#getLogChannel()} + * + * @param t The exceptions to log + */ + public static void log(Throwable t) { + + Settings.getLogChannel().sendMessage("Error : " + t.getMessage()).queue(); + + } +} diff --git a/src/main/java/netneutrality/handler/MessageRateLimit.java b/src/main/java/netneutrality/handler/MessageRateLimit.java new file mode 100644 index 0000000..07bc506 --- /dev/null +++ b/src/main/java/netneutrality/handler/MessageRateLimit.java @@ -0,0 +1,43 @@ +package netneutrality.handler; + +import java.time.OffsetDateTime; + +import net.dv8tion.jda.core.entities.Member; +import net.dv8tion.jda.core.entities.PrivateChannel; +import net.dv8tion.jda.core.events.message.MessageReceivedEvent; + +public class MessageRateLimit { + + private static Member lastSender; + private static OffsetDateTime timestamp; + private static int cooldown = 500000000; // 1 seconds = 1000000000 nanoseconds + + public static boolean check(MessageReceivedEvent event) { + + if (event.getChannel() instanceof PrivateChannel) + return false; + + if (lastSender == null || timestamp == null) { + lastSender = event.getMember(); + timestamp = event.getMessage().getCreationTime(); + return false; + } + + if (event.getMember().getUser().getId().equals(lastSender.getUser().getId())) { + if (event.getMessage().getCreationTime().minusNanos(cooldown).isBefore(timestamp)) { + lastSender = event.getMember(); + timestamp = event.getMessage().getCreationTime(); + event.getMessage().delete().queue(); + System.err.print("Rate limited\n>"); + return true; + } + } + + lastSender = event.getMember(); + timestamp = event.getMessage().getCreationTime(); + + return false; + + } + +} diff --git a/src/main/java/netneutrality/handler/NewCommandListener.java b/src/main/java/netneutrality/handler/NewCommandListener.java new file mode 100644 index 0000000..b9a737f --- /dev/null +++ b/src/main/java/netneutrality/handler/NewCommandListener.java @@ -0,0 +1,147 @@ +package netneutrality.handler; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Modifier; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import net.dv8tion.jda.core.entities.ChannelType; +import netneutrality.command.Visibility; +import netneutrality.command.basic.HelpCommand; +import netneutrality.utils.MessageFunction; +import org.reflections.Reflections; + +import net.dv8tion.jda.core.entities.Message; +import net.dv8tion.jda.core.events.message.MessageReceivedEvent; +import net.dv8tion.jda.core.hooks.ListenerAdapter; +import netneutrality.command.AbstractCommand; +import netneutrality.db.DBController; +import netneutrality.db.controllers.DBBlacklist; +import netneutrality.db.controllers.DBMessage; +import netneutrality.db.models.MBlacklist; +import netneutrality.utils.Settings; +import netneutrality.utils.UserFunction; + +public class NewCommandListener extends ListenerAdapter { + + private HashMap commands = new HashMap<>(); + private HashMap commandsAlias = new HashMap<>(); + private Map alias = new HashMap<>(); + + + public NewCommandListener() { + initCommands(); + initAlias(); + } + + @Override + public void onMessageReceived(MessageReceivedEvent event) { + + if (event.getAuthor().isBot()) return; + if (event.isWebhookMessage()) return; + if (MessageRateLimit.check(event)) return; + + + if (event.isFromType(ChannelType.TEXT)) + ((DBMessage) DBController.get("message")).log(event.getGuild().getName(), event.getTextChannel().getName(), + event.getMember().getUser().getName(), + event.getMessage().getCreationTime().format(DateTimeFormatter.ofPattern(Settings.DATETIMEFORMAT)), event.getMessage().getId(), + event.getMessage().getContentDisplay().trim()); + + Message message = event.getMessage(); + String msg = message.getContentDisplay().trim(); + + if (msg.startsWith(Settings.PREFIX)) { + msg = msg.substring(1); + String cmd = msg.split(" ", 2)[0]; + + + if (commands.containsKey(cmd) || commandsAlias.containsKey(cmd)) { + + AbstractCommand c = commands.containsKey(cmd) ? commands.get(cmd) : commandsAlias.get(cmd); + + + if (Visibility.check(event.getChannel(), c.getVisibility())) { + if (c.needAdmin() && c.getVisibility() != Visibility.PRIVATE) { + if (!UserFunction.isAdmin(event.getMember())) { + return; + } + } + + if (cmd.equals("help")) { + ((HelpCommand) commands.get("help")).sendHelp(commands, commandsAlias, event.getAuthor(), event.getChannel()); + } else { + c.execute(event, msg.replaceFirst("(" + cmd + ")(\\ )?", "")); + } + } + + + } + } else { + ArrayList blacklist = new ArrayList<>(); + + try { + blacklist = ((DBBlacklist) DBController.get("blacklist")).getBlacklistFromServer(event.getGuild().getId()); + } catch (RuntimeException e) { } + + if (!blacklist.isEmpty()) { + + boolean found = false; + for (int i = 0; i < blacklist.size(); i++) { + if (msg.toLowerCase().contains(blacklist.get(i).getWord())) + found = true; + } + + if (found) { + event.getMessage().delete().queue(); + event.getTextChannel().sendMessage("Not in my christian server").queue(); + } + + } + } + } + + public void initCommands() { + System.out.println("Loading commands.."); + + Reflections reflections = new Reflections("netneutrality.command"); + Set> classes = reflections.getSubTypesOf(AbstractCommand.class); + + for (Class s : classes) { + try { + if (Modifier.isAbstract(s.getModifiers())) { + continue; + } + + AbstractCommand command = s.getConstructor().newInstance(); + + if (!command.isEnabled()) + continue; + + if (!commands.containsKey(command.getCommand())) { + commands.put(command.getCommand(), command); + } + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException + | InvocationTargetException | NoSuchMethodException | SecurityException e) { + e.printStackTrace(); + } + } + + System.out.println("Loaded " + commands.size() + " commands!"); + } + + public void initAlias() { + + for (AbstractCommand command : commands.values()) { + for (String alias : command.getAlias()) { + if (!commandsAlias.containsKey(alias)) + commandsAlias.put(alias, command); + } + } + } + + +} diff --git a/src/main/java/netneutrality/http/Selly.java b/src/main/java/netneutrality/http/Selly.java new file mode 100644 index 0000000..3004103 --- /dev/null +++ b/src/main/java/netneutrality/http/Selly.java @@ -0,0 +1,72 @@ +package netneutrality.http; + +/* + * Copyright (c) anthorob + * + * This file is closed-source. It should not be distributed or copied in any way or form + */ + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.io.IOException; +import java.util.Base64; +import java.util.HashMap; +import java.util.Map; + +public class Selly { + + private String authorization; + private byte[] encodedAuth; + + public Selly(String email, String apiKey) { + String concat = email + ":" + apiKey; + encodedAuth = Base64.getEncoder().encode(concat.getBytes()); + } + + public JSONArray getOrders() { + WebModule orders = new WebModule("https://selly.gg/api/v2/orders"); + Map headers = new HashMap<>(); + headers.put("Authorization", "Basic " + new String(encodedAuth)); + JSONArray response = null; + try { + orders.request(headers); + response = orders.getAsArray(); + } catch (IOException e) { + e.printStackTrace(); + } + + return response; + } + + public JSONObject getOrderById(String id) { + WebModule order = new WebModule("https://selly.gg/api/v2/orders/" + id); + Map headers = new HashMap<>(); + headers.put("Authorization", "Basic " + new String(encodedAuth)); + JSONObject response = null; + try { + order.request(headers); + response = order.getAsObject(); + } catch (IOException e) { + e.printStackTrace(); + } + + return response; + } + + public JSONArray getProducts() { + WebModule orders = new WebModule("https://selly.gg/api/v2/products"); + Map headers = new HashMap<>(); + headers.put("Authorization", "Basic " + new String(encodedAuth)); + JSONArray response = null; + + try { + orders.request(headers); + response = orders.getAsArray(); + } catch (IOException e) { + e.printStackTrace(); + } + + return response; + } +} diff --git a/src/main/java/netneutrality/http/WebModule.java b/src/main/java/netneutrality/http/WebModule.java new file mode 100644 index 0000000..154e932 --- /dev/null +++ b/src/main/java/netneutrality/http/WebModule.java @@ -0,0 +1,151 @@ +package netneutrality.http; + +import java.io.IOException; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import com.google.common.base.Joiner; +import okhttp3.*; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public class WebModule { + + private String url; + private OkHttpClient client = new OkHttpClient(); + private Response response; + + public WebModule(String url) { + this.url = url; + } + + /** + * Send a request to the specified URL in the constructor. + *
Needs to be executed before any other method call + * + * @return an instance of the WebModule class with the Response of the Web Request + * @throws IOException + */ + public WebModule request() throws IOException { + + Request request = 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") + .build(); + response = client.newCall(request).execute(); + + return this; + } + + public WebModule request(Map headers) throws IOException { + + 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"); + + for (Map.Entry header : headers.entrySet()) { + builder.addHeader(header.getKey(), header.getValue()); + } + + Request request = builder.build(); + + response = client.newCall(request).execute(); + + return this; + } + + public WebModule post(TreeMap params, Map headers) throws IOException { + RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), createJson(params)); + 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"); + + for (Map.Entry header : headers.entrySet()) { + builder.addHeader(header.getKey(), header.getValue()); + } + Request request = builder.build(); + response = client.newCall(request).execute(); + + return this; + } + + public static String createJson(TreeMap params) { + + + StringBuilder json = new StringBuilder(); + + for (Map.Entry param : params.entrySet()) { + String str = "\"" + param.getKey() + "\":\"" + param.getValue() + "\""; + json.append(str); + json.append(","); + } + json.insert(0, "{"); + + return (json.length() > 1 ? json.substring(0, json.length() - 1) + "}" : ""); + } + + public static String createJsonArray(List list) { + StringBuilder json = new StringBuilder(); + + for (String str : list) { + json.append("\"" + str + "\""); + json.append(","); + } + json.insert(0, "["); + + return (json.length() > 1 ? json.substring(0, json.length() - 1) + "]" : ""); + } + + public static String createJsonArray(TreeMap users) { + StringBuilder json = new StringBuilder(); + + for (Map.Entry param : users.entrySet()) { + String str = "{\"" + param.getKey() + "\":\"" + param.getValue() + "\"}"; + json.append(str); + json.append(","); + } + json.insert(0, "["); + + return (json.length() > 1 ? json.substring(0, json.length() - 1) + "]" : "[]"); + } + + /** + * @return the response as a JSONObject + * @throws JSONException + * @throws IOException + */ + public JSONObject getAsObject() throws JSONException, IOException { + if (response == null) + throw new RuntimeException("Request has not been sent"); + + return new JSONObject(response.body().string()); + } + + /** + * Use if your response start with an array : [ ] + * + * @return the response as a JSONArray + * @throws JSONException + * @throws IOException + */ + public JSONArray getAsArray() throws JSONException, IOException { + if (response == null) + throw new RuntimeException("Request has not been sent"); + + return new JSONArray(response.body().string()); + } + + /** + * @return the response as a String + * @throws JSONException + * @throws IOException + */ + public String getRawData() throws IOException { + if (response == null) + throw new RuntimeException("Request has not been sent"); + + return response.body().string(); + } + + +} diff --git a/src/main/java/netneutrality/http/server/GuildBrowser.java b/src/main/java/netneutrality/http/server/GuildBrowser.java new file mode 100644 index 0000000..86812b4 --- /dev/null +++ b/src/main/java/netneutrality/http/server/GuildBrowser.java @@ -0,0 +1,58 @@ +package netneutrality.http.server; + +/* + * Copyright (c) anthorob + * + * This file is closed-source. It should not be distributed or copied in any way or form + */ + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; +import net.dv8tion.jda.core.entities.Guild; +import net.dv8tion.jda.core.entities.Member; +import netneutrality.MusicBot; +import netneutrality.http.WebModule; + +import java.io.IOException; +import java.io.OutputStream; +import java.util.TreeMap; + +public class GuildBrowser implements HttpHandler { + + @Override + public void handle(HttpExchange he) throws IOException { + + + String url[] = he.getRequestURI().toString().split("/"); + StringBuilder response = new StringBuilder(); + String json; + + if (url.length > 2) { + TreeMap users = new TreeMap<>(); + for (Guild guild : MusicBot.getJDA().getGuilds()) { + if (guild.getName().equalsIgnoreCase(url[2])) { + for (Member member : guild.getMembers()) { + users.put(member.getUser().getName(), member.getEffectiveName()); + } + } + } + + json = WebModule.createJsonArray(users); + + } else { + for (Guild guild : MusicBot.getJDA().getGuilds()) { + response.append("\"" + guild.getName() + "\""); + response.append(","); + } + response.insert(0, "["); + + json = response.substring(0, response.length() - 1) + "]"; + } + + he.getResponseHeaders().add("Content-Type", "application/json"); + he.sendResponseHeaders(200, json.getBytes().length); + OutputStream os = he.getResponseBody(); + os.write(json.getBytes()); + os.close(); + } +} diff --git a/src/main/java/netneutrality/http/server/RootHandler.java b/src/main/java/netneutrality/http/server/RootHandler.java new file mode 100644 index 0000000..177c3a3 --- /dev/null +++ b/src/main/java/netneutrality/http/server/RootHandler.java @@ -0,0 +1,25 @@ +package netneutrality.http.server; + +/* + * Copyright (c) anthorob + * + * This file is closed-source. It should not be distributed or copied in any way or form + */ + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; + +import java.io.IOException; +import java.io.OutputStream; + +public class RootHandler implements HttpHandler { + + @Override + public void handle(HttpExchange he) throws IOException { + String response = "

Server start success if you see this message

"; + he.sendResponseHeaders(200, response.length()); + OutputStream os = he.getResponseBody(); + os.write(response.getBytes()); + os.close(); + } +} diff --git a/src/main/java/netneutrality/http/server/WebApi.java b/src/main/java/netneutrality/http/server/WebApi.java new file mode 100644 index 0000000..777fd32 --- /dev/null +++ b/src/main/java/netneutrality/http/server/WebApi.java @@ -0,0 +1,44 @@ +package netneutrality.http.server; + +/* + * Copyright (c) anthorob + * + * This file is closed-source. It should not be distributed or copied in any way or form + */ + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; +import com.sun.net.httpserver.HttpServer; +import net.dv8tion.jda.core.entities.Guild; +import net.dv8tion.jda.core.entities.Member; +import netneutrality.MusicBot; +import netneutrality.http.WebModule; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.util.TreeMap; + +public class WebApi { + + private int port = 9000; + private HttpServer server; + + public WebApi() { + System.out.println("Starting web server..."); + try { + server = HttpServer.create(new InetSocketAddress(port), 0); + } catch (IOException e) { + e.printStackTrace(); + } + server.createContext("/", new RootHandler()); + server.createContext("/guild", new GuildBrowser()); + server.setExecutor(null); + server.start(); + System.out.println("Web server started at [" + server.getAddress().getAddress().toString() + "]"); + + } + + +} + diff --git a/src/main/java/netneutrality/utils/ChannelFunction.java b/src/main/java/netneutrality/utils/ChannelFunction.java new file mode 100644 index 0000000..3491596 --- /dev/null +++ b/src/main/java/netneutrality/utils/ChannelFunction.java @@ -0,0 +1,42 @@ +package netneutrality.utils; + +import java.util.List; + +import net.dv8tion.jda.core.entities.Message; +import net.dv8tion.jda.core.entities.TextChannel; + +public class ChannelFunction { + + public static void bulkDeleteMessage(TextChannel channel, int toDelete) { + + if (toDelete >= 2500) return; + + Thread deleteMessage = new Thread(new Runnable() { + + @Override + public void run() { + int toDeleteFinal = toDelete + 1; + int iteration = toDeleteFinal / 100; + for (int i = 0; i < iteration; i++) { + List messages = channel.getHistory().retrievePast(100).complete(); + channel.deleteMessages(messages).complete(); + toDeleteFinal -= 100; + + System.out.println("Deleted 100 message"); + } + + if (toDeleteFinal > 0) { + List messages = channel.getHistory().retrievePast(toDeleteFinal).complete(); + channel.deleteMessages(messages).complete(); + System.out.println("Deleted " + toDeleteFinal + " messages"); + } else { + System.out.println("No more message"); + } + + } + }); + + deleteMessage.start(); + + } +} diff --git a/src/main/java/netneutrality/utils/MessageFunction.java b/src/main/java/netneutrality/utils/MessageFunction.java new file mode 100644 index 0000000..587cfcf --- /dev/null +++ b/src/main/java/netneutrality/utils/MessageFunction.java @@ -0,0 +1,41 @@ +package netneutrality.utils; + +/* + * Copyright (c) anthorob + * + * This file is closed-source. It should not be distributed or copied in any way or form + */ + +import java.util.List; + +import net.dv8tion.jda.core.entities.ChannelType; +import net.dv8tion.jda.core.entities.Member; +import net.dv8tion.jda.core.entities.Message; + +public class MessageFunction { + + public static Member getStartingMention(Message message) { + if (isStartingWithMention(message)) { + return message.getMentionedMembers().get(0); + } + + return null; + + + } + + public static boolean isStartingWithMention(Message message) { + if (!message.isFromType(ChannelType.TEXT)) + return false; + + List mentions= message.getMentionedMembers(); + + for (Member member : mentions) { + if (message.getContentDisplay().startsWith("@" + member.getUser().getName())) + return true; + } + + return false; + } + +} diff --git a/src/main/java/netneutrality/utils/Settings.java b/src/main/java/netneutrality/utils/Settings.java new file mode 100644 index 0000000..e359063 --- /dev/null +++ b/src/main/java/netneutrality/utils/Settings.java @@ -0,0 +1,37 @@ +package netneutrality.utils; + +import net.dv8tion.jda.core.entities.Guild; +import net.dv8tion.jda.core.entities.TextChannel; +import net.dv8tion.jda.core.entities.User; + +public class Settings { + + public static final String DATETIMEFORMAT = "yyyy-MM-dd HH:mm:ss"; + public static String PREFIX = "$"; + private static User owner; + private static Guild ownerGuild; + private static TextChannel logChannel; + + public static User getCreator() { + return owner; + } + + public static void setCreator(User creator) { + Settings.owner = creator; + } + + public static Guild getOwnerGuild() { + return ownerGuild; + } + + public static void setOwnerGuild(Guild ownerGuild) { + Settings.ownerGuild = ownerGuild; + logChannel = ownerGuild.getTextChannelById("400383009330823179"); + } + + public static TextChannel getLogChannel() { + return logChannel; + } + + +} diff --git a/src/main/java/netneutrality/utils/UserFunction.java b/src/main/java/netneutrality/utils/UserFunction.java new file mode 100644 index 0000000..d5a8464 --- /dev/null +++ b/src/main/java/netneutrality/utils/UserFunction.java @@ -0,0 +1,20 @@ +package netneutrality.utils; + +import net.dv8tion.jda.core.Permission; +import net.dv8tion.jda.core.entities.Member; +import net.dv8tion.jda.core.entities.Role; + +public class UserFunction { + + public static boolean isAdmin(Member user) { + boolean isAdmin = false; + for(Role role : user.getRoles()) { + if (role.getPermissions().contains(Permission.MANAGE_SERVER) || role.getPermissions().contains(Permission.ADMINISTRATOR)) + isAdmin = true; + } + + return isAdmin; + } + + +}