Modify DB scheme and update dependencies

This commit is contained in:
anthorob committed 2022-01-04 16:57:44 -05:00
1 parent 9902a3c913
commit 94980bf419
14 files changed
+324 -124

No files matched your search

+8 -8
View File
@@ -91,13 +91,13 @@
<dependency>
<groupId>net.dv8tion</groupId>
<artifactId>JDA</artifactId>
<version>4.3.0_277</version>
<version>4.4.0_350</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.1</version>
<version>4.9.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.json/json -->
@@ -111,7 +111,7 @@
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.9.12</version>
<version>0.10.2</version>
</dependency>
<dependency>
@@ -122,17 +122,17 @@
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.14.1</version>
<version>2.17.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.14.1</version>
<version>2.17.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.14.1</version>
<version>2.17.0</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
@@ -143,13 +143,13 @@
<dependency>
<groupId>org.fusesource.jansi</groupId>
<artifactId>jansi</artifactId>
<version>2.3.4</version>
<version>2.4.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.sedmelluq</groupId>
<artifactId>lavaplayer</artifactId>
<version>1.3.77</version>
<version>1.3.78</version>
</dependency>
<dependency>
<groupId>junit</groupId>
+183
View File
@@ -0,0 +1,183 @@
-- phpMyAdmin SQL Dump
-- version 5.1.0
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: Jan 04, 2022 at 09:55 PM
-- Server version: 10.4.10-MariaDB
-- PHP Version: 7.4.19
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `netneutrality`
--
-- --------------------------------------------------------
--
-- Table structure for table `blacklist`
--
DROP TABLE IF EXISTS `blacklist`;
CREATE TABLE IF NOT EXISTS `blacklist` (
`guild_id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`word` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`enabled` tinyint(1) NOT NULL,
`creator_id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`guild_id`,`word`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `guilds`
--
DROP TABLE IF EXISTS `guilds`;
CREATE TABLE IF NOT EXISTS `guilds` (
`guild_id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`logging` int(11) DEFAULT 0,
`log_channel` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`guild_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `guilds`
--
INSERT INTO `guilds` (`guild_id`, `logging`, `log_channel`) VALUES
('195386426400047105', 0, NULL),
('250767028397408256', 0, NULL);
--
-- Triggers `guilds`
--
DROP TRIGGER IF EXISTS `insert_settings`;
DELIMITER $$
CREATE TRIGGER `insert_settings` AFTER INSERT ON `guilds` FOR EACH ROW INSERT INTO guild_settings(guild_id) VALUES (new.guild_id)
$$
DELIMITER ;
-- --------------------------------------------------------
--
-- Table structure for table `guild_settings`
--
DROP TABLE IF EXISTS `guild_settings`;
CREATE TABLE IF NOT EXISTS `guild_settings` (
`guild_id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`music_role` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`music_channel` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`blacklist_exclude_channels` mediumtext COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`guild_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `guild_settings`
--
INSERT INTO `guild_settings` (`guild_id`, `music_role`, `music_channel`, `blacklist_exclude_channels`) VALUES
('195386426400047105', NULL, NULL, NULL),
('250767028397408256', NULL, NULL, NULL);
-- --------------------------------------------------------
--
-- Table structure for table `logging`
--
DROP TABLE IF EXISTS `logging`;
CREATE TABLE IF NOT EXISTS `logging` (
`guild_id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`channel_id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`enabled` tinyint(4) NOT NULL,
PRIMARY KEY (`guild_id`,`channel_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `log_message`
--
DROP TABLE IF EXISTS `log_message`;
CREATE TABLE IF NOT EXISTS `log_message` (
`guild_id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`channel_id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`user_id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`date_sent` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`message_id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`message` varchar(2000) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`edited_message` varchar(2000) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`message_id`),
KEY `fk_log_guilds` (`guild_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `permissions`
--
DROP TABLE IF EXISTS `permissions`;
CREATE TABLE IF NOT EXISTS `permissions` (
`guild_id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`role_id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`type` int(11) DEFAULT NULL,
`command` int(11) DEFAULT NULL,
PRIMARY KEY (`guild_id`,`role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `web_users`
--
DROP TABLE IF EXISTS `web_users`;
CREATE TABLE IF NOT EXISTS `web_users` (
`id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` mediumtext COLLATE utf8mb4_unicode_ci NOT NULL,
`token` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`expires` timestamp NOT NULL DEFAULT current_timestamp(),
`refresh_token` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `blacklist`
--
ALTER TABLE `blacklist`
ADD CONSTRAINT `fk_blacklist_guilds` FOREIGN KEY (`guild_id`) REFERENCES `guilds` (`guild_id`);
--
-- Constraints for table `guild_settings`
--
ALTER TABLE `guild_settings`
ADD CONSTRAINT `fk_guildid_guilds` FOREIGN KEY (`guild_id`) REFERENCES `guilds` (`guild_id`);
--
-- Constraints for table `log_message`
--
ALTER TABLE `log_message`
ADD CONSTRAINT `fk_log_guilds` FOREIGN KEY (`guild_id`) REFERENCES `guilds` (`guild_id`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
@@ -42,6 +42,7 @@ public class GuildManager {
}
public String getSetting(String key) {
reloadSettings();
return guildEntity.getSettings().getSettingByKey(key);
}
@@ -20,7 +20,8 @@ public abstract class AbstractMusicCommand extends AbstractCommand {
@Override
public boolean canBeExecutedBy(Guild guild, Member member) {
String roleDb = GuildManager.getManager(guild).getSetting("music_role");
String roleDb = GuildManager.getManager(guild).getSetting("music.role");
System.out.println(roleDb);
if (!roleDb.isEmpty()) {
Role neededRole = MusicBot.getJDA().getRoleById(roleDb);
@@ -1,7 +1,6 @@
package netneutrality.db.controllers;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
@@ -15,14 +14,10 @@ public class DBBlacklist extends AbstractController {
private final Logger logger = LoggerFactory.getLogger(DBBlacklist.class);
public DBBlacklist() {
}
public void add(MBlacklist obj, Consumer<Boolean> success) {
isAlreadyBlacklisted(obj.getWord(), obj.getServerId(), blacklisted -> {
if (blacklisted == 0) {
database.prepareAndExecuteAsync("INSERT INTO blacklist VALUES(?,?,?,?)", obj.getWord(), obj.getServerId(), obj.isEnabled(), obj.getCreatorId()).async();
database.prepareAndExecuteAsync("INSERT INTO blacklist VALUES(?,?,?,?)", obj.getServerId(), obj.getWord(), obj.isEnabled(), obj.getCreatorId()).async();
success.accept(true);
} else {
success.accept(false);
@@ -34,7 +29,7 @@ public class DBBlacklist extends AbstractController {
public void delete(String word, String serverId, Consumer<Boolean> success) {
isAlreadyBlacklisted(word, serverId, blacklisted -> {
if (blacklisted >= 1) {
database.prepareAndExecuteAsync("DELETE FROM blacklist WHERE word = ? AND serverId = ?", word, serverId).async();
database.prepareAndExecuteAsync("DELETE FROM blacklist WHERE word = ? AND guild_id = ?", word, serverId).async();
logger.debug("removed word from blacklist");
success.accept(true);
} else {
@@ -49,7 +44,7 @@ public class DBBlacklist extends AbstractController {
isAlreadyBlacklisted(word, serverId, blacklisted -> {
if (blacklisted >= 1) {
database.prepareAndExecuteAsync("UPDATE blacklist SET isEnabled = 1 WHERE word = ? AND serverId = ?", word, serverId).async();
database.prepareAndExecuteAsync("UPDATE blacklist SET enabled = 1 WHERE word = ? AND guild_id = ?", word, serverId).async();
logger.info("enabled");
success.accept(true);
} else {
@@ -64,7 +59,7 @@ public class DBBlacklist extends AbstractController {
isAlreadyBlacklisted(word, serverId, blacklisted -> {
if (blacklisted >= 1) {
database.prepareAndExecuteAsync("UPDATE blacklist SET isEnabled = 0 WHERE word = ? AND serverId = ?", word, serverId).async();
database.prepareAndExecuteAsync("UPDATE blacklist SET enabled = 0 WHERE word = ? AND guild_id = ?", word, serverId).async();
logger.info("disabled");
success.accept(true);
} else {
@@ -78,7 +73,7 @@ public class DBBlacklist extends AbstractController {
@Deprecated
public void getBlacklistForWord(String word, String serverId, Consumer<MBlacklist> success) {
database.prepareAndExecuteAsync("SELECT * FROM blacklist WHERE word = ? AND serverId = ?", word, serverId).async((table -> {
database.prepareAndExecuteAsync("SELECT * FROM blacklist WHERE word = ? AND guild_id = ?", word, serverId).async((table -> {
MBlacklist blacklisted = null;
if (table.getNbRows() > 0) {
@@ -91,7 +86,7 @@ public class DBBlacklist extends AbstractController {
}
public void getBlacklistFromServer(String serverId, Consumer<ArrayList<MBlacklist>> success) {
database.prepareAndExecuteAsync("SELECT * FROM blacklist WHERE serverId = ? AND isEnabled = 1", serverId).async(model -> {
database.prepareAndExecuteAsync("SELECT * FROM blacklist WHERE guild_id = ? AND enabled = 1", serverId).async(model -> {
ArrayList<MBlacklist> output = new ArrayList<>();
if (model.getNbRows() > 0) {
@@ -108,9 +103,9 @@ public class DBBlacklist extends AbstractController {
}
@Deprecated
public ArrayList<MBlacklist> getBlacklistFromServer(String serverId) throws ExecutionException, InterruptedException {
public ArrayList<MBlacklist> getBlacklistFromServer(String serverId) {
MTableModel model = database.prepareAndExecuteAsync("SELECT * FROM blacklist WHERE serverId = ? AND isEnabled = 1", serverId).blocking();
MTableModel model = database.prepareAndExecuteAsync("SELECT * FROM blacklist WHERE guild_id = ? AND enabled = 1", serverId).blocking();
ArrayList<MBlacklist> output = new ArrayList<>();
if (model.getNbRows() > 0) {
@@ -128,7 +123,7 @@ public class DBBlacklist extends AbstractController {
private boolean isAlreadyBlacklisted(String word, String serverId) {
AtomicBoolean result = new AtomicBoolean();
database.prepareAndExecuteAsync("SELECT COUNT(*) FROM blacklist WHERE word = ? AND serverId = ?", word, serverId).async(table -> {
database.prepareAndExecuteAsync("SELECT COUNT(*) FROM blacklist WHERE word = ? AND guild_id = ?", word, serverId).async(table -> {
if (!table.isEmpty()) {
result.set((int) table.getRowModel(0).getItem(0) != 0);
}
@@ -140,7 +135,7 @@ public class DBBlacklist extends AbstractController {
private void isAlreadyBlacklisted(String word, String serverId, Consumer<Integer> result) {
database.prepareAndExecuteAsync("SELECT COUNT(*) FROM blacklist WHERE word = ? AND serverId = ?", word, serverId).async(table -> {
database.prepareAndExecuteAsync("SELECT COUNT(*) FROM blacklist WHERE word = ? AND guild_id = ?", word, serverId).async(table -> {
if (!table.isEmpty()) {
int count = Integer.parseInt(table.getRowModel(0).getItem(0).toString());
@@ -13,7 +13,6 @@ public class DBGuild extends AbstractController {
public void insertGuildInDB(Guild g) {
if (!database.exists("guilds", "guild_id", g.getId())) {
database.prepareAndExecuteAsync("INSERT INTO guilds VALUES(?, ?, ?)", g.getId(), "0", null).blocking();
database.prepareAndExecuteAsync("INSERT INTO guild_settings VALUES(?)", g.getId()).blocking();
}
}
@@ -1,9 +1,7 @@
package netneutrality.db.controllers;
import java.sql.SQLException;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.sql.ResultSet;
import java.util.Date;
import java.util.function.Consumer;
import net.dv8tion.jda.api.entities.Guild;
@@ -15,16 +13,13 @@ import netneutrality.db.DBController;
import netneutrality.db.MysqlDatabase;
import netneutrality.db.models.MMessage;
import netneutrality.db.models.MTableModel;
import netneutrality.handler.LogHandler;
import netneutrality.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DBMessage extends AbstractController {
private final static Logger logger = LoggerFactory.getLogger(DBMessage.class);
public DBMessage() {
}
/**
* Returns an instance of {@link MysqlDatabase} with the database name as set in the {@link DBController} class
@@ -39,7 +34,7 @@ public class DBMessage extends AbstractController {
String serverid = guild.getId();
String channelid = channel.getId();
String userid = author.getId();
String datesent = message.getTimeCreated().format(DateTimeFormatter.ofPattern(Settings.getInstance().DATETIMEFORMAT));
Date datesent = new Date(message.getTimeCreated().toInstant().toEpochMilli());
String messageid = message.getId();
String msg = message.getContentRaw().trim();
@@ -47,12 +42,12 @@ public class DBMessage extends AbstractController {
}
public void logEdit(String messageId, String newMessage) {
database.prepareAndExecuteAsync("UPDATE log_message SET editedMessage = ? WHERE messageId = ?", newMessage, messageId).async();
database.prepareAndExecuteAsync("UPDATE log_message SET edited_message = ? WHERE message_id = ?", newMessage, messageId).async();
}
public MMessage getMessage(String messageId) {
MTableModel table = database.prepareAndExecuteAsync("SELECT * FROM log_message WHERE messageId = ?", messageId).blocking();
MTableModel table = database.prepareAndExecuteAsync("SELECT * FROM log_message WHERE message_id = ?", messageId).blocking();
if (table.getNbRows() > 0) {
return new MMessage(table.getRowModel(0));
}
@@ -61,7 +56,7 @@ public class DBMessage extends AbstractController {
}
public void getMessagesFromUser(String username, String serverName, int max, Consumer<ArrayList<MMessage>> success) {
database.prepareAndExecuteAsync("SELECT * FROM log_message WHERE userId = ? AND serverId = ? ORDER BY dateSent DESC LIMIT ?", username, serverName, max).async(table -> {
database.prepareAndExecuteAsync("SELECT * FROM log_message WHERE user_id = ? AND server_id = ? ORDER BY dateSent DESC LIMIT ?", username, serverName, max).async(table -> {
ArrayList<MMessage> messages = new ArrayList<>();
if (table.getNbRows() > 0) {
@@ -79,7 +74,7 @@ public class DBMessage extends AbstractController {
public ArrayList<MMessage> getMessagesFromUser(String username, String serverName, int max) {
ArrayList<MMessage> messages = new ArrayList<>();
MTableModel table = database.prepareAndExecuteAsync("SELECT * FROM log_message WHERE userId = ? AND serverId = ? ORDER BY dateSent DESC LIMIT ?", username, serverName, max).blocking();;
MTableModel table = database.prepareAndExecuteAsync("SELECT * FROM log_message WHERE user_id = ? AND server_id = ? ORDER BY date_sent DESC LIMIT ?", username, serverName, max).blocking();;
if (table.getNbRows() > 0) {
for (int row = 0; row < max; row++) {
messages.add(new MMessage(table.getRowModel(row)));
@@ -90,7 +85,7 @@ public class DBMessage extends AbstractController {
}
public String getMessageString(String messageId) {
MTableModel table = database.prepareAndExecuteAsync("SELECT message FROM log_message WHERE messageId = ?", messageId).blocking();
MTableModel table = database.prepareAndExecuteAsync("SELECT message FROM log_message WHERE message_id = ?", messageId).blocking();
return (String) table.getRowModel(0).getItem(0);
}
@@ -0,0 +1,33 @@
package netneutrality.http.server;/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.IOException;
import java.io.OutputStream;
public abstract class AbstractHandler implements HttpHandler {
public abstract void handle(HttpExchange exchange) throws IOException;
public void sendStringResponse(HttpExchange exchange, String str) throws IOException {
exchange.sendResponseHeaders(200, str.length());
OutputStream os = exchange.getResponseBody();
os.write(str.getBytes());
os.close();
}
public void sendJsonResponse(HttpExchange exchange, String str) throws IOException {
exchange.getResponseHeaders().add("Content-Type", "application/json");
exchange.sendResponseHeaders(200, str.length());
OutputStream os = exchange.getResponseBody();
os.write(str.getBytes());
os.close();
}
}
@@ -8,12 +8,15 @@ package netneutrality.http.server;/*
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import netneutrality.MusicBot;
import netneutrality.http.WebModule;
import org.apache.logging.log4j.LogManager;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.TreeMap;
public class ActionHandler implements HttpHandler {
public class ActionHandler extends AbstractHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
@@ -21,12 +24,21 @@ public class ActionHandler implements HttpHandler {
if (path.equals("/actions/shutdown")) {
LogManager.getLogger(MusicBot.class).info("Request to shutdown received");
WebApi.sendStringResponse(exchange, "Shutting down..");
sendStringResponse(exchange, "Shutting down..");
System.exit(0);
return;
}
WebApi.sendStringResponse(exchange, path);
if (path.equals("/actions/status")) {
TreeMap<String, String> json = new TreeMap<>();
json.put("health", String.valueOf(MusicBot.getJDA().getStatus()));
json.put("ping", String.valueOf(MusicBot.getJDA().getGatewayPing()));
sendJsonResponse(exchange, WebModule.createJson(json));
return;
}
sendStringResponse(exchange, path);
}
}
@@ -1,58 +0,0 @@
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.api.entities.Guild;
import net.dv8tion.jda.api.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<String, String> 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();
}
}
@@ -0,0 +1,47 @@
package netneutrality.http.server;
/*
* Copyright (c) anthorob
*
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import netneutrality.MusicBot;
import netneutrality.http.WebModule;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
public class GuildHandler extends AbstractHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
String path = exchange.getRequestURI().getRawPath();
if (path.equals("/guilds/owner")) {
TreeMap<String, String> owners = new TreeMap<>();
JDA jda = MusicBot.getJDA();
jda.getGuilds().forEach(guild -> {
owners.put(guild.getId(), guild.getOwnerId());
});
sendJsonResponse(exchange, WebModule.createJsonArray(owners));
return;
}
sendStringResponse(exchange, path);
}
}
@@ -3,7 +3,8 @@ package netneutrality.http.server;
/*
* Copyright (c) anthorob
*
* This file is closed-source. It should not be distributed or copied in any way or form
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import com.sun.net.httpserver.HttpExchange;
@@ -12,14 +13,13 @@ import com.sun.net.httpserver.HttpHandler;
import java.io.IOException;
import java.io.OutputStream;
public class RootHandler implements HttpHandler {
public class RootHandler extends AbstractHandler {
@Override
public void handle(HttpExchange he) throws IOException {
public void handle(HttpExchange exchange) throws IOException {
String response = "<h1>Server start success if you see this message</h1>";
he.sendResponseHeaders(200, response.length());
OutputStream os = he.getResponseBody();
os.write(response.getBytes());
os.close();
sendStringResponse(exchange, response);
}
}
@@ -3,17 +3,16 @@ package netneutrality.http.server;
/*
* Copyright (c) anthorob
*
* This file is closed-source. It should not be distributed or copied in any way or form
* https://xtremcommunity.com/
* https://discord.gg/CdFcyQ
*/
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import netneutrality.thread.BaseThread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
@@ -36,22 +35,15 @@ public class WebApi {
} catch (IOException e) {
e.printStackTrace();
}
server.createContext("/", new RootHandler());
server.createContext("/actions", new ActionHandler());
server.createContext("/guild", new GuildBrowser());
server.createContext("/guilds", new GuildHandler());
server.setExecutor(executor);
server.start();
logger.info("Web server started at [" + server.getAddress() + "]");
}
public static void sendStringResponse(HttpExchange exchange, String str) throws IOException {
exchange.sendResponseHeaders(200, str.length());
OutputStream os = exchange.getResponseBody();
os.write(str.getBytes());
os.close();
}
}
@@ -33,7 +33,7 @@ public class TrackScheduler extends AudioEventAdapter {
// something is playing, it returns false and does nothing. In that case the player was already playing so this
// track goes to the queue instead.
boolean start = player.startTrack(track, true);
channel.getManager().setTopic(":speaker: Now playing : " + track.getInfo().title).queue();
//channel.getManager().setTopic(":speaker: Now playing : " + track.getInfo().title).queue();
if (!start) {
queue.offer(track);
@@ -55,7 +55,7 @@ public class TrackScheduler extends AudioEventAdapter {
public void resetTopic() {
if (this.channel != null) {
this.channel.getManager().setTopic(this.topic).queue();
//this.channel.getManager().setTopic(this.topic).queue();
}
this.topic = "";
@@ -69,10 +69,10 @@ public class TrackScheduler extends AudioEventAdapter {
// giving null to startTrack, which is a valid argument and will simply stop the player.
AudioTrack track = queue.poll();
if (track != null) {
channel.getManager().setTopic(":speaker: Now playing : " + track.getInfo().title).queue();
//channel.getManager().setTopic(":speaker: Now playing : " + track.getInfo().title).queue();
player.startTrack(track, false);
} else {
channel.getManager().setTopic(topic).queue();
//channel.getManager().setTopic(topic).queue();
}
@@ -109,11 +109,11 @@ public class TrackScheduler extends AudioEventAdapter {
@Override
public void onTrackException(AudioPlayer player, AudioTrack track, FriendlyException exception) {
// An already playing track threw an exception (track end event will still be received separately)
channel.sendMessage("Error while playing track: " + track.getInfo().title).queue();
}
@Override
public void onTrackStuck(AudioPlayer player, AudioTrack track, long thresholdMs) {
// Audio track has been unable to provide us any audio, might want to just start a new track
nextTrack();
}
}