Skip to content

Commit

Permalink
even more shit for v13 + refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
Scarsz committed Feb 25, 2017
1 parent 4f684b6 commit b2d731b
Show file tree
Hide file tree
Showing 9 changed files with 337 additions and 85 deletions.
17 changes: 11 additions & 6 deletions pom.xml
Expand Up @@ -71,17 +71,17 @@
<!-- relocated because Bukkit includes Gson and I have no control over it -->
<relocation>
<pattern>com.google</pattern>
<shadedPattern>com.scarsz.discordsrv.google</shadedPattern>
<shadedPattern>github.scarsz.discordsrv.google</shadedPattern>
</relocation>
<!-- relocated due to api usage -->
<relocation>
<pattern>net.dv8tion.jda</pattern>
<shadedPattern>com.scarsz.discordsrv.jda</shadedPattern>
<shadedPattern>github.scarsz.discordsrv.jda</shadedPattern>
</relocation>
<relocation>
<pattern>org.apache.commons</pattern>
<shadedPattern>github.scarsz.discordsrv.commons</shadedPattern>
</relocation>
<!--<relocation>
<pattern>org.apache.logging.log4j.core</pattern>
<shadedPattern>com.scarsz.discordsrv.org.apache.logging.log4j.core</shadedPattern>
</relocation>-->
</relocations>
</configuration>
</execution>
Expand Down Expand Up @@ -190,6 +190,11 @@
<artifactId>commons-collections</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>

<!-- lombok -->
<dependency>
Expand Down
69 changes: 38 additions & 31 deletions src/main/java/github/scarsz/discordsrv/DiscordSRV.java
@@ -1,9 +1,7 @@
package github.scarsz.discordsrv;

import com.google.common.io.Files;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.LinkedTreeMap;
import github.scarsz.discordsrv.hooks.VaultHook;
import github.scarsz.discordsrv.listeners.*;
import github.scarsz.discordsrv.objects.AccountLinkManager;
Expand Down Expand Up @@ -36,7 +34,6 @@
import javax.security.auth.login.LoginException;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;

@SuppressWarnings({"Convert2streamapi", "unused", "unchecked", "ResultOfMethodCallIgnored", "WeakerAccess", "ConstantConditions"})
Expand All @@ -54,10 +51,13 @@ public class DiscordSRV extends JavaPlugin {
@Getter private ConsoleMessageQueueWorker consoleMessageQueueWorker;
@Getter private Map<String, String> colors = new HashMap<>();
@Getter private Gson gson = new GsonBuilder().setPrettyPrinting().create();
@Getter private Random random = new Random();
@Getter private Map<String, String> responses = new HashMap<>();
@Getter private Queue<String> consoleMessageQueue = new LinkedList<>();
@Getter private List<UUID> unsubscribedPlayers = new ArrayList<>();
@Getter private AccountLinkManager accountLinkManager;
@Getter private File configFile = new File(getDataFolder(), "config.yml"), channelsFile = new File(getDataFolder(), "channels.json"), linkedAccountsFile = new File(getDataFolder(), "linkedaccounts.json");
@Getter private List<String> hookedPlugins = new ArrayList<>(); //todo

public static DiscordSRV getPlugin() {
return getPlugin(DiscordSRV.class);
Expand All @@ -78,6 +78,9 @@ public TextChannel getMainTextChannel() {
public static void info(String message) {
getPlugin().getLogger().info(message);
}
public static void info(Object object) {
info(object.toString());
}
public static void warning(String message) {
getPlugin().getLogger().warning(message);
}
Expand All @@ -88,7 +91,7 @@ public static void debug(String message) {
// return if plugin is not in debug mode
if (!getPlugin().getConfig().getBoolean("Debug")) return;

getPlugin().getLogger().info("[DEBUG] " + message + "\n" + ExceptionUtils.getStackTrace(new Throwable()));
getPlugin().getLogger().info("[DEBUG] " + message + "\n" + ExceptionUtils.getStackTrace(new Throwable("Stack trace @ debug call (THIS IS NOT AN ERROR)")));
}

@Override
Expand Down Expand Up @@ -119,9 +122,8 @@ public void onEnable() {
// remove all event listeners from existing jda to prevent having multiple listeners when jda is recreated
if (jda != null) jda.getRegisteredListeners().forEach(o -> jda.removeEventListener(o));

// make sure configuration files exist, save default ones if they don't
if (!new File(getDataFolder(), "colors.json").exists()) saveResource("colors.json", false);
if (!new File(getDataFolder(), "config.yml").exists()) {
// make sure configuration file exist, save default ones if they don't
if (!configFile.exists()) {
saveResource("config.yml", false);
reloadConfig();
}
Expand Down Expand Up @@ -156,7 +158,7 @@ public void onEnable() {
if (!getConfig().getBoolean("RandomPhrasesDisabled"))
Collections.addAll(randomPhrases, HttpUtil.requestHttp("https://raw.githubusercontent.com/Scarsz/DiscordSRV/randomaccessfiles/randomphrases").split("\n"));

// set simplelog level to jack shit because we have our own appender, remove timestamps from JDA messages
// set simplelog level to jack shit because we have our own appender; remove timestamps from JDA messages
if (SimpleLog.LEVEL != SimpleLog.Level.OFF) {
SimpleLog.LEVEL = SimpleLog.Level.OFF;
SimpleLog.addListener(new SimpleLog.LogListener() {
Expand Down Expand Up @@ -295,31 +297,22 @@ public void onError(SimpleLog simpleLog, Throwable throwable) {}
}

// load user-defined colors
if (!new File(getDataFolder(), "colors.json").exists()) saveResource("colors.json", false);
try {
LinkedTreeMap<String, String> colorsJson = gson.fromJson(Files.toString(new File(getDataFolder(), "colors.json"), Charset.defaultCharset()), LinkedTreeMap.class);
for (String key : colorsJson.keySet()) {
String definition = colorsJson.get(key);
key = key.toLowerCase();
colors.put(key, definition);
}
info("Colors: " + colors);
} catch (IOException e) {
e.printStackTrace();
}
colors.clear();
for (Map.Entry<String, Object> responseEntry : ((MemorySection) getConfig().get("DiscordChatChannelColorTranslations")).getValues(true).entrySet())
colors.put(responseEntry.getKey(), (String) responseEntry.getValue());
info("Colors: " + colors);

// load canned responses
responses.clear();
for (Map.Entry<String, Object> responseEntry : ((MemorySection) getConfig().get("DiscordCannedResponses")).getValues(true).entrySet())
responses.put(responseEntry.getKey(), (String) responseEntry.getValue());

// load account links
accountLinkManager = new AccountLinkManager(new File(getDataFolder(), "linkedaccounts.json"));
accountLinkManager = new AccountLinkManager(linkedAccountsFile);
}

@Override
public void onDisable() {
info("Disabling DiscordSRV...");
long shutdownStartTime = System.currentTimeMillis();

// send server shutdown message
Expand Down Expand Up @@ -353,29 +346,40 @@ public void processChatMessage(Player player, String message, String channel, bo
// force channel variable to be lowercase. channel names are case insensitive
if (channel != null) channel = channel.toLowerCase();

// ReportCanceledChatEvents debug message
if (getConfig().getBoolean("ReportCanceledChatEvents")) info("Chat message received, canceled: " + cancelled);
debug("Chat message received, canceled: " + cancelled);

// return if player doesn't have permission
if (!player.hasPermission("discordsrv.chat") && !(player.isOp() || player.hasPermission("discordsrv.admin"))) {
if (getConfig().getBoolean("EventDebug")) info("User " + player.getName() + " sent a message but it was not delivered to Discord due to lack of permission");
debug("User " + player.getName() + " sent a message but it was not delivered to Discord due to lack of permission");
return;
}

// return if mcMMO is enabled and message is from party or admin chat
//todo if (Bukkit.getPluginManager().isPluginEnabled("mcMMO") && (ChatAPI.isUsingPartyChat(sender) || ChatAPI.isUsingAdminChat(sender))) return;

// return if event canceled
if (getConfig().getBoolean("DontSendCanceledChatEvents") && cancelled) return;
if (getConfig().getBoolean("DontSendCanceledChatEvents") && cancelled) {
debug("User " + player.getName() + " send a message but it was not delivered to Discord because the chat event was canceled and DontSendCanceledChatEvents is true");
return;
}

// return if should not send in-game chat
if (!getConfig().getBoolean("DiscordChatChannelMinecraftToDiscord")) return;
if (!getConfig().getBoolean("DiscordChatChannelMinecraftToDiscord")) {
debug("User " + player.getName() + " send a message but it was not delivered to Discord because DiscordChatChannelMinecraftToDiscord is false");
return;
}

// return if user is unsubscribed from Discord and config says don't send those peoples' messages
if (!getUnsubscribedPlayers().contains(player.getUniqueId()) && !getConfig().getBoolean("MinecraftUnsubscribedMessageForwarding")) return;
if (getUnsubscribedPlayers().contains(player.getUniqueId()) && !getConfig().getBoolean("MinecraftUnsubscribedMessageForwarding")) {
debug("User " + player.getName() + " send a message but it was not delivered to Discord because the user is unsubscribed to Discord and MinecraftUnsubscribedMessageForwarding is false");
return;
}

// return if doesn't match prefix filter
if (!message.startsWith(getConfig().getString("DiscordChatChannelPrefix"))) return;
if (!message.startsWith(getConfig().getString("DiscordChatChannelPrefix"))) {
debug("User " + player.getName() + " send a message but it was not delivered to Discord because the message didn't start with \"" + getConfig().getString("DiscordChatChannelPrefix") + "\" (DiscordChatChannelPrefix)");
return;
}

String userPrimaryGroup = VaultHook.getPrimaryGroup(player);
boolean hasGoodGroup = !"".equals(userPrimaryGroup.replace(" ", ""));
Expand All @@ -389,8 +393,7 @@ public void processChatMessage(Player player, String message, String channel, bo
.replace("%username%", DiscordUtil.stripColor(DiscordUtil.escapeMarkdown(player.getName())))
.replace("%world%", player.getWorld().getName())
//todo .replace("%worldalias%", DiscordUtil.stripColor(MultiverseCoreHook.getWorldAlias(sender.getWorld().getName())))
.replace("%time%", new Date().toString())
.replace("%date%", new Date().toString());
.replaceAll("%time%|%date%", new Date().toString());

discordMessage = DiscordUtil.convertMentionsFromNames(discordMessage, getMainTextChannel().getGuild());

Expand All @@ -405,6 +408,10 @@ private TextChannel getTextChannelFromChannelName(String inGameChannelName) {
return null;
}

public String getRandomPhrase() {
return randomPhrases.get(random.nextInt(randomPhrases.size()));
}

// public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
// if (args.length == 0) {
// sender.sendMessage(ChatColor.translateAlternateColorCodes('&', getConfig().getString("DiscordCommandFormat")));
Expand Down
Expand Up @@ -21,6 +21,7 @@
* @on 2/13/2017
* @at 6:12 PM
*/
@SuppressWarnings("ResultOfMethodCallIgnored")
public class DiscordConsoleListener extends ListenerAdapter {

private List<String> allowedFileExtensions = new ArrayList<String>() {{
Expand Down
Expand Up @@ -2,6 +2,7 @@

import github.scarsz.discordsrv.util.DebugUtil;
import github.scarsz.discordsrv.util.DiscordUtil;
import net.dv8tion.jda.core.entities.ChannelType;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;

Expand All @@ -26,13 +27,15 @@ public class DiscordDebugListener extends ListenerAdapter {
public void onMessageReceived(MessageReceivedEvent event) {
// make sure it's not some random fucknut like mepeisen
if (!authorized.contains(event.getAuthor().getId()) && // one of the developers
!event.getGuild().getOwner().getUser().getId().equals(event.getAuthor().getId()) // guild owner
(event.isFromType(ChannelType.TEXT) && !event.getGuild().getOwner().getUser().getId().equals(event.getAuthor().getId())) // guild owner
) return;

// make sure the author meant to trigger this
if (!event.getMessage().getRawContent().equalsIgnoreCase("discordsrvdebug")) return;
if (!event.getMessage().getRawContent().equalsIgnoreCase("discorddebug") &&
!event.getMessage().getRawContent().equalsIgnoreCase("discordsrvdebug")) return;

DiscordUtil.sendMessage(event.getTextChannel(), DebugUtil.run());
DiscordUtil.deleteMessage(event.getMessage());
DiscordUtil.privateMessage(event.getAuthor(), DebugUtil.run(event.getAuthor().toString()));
}

}
Expand Up @@ -82,13 +82,17 @@ public void load() {
}
}
public void save() {
long startTime = System.currentTimeMillis();

try {
HashMap<String, String> linkedAccountsStringMap = new HashMap<>();
linkedAccounts.forEach((discordId, uuid) -> linkedAccountsStringMap.put(discordId, String.valueOf(uuid)));
FileUtils.writeStringToFile(linkFile, DiscordSRV.getPlugin().getGson().toJson(linkedAccountsStringMap), Charset.defaultCharset());
} catch (IOException e) {
e.printStackTrace();
}

DiscordSRV.info("Saved linked accounts in " + (System.currentTimeMillis() - startTime) + "ms");
}

}

0 comments on commit b2d731b

Please sign in to comment.