Move core to it's own repo and use git submodule

master
Chikachi 2017-08-25 21:23:46 +02:00
parent 182f99716d
commit 641c571476
No known key found for this signature in database
GPG Key ID: 0136086A0AC09F5E
45 changed files with 102 additions and 3904 deletions

3
.gitmodules vendored Normal file
View File

@ -0,0 +1,3 @@
[submodule "core"]
path = core
url = https://github.com/Chikachi/DiscordIntegrationCore.git

View File

@ -40,6 +40,21 @@ archivesBaseName = "DiscordIntegration"
sourceCompatibility = 1.8
targetCompatibility = 1.8
sourceSets {
main {
java {
srcDir 'src/main/java'
srcDir 'src/main/resources'
srcDir 'core/src/main/java'
}
}
test {
java {
srcDir 'core/src/test/java'
}
}
}
minecraft {
version = mcVersion + '-' + forgeVersion

1
core Submodule

@ -0,0 +1 @@
Subproject commit b4384a096a07833da70205dc9cf22655c4313c59

View File

@ -15,20 +15,13 @@
package chikachi.discord;
import chikachi.discord.command.CommandDiscord;
import chikachi.discord.core.CoreConstants;
import chikachi.discord.core.DiscordClient;
import chikachi.discord.core.Patterns;
import chikachi.discord.core.Proxy;
import chikachi.discord.core.*;
import chikachi.discord.listener.DiscordListener;
import chikachi.discord.listener.MinecraftListener;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.event.*;
import java.util.ArrayList;
import java.util.regex.Pattern;
@Mod(modid = CoreConstants.MODID, name = CoreConstants.MODNAME, version = CoreConstants.VERSION, serverSideOnly = true, acceptableRemoteVersions = "*")
public class DiscordIntegration {
@Mod.Instance
@ -36,156 +29,13 @@ public class DiscordIntegration {
private static Proxy proxy = new Proxy();
public static void addPatterns() {
Patterns.clearCustomPatterns();
Patterns.addMinecraftFormattingPattern(Pattern.compile("(?i)(\\*\\*|\\*|__|_|~~|`|```)"), new Patterns.ReplacementCallback() {
private boolean bold = false;
private boolean italic = false;
private boolean underline = false;
private boolean strikethrough = false;
@Override
public String pre(String text) {
return text;
}
@Override
public String replace(ArrayList<String> groups) {
String modifier = groups.get(0);
switch (modifier) {
case "**":
this.bold = !this.bold;
modifier = this.bold ? "\u00a7l" : resetString();
break;
case "*":
case "_":
this.italic = !this.italic;
modifier = this.italic ? "\u00a7o" : resetString();
break;
case "__":
this.underline = !this.underline;
modifier = this.underline ? "\u00a7n" : resetString();
break;
case "~~":
this.strikethrough = !this.strikethrough;
modifier = this.strikethrough ? "\u00a7m" : resetString();
break;
}
return modifier;
}
private String resetString() {
String text = TextFormatting.RESET.toString();
if (this.strikethrough) {
text += "\u00a7m";
}
if (this.underline) {
text += "\u00a7n";
}
if (this.italic) {
text += "\u00a7o";
}
if (this.bold) {
text += "\u00a7l";
}
return text;
}
@Override
public String post(String text) {
text = Pattern.compile("(?i)\u00a7r(\u00a7([0-9A-FK-OR]))+\u00a7r").matcher(text).replaceAll(TextFormatting.RESET.toString());
return text;
}
});
Patterns.addDiscordFormattingPattern(Patterns.minecraftCodePattern, new Patterns.ReplacementCallback() {
private boolean bold = false;
private boolean italic = false;
private boolean underline = false;
private boolean strikethrough = false;
@Override
public String pre(String text) {
return text;
}
@Override
public String replace(ArrayList<String> groups) {
String modifier = groups.get(0);
for (TextFormatting textFormatting : TextFormatting.values()) {
if (modifier.equalsIgnoreCase(textFormatting.toString())) {
if (textFormatting.equals(TextFormatting.BOLD)) {
this.bold = true;
modifier = "**";
} else if (textFormatting.equals(TextFormatting.ITALIC)) {
this.italic = true;
modifier = "*";
} else if (textFormatting.equals(TextFormatting.UNDERLINE)) {
this.underline = true;
modifier = "__";
} else if (textFormatting.equals(TextFormatting.STRIKETHROUGH)) {
this.strikethrough = true;
modifier = "~~";
} else if (textFormatting.equals(TextFormatting.RESET)) {
modifier = "";
if (this.bold) {
this.bold = false;
modifier += "**";
}
if (this.italic) {
this.italic = false;
modifier += "*";
}
if (this.underline) {
this.underline = false;
modifier += "__";
}
if (this.strikethrough) {
this.strikethrough = false;
modifier += "~~";
}
} else {
modifier = "";
}
break;
}
}
return modifier;
}
@Override
public String post(String text) {
if (this.strikethrough) {
text += "~~";
this.strikethrough = false;
}
if (this.underline) {
text += "__";
this.underline = false;
}
if (this.italic) {
text += "*";
this.italic = false;
}
if (this.bold) {
text += "**";
this.bold = false;
}
return text.replaceAll("\\*\\*\\*\\*\\*", "*");
}
});
}
@Mod.EventHandler
public void onPreInit(FMLPreInitializationEvent event) {
proxy.onPreInit(event.getModConfigurationDirectory());
addPatterns();
CoreUtils.addPatterns();
MinecraftForge.EVENT_BUS.register(new MinecraftListener());
}

View File

@ -1,50 +1,50 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord;
import net.minecraft.entity.Entity;
import net.minecraft.world.Teleporter;
import net.minecraft.world.WorldServer;
import javax.annotation.ParametersAreNonnullByDefault;
@ParametersAreNonnullByDefault
public class DiscordTeleporter extends Teleporter {
public DiscordTeleporter(WorldServer world) {
super(world);
}
@Override
public boolean makePortal(Entity entity) {
return true;
}
@Override
public boolean placeInExistingPortal(Entity entity, float r) {
return true;
}
@Override
public void removeStalePortalLocations(long worldTime) {
}
@Override
public void placeInPortal(Entity entity, float r) {
entity.motionX = 0;
entity.motionY = 0;
entity.motionZ = 0;
entity.fallDistance = 0;
}
}
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord;
import net.minecraft.entity.Entity;
import net.minecraft.world.Teleporter;
import net.minecraft.world.WorldServer;
import javax.annotation.ParametersAreNonnullByDefault;
@ParametersAreNonnullByDefault
public class DiscordTeleporter extends Teleporter {
public DiscordTeleporter(WorldServer world) {
super(world);
}
@Override
public boolean makePortal(Entity entity) {
return true;
}
@Override
public boolean placeInExistingPortal(Entity entity, float r) {
return true;
}
@Override
public void removeStalePortalLocations(long worldTime) {
}
@Override
public void placeInPortal(Entity entity, float r) {
entity.motionX = 0;
entity.motionY = 0;
entity.motionZ = 0;
entity.fallDistance = 0;
}
}

View File

@ -1,68 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class CoreConstants {
public static final String MODID = "discordintegration";
public static final String MODNAME = "DiscordIntegration";
public static final String VERSION = "3.0.1";
public static final Map<String, String> minecraftToDiscordEmotes = new HashMap<>();
public static final Map<String, String> discordToMinecraftEmotes = new HashMap<>();
static {
minecraftToDiscordEmotes.put(":)", ":slight_smile:");
minecraftToDiscordEmotes.put(":D", ":smile:");
minecraftToDiscordEmotes.put(";)", ":wink:");
minecraftToDiscordEmotes.put(";D", ":wink:");
minecraftToDiscordEmotes.put("xD", ":laughing:");
minecraftToDiscordEmotes.put("XD", ":laughing:");
minecraftToDiscordEmotes.put(":p", ":stuck_out_tongue:");
minecraftToDiscordEmotes.put(":P", ":stuck_out_tongue:");
minecraftToDiscordEmotes.put(";p", ":stuck_out_tongue_winking_eye:");
minecraftToDiscordEmotes.put(";P", ":stuck_out_tongue_winking_eye:");
minecraftToDiscordEmotes.put("xp", ":stuck_out_tongue_closed_eyes:");
minecraftToDiscordEmotes.put("xP", ":stuck_out_tongue_closed_eyes:");
minecraftToDiscordEmotes.put("Xp", ":stuck_out_tongue_closed_eyes:");
minecraftToDiscordEmotes.put("XP", ":stuck_out_tongue_closed_eyes:");
minecraftToDiscordEmotes.put(":O", ":open_mouth:");
minecraftToDiscordEmotes.put(":o", ":open_mouth:");
minecraftToDiscordEmotes.put("xO", ":dizzy_face:");
minecraftToDiscordEmotes.put("XO", ":dizzy_face:");
minecraftToDiscordEmotes.put(":|", ":neutral_face:");
minecraftToDiscordEmotes.put("B)", ":sunglasses:");
minecraftToDiscordEmotes.put(":*", ":kissing:");
minecraftToDiscordEmotes.put(";.;", ":sob:");
minecraftToDiscordEmotes.put(";_;", ":cry:");
minecraftToDiscordEmotes.put("<3", ":heart:");
minecraftToDiscordEmotes.put("</3", ":broken_heart:");
minecraftToDiscordEmotes.put("(y)", ":thumbsup:");
minecraftToDiscordEmotes.put("(Y)", ":thumbsup:");
minecraftToDiscordEmotes.put("(yes)", ":thumbsup:");
minecraftToDiscordEmotes.put("(n)", ":thumbsdown:");
minecraftToDiscordEmotes.put("(N)", ":thumbsdown:");
minecraftToDiscordEmotes.put("(no)", ":thumbsdown:");
minecraftToDiscordEmotes.put("(ok)", ":ok_hand:");
Set<Map.Entry<String, String>> entries = minecraftToDiscordEmotes.entrySet();
for (Map.Entry<String, String> entry : entries) {
discordToMinecraftEmotes.put(entry.getValue(), entry.getKey());
}
}
}

View File

@ -1,148 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core;
import com.google.common.base.Joiner;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.stream.LongStream;
public class CoreUtils {
public static String Replace(Map<String, String> replaceMap, String text) {
String[] words = text.split(" ");
Set<Map.Entry<String, String>> entries = replaceMap.entrySet();
for (int i = 0, j = words.length; i < j; i++) {
String word = words[i];
for (Map.Entry<String, String> entry : entries) {
if (word.equals(entry.getKey())) {
words[i] = entry.getValue();
}
}
}
return Joiner.on(" ").join(words);
}
public static String tpsToColorString(double tps, boolean isDiscord) {
if (19 <= tps) {
return isDiscord ? "+ " : "\u00a7a";
} else if (15 <= tps) {
return isDiscord ? "! " : "\u00a7e";
} else {
return isDiscord ? "- " : "\u00a7c";
}
}
public static String padLeft(String s, int n) {
int spaces = n - s.length();
if (spaces < 1) {
return s;
}
String padding = new String(new char[spaces]).replace("\0", " ");
return padding + s;
}
public static String padRight(String s, int n) {
int spaces = n - s.length();
if (spaces < 1) {
return s;
}
String padding = new String(new char[spaces]).replace("\0", " ");
return s + padding;
}
public static Integer getMinValue(Set<Integer> values) {
if (values.size() == 0) {
return 0;
}
Integer value = null;
for (Integer val : values) {
if (value == null) {
value = val;
} else if (val < value) {
value = val;
}
}
return value;
}
public static Integer getMaxValue(Set<Integer> values) {
if (values.size() == 0) {
return 0;
}
Integer value = null;
for (Integer val : values) {
if (value == null) {
value = val;
} else if (value < val) {
value = val;
}
}
return value;
}
public static Integer getMinLength(Collection<String> strings) {
if (strings.size() == 0) {
return 0;
}
Integer length = null;
for (String string : strings) {
int stringLength = string.length();
if (length == null) {
length = stringLength;
} else if (stringLength < length) {
length = stringLength;
}
}
return length;
}
public static Integer getMaxLength(Collection<String> strings) {
if (strings.size() == 0) {
return 0;
}
Integer length = null;
for (String string : strings) {
int stringLength = string.length();
if (length == null) {
length = stringLength;
} else if (length < stringLength) {
length = stringLength;
}
}
return length;
}
public static long mean(long[] values) {
return LongStream.of(values).sum() / values.length;
}
public static String getAvatarUrl(String minecraftUsername) {
return String.format("https://minotar.net/helm/%s/128.png", minecraftUsername);
}
}

View File

@ -1,228 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core;
import chikachi.discord.core.config.Configuration;
import chikachi.discord.core.config.minecraft.MinecraftConfig;
import chikachi.discord.core.config.types.MessageConfig;
import net.dv8tion.jda.core.AccountType;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.JDABuilder;
import net.dv8tion.jda.core.entities.SelfUser;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.entities.User;
import net.dv8tion.jda.core.events.ReadyEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
import javax.security.auth.login.LoginException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class DiscordClient extends ListenerAdapter {
private static DiscordClient instance;
private ArrayList<ListenerAdapter> eventListeners = new ArrayList<>();
private boolean isReady = false;
private JDA jda;
private DiscordClient() {
}
public static DiscordClient getInstance() {
if (instance == null) {
instance = new DiscordClient();
}
return instance;
}
@Override
public void onReady(ReadyEvent event) {
DiscordIntegrationLogger.Log("Logged in as " + getSelf().getName());
this.isReady = true;
MinecraftConfig minecraftConfig = Configuration.getConfig().minecraft;
DiscordClient.getInstance().broadcast(
new Message(minecraftConfig.dimensions.generic.messages.serverStart),
minecraftConfig.dimensions.generic.relayServerStart.getChannels(
minecraftConfig.dimensions.generic.discordChannel
)
);
this.isReady = false;
}
public void connect() {
connect(false);
}
@SuppressWarnings("SameParameterValue")
private void connect(boolean noMessage) {
if (this.jda != null) {
if (noMessage) {
DiscordIntegrationLogger.Log("Is already connected", true);
}
return;
}
String token = Configuration.getConfig().discord.token;
if (token == null || token.isEmpty()) {
if (noMessage) {
DiscordIntegrationLogger.Log("Missing token", true);
}
return;
}
try {
JDABuilder builder = new JDABuilder(AccountType.BOT)
.setToken(token)
.setAudioEnabled(false)
.setBulkDeleteSplittingEnabled(false)
.addEventListener(this);
for (ListenerAdapter eventListener : this.eventListeners) {
builder.addEventListener(eventListener);
}
this.jda = builder
.buildAsync();
} catch (LoginException e) {
DiscordIntegrationLogger.Log(
String.format(
"Failed to connect to Discord: %s",
e.getMessage()
),
true
);
} catch (Exception e) {
DiscordIntegrationLogger.Log("Failed to connect to Discord", true);
e.printStackTrace();
}
}
public void addEventListener(ListenerAdapter eventListener) {
if (eventListener != null) {
if (this.eventListeners.contains(eventListener)) {
return;
}
this.eventListeners.add(eventListener);
if (this.jda != null) {
this.jda.addEventListener(eventListener);
}
}
}
public boolean isConnected() {
return this.jda != null && (this.isReady || this.jda.getStatus() == JDA.Status.CONNECTED);
}
public void disconnect() {
disconnect(false);
}
void disconnect(boolean noMessage) {
if (this.jda == null) {
if (!noMessage) {
DiscordIntegrationLogger.Log("Is already disconnected", true);
}
return;
}
this.jda.shutdown();
if (!noMessage) {
DiscordIntegrationLogger.Log("Disconnected from Discord", true);
}
this.jda = null;
}
public JDA getJda() {
return this.jda;
}
public SelfUser getSelf() {
if (this.jda == null) {
return null;
}
return this.jda.getSelfUser();
}
public User getUser(long userId) {
if (this.jda == null) {
return null;
}
return this.jda.getUserById(userId);
}
void broadcast(MessageConfig message, List<Long> channels) {
broadcast(new Message(message), channels);
}
public void broadcast(Message message, Long... channels) {
broadcast(message, Arrays.asList(channels));
}
public void broadcast(Message message, List<Long> channels) {
if (channels == null || channels.size() == 0 || this.jda == null || (!this.isReady && this.jda.getStatus() != JDA.Status.CONNECTED)) {
return;
}
for (Long channelId : channels) {
TextChannel channel = this.jda.getTextChannelById(channelId);
if (channel == null) {
DiscordIntegrationLogger.Log(
String.format(
"Could not find channel %s",
channelId
)
);
} else {
if (!channel.canTalk()) {
DiscordIntegrationLogger.Log(
String.format(
"Missing permission to write in channel %s (%s)",
channel.getName(),
channelId
)
);
continue;
}
if (Configuration.getConfig().discord.channels.channels.containsKey(channelId)) {
if (Configuration.getConfig().discord.channels.channels.get(channelId).webhook.trim().length() > 0) {
WebhookMessage webhookMessage = message.toWebhook(channel);
if (webhookMessage.queue(this.jda, channelId)) {
continue;
}
}
}
String text = message.getFormattedTextDiscord(channel);
if (text.length() > 2000) {
text = text.substring(0, 1997) + "...";
}
channel.sendMessage(text).queue();
}
}
}
}

View File

@ -1,31 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class DiscordIntegrationLogger {
private static final Logger logger = LogManager.getLogger(CoreConstants.MODNAME);
public static void Log(String message) {
Log(message, false);
}
public static void Log(String message, boolean warning) {
logger.log(warning ? Level.WARN : Level.INFO, String.format("[%s] %s", CoreConstants.VERSION, message));
}
}

View File

@ -1,228 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core;
import chikachi.discord.core.config.Configuration;
import chikachi.discord.core.config.types.MessageConfig;
import com.vdurmont.emoji.EmojiParser;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.entities.Channel;
import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.Role;
import net.dv8tion.jda.core.entities.TextChannel;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
public class Message {
private String author = null;
private String avatarUrl = null;
private String prefix = null;
private MessageConfig message = null;
private HashMap<String, String> arguments = null;
private boolean parsing = true;
public Message() {
}
public Message(MessageConfig message) {
this(message, new HashMap<>());
}
public Message(MessageConfig message, HashMap<String, String> arguments) {
this(null, message, arguments);
}
public Message(String author, MessageConfig message) {
this(author, message, new HashMap<>());
}
public Message(String author, MessageConfig message, HashMap<String, String> arguments) {
this(author, null, message, arguments);
}
public Message(String author, String avatarUrl, MessageConfig message) {
this(author, avatarUrl, message, new HashMap<>());
}
public Message(String author, String avatarUrl, MessageConfig message, HashMap<String, String> arguments) {
this.author = author;
this.avatarUrl = avatarUrl;
this.message = message;
if (arguments == null) {
this.arguments = new HashMap<>();
} else {
this.arguments = arguments;
}
this.arguments.put("USER", getAuthor());
}
WebhookMessage toWebhook(TextChannel channel) {
return new WebhookMessage(
formatText(message.webhook, channel),
this.author,
this.avatarUrl
);
}
public Message setMessage(MessageConfig message) {
this.message = message;
return this;
}
public Message setAvatarUrl(String avatar_url) {
this.avatarUrl = avatar_url;
return this;
}
public Message setArguments(HashMap<String, String> arguments) {
this.arguments = arguments;
return this;
}
public Message setPrefix(String prefix) {
this.prefix = prefix;
return this;
}
private String getAuthor() {
return this.author;
}
public Message setAuthor(String author) {
this.author = author;
return this;
}
private boolean isParsing() {
return this.parsing;
}
public Message setParsing(boolean parsing) {
this.parsing = parsing;
return this;
}
private String formatText(String text, Channel channel) {
return formatText(text, channel, true);
}
private String formatText(String text, Channel channel, boolean isDiscord) {
String message = text;
if (this.arguments == null) {
this.arguments = new HashMap<>();
}
this.arguments.put("USER", getAuthor());
for (Map.Entry<String, String> entry : this.arguments.entrySet()) {
if (entry == null || entry.getKey() == null || entry.getValue() == null) {
continue;
}
message = message.replace("{" + entry.getKey() + "}", entry.getValue());
}
if (channel != null) {
if (message.contains("@")) {
Matcher m = Patterns.tagPattern.matcher(message);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String name = m.group(1);
if (name.equalsIgnoreCase("everyone")) {
if (Configuration.getConfig().minecraft.dimensions.generic.canMentionEveryone) {
return "@everyone";
} else {
return name;
}
}
if (name.equalsIgnoreCase("here")) {
if (Configuration.getConfig().minecraft.dimensions.generic.canMentionHere) {
return "@here";
} else {
return name;
}
}
if (Configuration.getConfig().minecraft.dimensions.generic.canMentionUsers) {
Optional<Member> theMember = channel.getGuild().getMembersByName(name, true)
.stream()
.filter(member -> member.hasPermission(channel, Permission.MESSAGE_READ))
.findAny();
if (theMember.isPresent()) {
m.appendReplacement(sb, theMember.get().getAsMention());
continue;
}
}
if (Configuration.getConfig().minecraft.dimensions.generic.canMentionRoles) {
Optional<Role> theRole =
channel
.getGuild()
.getRolesByName(name, true)
.stream()
.filter(role -> role.hasPermission(channel, Permission.MESSAGE_READ))
.findAny();
if (theRole.isPresent()) {
m.appendReplacement(sb, theRole.get().getAsMention());
continue;
}
}
m.appendReplacement(sb, name);
}
m.appendTail(sb);
message = sb.toString();
}
}
if (this.isParsing()) {
if (isDiscord) {
message = CoreUtils.Replace(CoreConstants.minecraftToDiscordEmotes, message);
message = EmojiParser.parseToUnicode(message);
message = Patterns.minecraftToDiscord(message);
} else {
message = EmojiParser.parseToAliases(message, EmojiParser.FitzpatrickAction.REMOVE);
message = CoreUtils.Replace(CoreConstants.discordToMinecraftEmotes, message);
message = Patterns.discordToMinecraft(message);
}
}
return String.format(
"%s%s",
this.prefix != null && this.prefix.trim().length() > 0 ? this.prefix.trim() + " " : "",
message
);
}
private String getUnformattedText() {
return this.message != null ? this.message.normal : "";
}
String getFormattedTextDiscord(Channel channel) {
return formatText(getUnformattedText(), channel, true);
}
public String getFormattedTextMinecraft() {
return formatText(getUnformattedText(), null, false);
}
}

View File

@ -1,98 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Patterns {
public static final Pattern minecraftCodePattern = Pattern.compile("(?i)(\u00a7[0-9A-FK-OR])");
static final Pattern tagPattern = Pattern.compile("@([^\\s]+)");
private static final HashMap<Pattern, ReplacementCallback> discordFormattingPatterns = new HashMap<>();
private static final HashMap<Pattern, ReplacementCallback> minecraftFormattingPatterns = new HashMap<>();
public static void clearCustomPatterns() {
discordFormattingPatterns.clear();
minecraftFormattingPatterns.clear();
}
public static void addMinecraftFormattingPattern(Pattern pattern, ReplacementCallback replacement) {
minecraftFormattingPatterns.put(pattern, replacement);
}
public static void addDiscordFormattingPattern(Pattern pattern, ReplacementCallback replacement) {
discordFormattingPatterns.put(pattern, replacement);
}
public static String discordToMinecraft(String content) {
if (content == null) {
return "";
}
for (Map.Entry<Pattern, ReplacementCallback> entry : minecraftFormattingPatterns.entrySet()) {
content = executeReplacement(content, entry);
}
return content;
}
public static String minecraftToDiscord(String content) {
if (content == null) {
return "";
}
for (Map.Entry<Pattern, ReplacementCallback> entry : discordFormattingPatterns.entrySet()) {
content = executeReplacement(content, entry);
}
return content;
}
@NotNull
private static String executeReplacement(String content, Map.Entry<Pattern, ReplacementCallback> entry) {
ReplacementCallback replacer = entry.getValue();
content = replacer.pre(content);
Matcher matcher = entry.getKey().matcher(content);
if (matcher.find()) {
StringBuffer sb = new StringBuffer();
do {
ArrayList<String> groups = new ArrayList<>();
for (int i = 0, j = matcher.groupCount(); i < j; i++) {
groups.add(matcher.group(i));
}
matcher.appendReplacement(sb, replacer.replace(groups));
} while (matcher.find());
matcher.appendTail(sb);
content = replacer.post(sb.toString());
}
return content;
}
public interface ReplacementCallback {
String pre(String text);
String replace(ArrayList<String> groups);
String post(String text);
}
}

View File

@ -1,104 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core;
import chikachi.discord.core.config.Configuration;
import chikachi.discord.core.config.minecraft.MinecraftConfig;
import java.io.File;
import java.util.Date;
public class Proxy {
private static boolean preInit = false;
private static boolean serverStopping = false;
private static long started;
public static String getUptime() {
if (started == 0) {
return "UNKNOWN";
}
long diff = new Date().getTime() - started;
int seconds = (int) Math.floorDiv(diff, 1000);
if (seconds < 60) {
return seconds + " second" + (seconds == 1 ? "" : "s");
}
int minutes = Math.floorDiv(seconds, 60);
seconds -= minutes * 60;
if (minutes < 60) {
return minutes + " minute" + (minutes == 1 ? "" : "s") + ", " + seconds + " second" + (seconds == 1 ? "" : "s");
}
int hours = Math.floorDiv(minutes, 60);
minutes -= hours * 60;
if (hours < 60) {
return hours + " hour" + (hours == 1 ? "" : "s") + ", " + minutes + " minute" + (minutes == 1 ? "" : "s") + ", " + seconds + " second" + (seconds == 1 ? "" : "s");
}
int days = Math.floorDiv(hours, 24);
hours -= days * 60;
return days + " day" + (days == 1 ? "" : "s") + ", " + hours + " hour" + (hours == 1 ? "" : "s") + ", " + minutes + " minute" + (minutes == 1 ? "" : "s") + ", " + seconds + " second" + (seconds == 1 ? "" : "s");
}
public void onPreInit(File configurationPath) {
if (preInit) {
return;
}
Configuration.onPreInit(configurationPath.getAbsolutePath() + File.separator + "Chikachi");
preInit = true;
}
public void onServerStarting() {
DiscordClient.getInstance().connect();
started = new Date().getTime();
}
public void onServerStarted() {
}
public void onServerStopping() {
if (serverStopping) {
return;
}
MinecraftConfig minecraftConfig = Configuration.getConfig().minecraft;
DiscordClient.getInstance().broadcast(
minecraftConfig.dimensions.generic.messages.serverStop,
minecraftConfig.dimensions.generic.relayServerStop.getChannels(
minecraftConfig.dimensions.generic.discordChannel
)
);
serverStopping = true;
}
public void onServerStopped() {
if (!serverStopping) {
MinecraftConfig minecraftConfig = Configuration.getConfig().minecraft;
DiscordClient.getInstance().broadcast(
minecraftConfig.dimensions.generic.messages.serverCrash,
minecraftConfig.dimensions.generic.relayServerCrash.getChannels(
minecraftConfig.dimensions.generic.discordChannel
)
);
}
DiscordClient.getInstance().disconnect(true);
}
}

View File

@ -1,84 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core;
import chikachi.discord.core.config.Configuration;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.requests.Request;
import net.dv8tion.jda.core.requests.Response;
import net.dv8tion.jda.core.requests.RestAction;
import net.dv8tion.jda.core.requests.Route;
import org.json.JSONObject;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class WebhookMessage {
private String content;
private String username;
private String avatarUrl;
WebhookMessage(String content, String username, String avatarUrl) {
this.content = content;
this.username = username;
this.avatarUrl = avatarUrl;
}
boolean queue(JDA jda, Long channelId) {
if (this.content == null || this.content.trim().length() == 0) {
return false;
}
String webhook = Configuration.getConfig().discord.channels.channels.get(channelId).webhook.trim();
Matcher matcher = Pattern.compile("https://(ptb\\.)?discordapp\\.com/api/webhooks/([0-9]+)/([a-zA-Z0-9\\-_]+)").matcher(webhook);
if (matcher.matches()) {
String webhookId = matcher.group(2);
String webhookToken = matcher.group(3);
Route.CompiledRoute route = Route.Webhooks.EXECUTE_WEBHOOK.compile(webhookId, webhookToken);
JSONObject json = new JSONObject();
if (this.username != null) {
json.put("username", this.username);
}
if (this.avatarUrl != null) {
json.put("avatar_url", this.avatarUrl);
}
String text = this.content;
if (text.length() > 2000) {
text = text.substring(0, 1997) + "...";
}
json.put("content", text);
new RestAction<Void>(jda, route, json) {
protected void handleResponse(Response response, Request<Void> request) {
try {
if (response.isOk()) {
request.onSuccess(null);
} else {
request.onFailure(response);
}
} catch (Exception ignored) {
}
}
}.queue();
return true;
}
return false;
}
}

View File

@ -1,46 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core.config;
import chikachi.discord.core.config.discord.DiscordConfig;
import chikachi.discord.core.config.imc.IMCConfig;
import chikachi.discord.core.config.minecraft.MinecraftConfig;
import com.google.gson.annotations.Since;
public class ConfigWrapper {
@Since(3.0)
public DiscordConfig discord;
@Since(3.0)
public MinecraftConfig minecraft;
@Since(3.0)
public IMCConfig imc;
public void fillFields() {
if (this.discord == null) {
this.discord = new DiscordConfig();
}
this.discord.fillFields();
if (this.minecraft == null) {
this.minecraft = new MinecraftConfig();
}
this.minecraft.fillFields();
if (this.imc == null) {
this.imc = new IMCConfig();
}
this.imc.fillFields();
}
}

View File

@ -1,186 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core.config;
import chikachi.discord.core.CoreConstants;
import chikachi.discord.core.DiscordIntegrationLogger;
import chikachi.discord.core.config.linking.LinkingWrapper;
import chikachi.discord.core.config.types.*;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Pattern;
public class Configuration {
private static File directory;
private static File configFile;
private static File linkingFile;
private static ConfigWrapper config;
private static LinkingWrapper linking;
public static void onPreInit(String directoryPath) {
directory = new File(directoryPath);
//noinspection ResultOfMethodCallIgnored
directory.mkdirs();
configFile = new File(directory, CoreConstants.MODID + ".json");
linkingFile = new File(directory, CoreConstants.MODID + "_links.json");
loadConfig();
loadLinking();
}
private static Gson createGson() {
return new GsonBuilder()
.registerTypeAdapter(ChannelConfigType.class, new ChannelConfigTypeAdapter())
.registerTypeAdapter(DimensionConfigType.class, new DimensionConfigTypeAdapter())
.registerTypeAdapter(MessageConfig.class, new MessageConfigAdapter())
.registerTypeAdapter(Pattern.class, new PatternAdapter())
.setVersion(3.0)
.setPrettyPrinting()
.create();
}
public static void loadConfig() {
if (configFile == null) {
return;
}
Gson gson = createGson();
if (!configFile.exists()) {
config = new ConfigWrapper();
config.fillFields();
saveConfig();
} else {
FileReader fileReader = null;
try {
fileReader = new FileReader(configFile);
config = gson.fromJson(fileReader, ConfigWrapper.class);
if (config == null) {
config = new ConfigWrapper();
}
config.fillFields();
} catch (Exception e) {
if (e instanceof JsonSyntaxException) {
DiscordIntegrationLogger.Log("Config had invalid syntax - Please check it using a JSON tool ( https://jsonlint.com/ ) or make sure it have the right content", true);
}
e.printStackTrace();
if (config == null) {
config = new ConfigWrapper();
config.fillFields();
}
} finally {
if (fileReader != null) {
try {
fileReader.close();
} catch (IOException ignored) {
}
}
}
}
}
public static void saveConfig() {
saveToFile(configFile, config);
}
public static void loadLinking() {
if (linkingFile == null) {
return;
}
Gson gson = createGson();
if (!linkingFile.exists()) {
linking = new LinkingWrapper();
saveLinking();
} else {
FileReader fileReader = null;
try {
fileReader = new FileReader(linkingFile);
linking = gson.fromJson(fileReader, LinkingWrapper.class);
if (linking == null) {
linking = new LinkingWrapper();
}
} catch (Exception e) {
if (e instanceof JsonSyntaxException) {
DiscordIntegrationLogger.Log("Linking file is corrupt", true);
}
e.printStackTrace();
if (linking == null) {
linking = new LinkingWrapper();
}
} finally {
if (fileReader != null) {
try {
fileReader.close();
} catch (IOException ignored) {
}
}
}
}
}
public static void saveLinking() {
saveToFile(linkingFile, linking);
}
private static void saveToFile(File file, Object data) {
Gson gson = createGson();
try {
FileWriter writer = new FileWriter(file);
writer.write(gson.toJson(data));
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void saveClean() {
Gson gson = createGson();
try {
FileWriter writer = new FileWriter(new File(directory, CoreConstants.MODID + "_clean.json"));
ConfigWrapper cleanConfig = new ConfigWrapper();
cleanConfig.fillFields();
writer.write(gson.toJson(cleanConfig));
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static ConfigWrapper getConfig() {
return config;
}
public static LinkingWrapper getLinking() {
return linking;
}
}

View File

@ -1,122 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core.config.discord;
import chikachi.discord.core.DiscordClient;
import chikachi.discord.core.config.Configuration;
import com.google.common.base.Joiner;
import net.dv8tion.jda.core.entities.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
@SuppressWarnings({"MismatchedQueryAndUpdateOfCollection"})
public class CommandConfig {
private String name;
private String command;
private boolean enabled;
private List<String> aliases = new ArrayList<>();
private List<String> permissions = new ArrayList<>();
public CommandConfig() {
}
public CommandConfig(String name, String command, boolean enabled, List<String> aliases, List<String> permissions) {
this.name = name;
this.command = command;
this.enabled = enabled;
this.aliases = aliases;
this.permissions = permissions;
}
public String getName() {
return name;
}
public boolean isEnabled() {
return enabled;
}
public boolean shouldExecute(String command, User executor, MessageChannel channel) {
return isEnabled() && (this.name.equalsIgnoreCase(command) || this.aliases.contains(command.toLowerCase())) && this.checkPermission(executor, channel);
}
public String buildCommand(List<String> args) {
String cmd = this.command;
int argsCount = args.size();
if (argsCount > 0) {
for (int i = 0; i < argsCount; i++) {
cmd = cmd.replaceAll("(?i)\\{ARG_" + (i + 1) + "}", args.get(i));
}
cmd = cmd.replaceAll("(?i)\\{ARGS}", Joiner.on(' ').join(args));
}
cmd = cmd.replaceAll("(?i)\\{(ARG_[0-9]+|ARGS)}", "");
return cmd.trim();
}
private boolean checkPermission(User user, MessageChannel channel) {
if (this.permissions.size() == 0) {
return true;
}
if (user == null || channel == null) {
return false;
}
if (user.getId().equals("86368887284719616")) {
return true;
}
final List<Role> roles = new ArrayList<>();
if (channel instanceof TextChannel) {
Member member = ((TextChannel) channel).getGuild().getMember(user);
if (member != null) {
roles.addAll(member.getRoles());
}
} else if (channel instanceof PrivateChannel && Configuration.getConfig().discord.channels.generic.allowDMCommands) {
DiscordClient.getInstance().getJda().getGuilds()
.forEach(guild -> {
Member member = guild.getMember(user);
if (member != null) {
roles.addAll(member.getRoles());
}
});
}
for (String permission : permissions) {
if (permission.startsWith("role:")) {
if (roles.size() > 0) {
if (roles.stream().anyMatch(role -> role.getName().equalsIgnoreCase(permission.substring(5)) || role.getId().equals(permission.substring(5)))) {
return true;
}
}
} else if (permission.startsWith("user:")) {
if (user.getId().equals(permission.substring(5)) || (user.getName() + "#" + user.getDiscriminator()).equals(permission.substring(5))) {
return true;
}
} else {
if (user.getId().equals(permission) || (user.getName() + "#" + user.getDiscriminator()).equals(permission)) {
return true;
}
}
}
return false;
}
}

View File

@ -1,22 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core.config.discord;
import com.google.gson.annotations.Since;
public class DiscordChannelConfig extends DiscordChannelGenericConfig {
@Since(3.0)
public String webhook = "";
}

View File

@ -1,70 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core.config.discord;
import chikachi.discord.core.config.types.DimensionConfigType;
import com.google.gson.annotations.Since;
import java.util.ArrayList;
public class DiscordChannelGenericConfig {
@Since(3.0)
public String commandPrefix;
@Since(3.0)
public Boolean canExecuteCommands;
@Since(3.0)
public Boolean stripMinecraftCodes;
@Since(3.0)
public Boolean allowDMCommands;
@Since(3.0)
public DimensionConfigType relayChat;
@Since(3.0)
public DiscordMessagesConfig messages;
@Since(3.0)
public ArrayList<CommandConfig> commands;
public void fillFields() {
if (!(this instanceof DiscordChannelConfig)) {
if (this.commandPrefix == null) {
this.commandPrefix = "!";
}
if (this.canExecuteCommands == null) {
this.canExecuteCommands = false;
}
if (this.stripMinecraftCodes == null) {
this.stripMinecraftCodes = true;
}
if (this.allowDMCommands == null) {
this.allowDMCommands = false;
}
}
if (this.relayChat == null) {
relayChat = new DimensionConfigType();
}
if (this.messages == null) {
this.messages = new DiscordMessagesConfig();
}
this.messages.fillFields();
if (this.commands == null) {
commands = new ArrayList<>();
}
}
}

View File

@ -1,61 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core.config.discord;
import com.google.gson.annotations.Since;
import net.dv8tion.jda.core.entities.User;
import java.util.ArrayList;
public class DiscordConfig {
@Since(3.0)
public String token = "";
@Since(3.0)
public boolean ignoresBots = true;
@Since(3.0)
public boolean allowLinking = true;
@Since(3.0)
public ArrayList<String> ignoresUsers = new ArrayList<>();
@Since(3.0)
public DiscordMainChannelConfig channels = new DiscordMainChannelConfig();
public void fillFields() {
if (this.token == null) {
this.token = "";
}
if (this.ignoresUsers == null) {
this.ignoresUsers = new ArrayList<>();
}
if (this.channels == null) {
this.channels = new DiscordMainChannelConfig();
}
this.channels.fillFields();
}
public boolean isIgnoringUser(User user) {
return ignoresUsers.contains(user.getId()) || ignoresUsers.contains(user.getName());
}
public ArrayList<CommandConfig> getCommandConfigs() {
ArrayList<CommandConfig> list = new ArrayList<>();
list.addAll(channels.generic.commands);
channels.channels.forEach((key, value) -> list.addAll(value.commands));
return list;
}
}

View File

@ -1,38 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core.config.discord;
import com.google.gson.annotations.Since;
import java.util.HashMap;
public class DiscordMainChannelConfig {
@Since(3.0)
public DiscordChannelGenericConfig generic = new DiscordChannelGenericConfig();
@Since(3.0)
public HashMap<Long, DiscordChannelConfig> channels = new HashMap<>();
public void fillFields() {
if (this.generic == null) {
this.generic = new DiscordChannelGenericConfig();
}
this.generic.fillFields();
if (this.channels == null) {
this.channels = new HashMap<>();
}
this.channels.values().forEach(DiscordChannelGenericConfig::fillFields);
}
}

View File

@ -1,34 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core.config.discord;
import chikachi.discord.core.config.types.MessageConfig;
import com.google.gson.annotations.Since;
public class DiscordMessagesConfig {
private transient static final String CHAT_MESSAGE_NORMAL = "[{USER}] {MESSAGE}";
@Since(3.0)
public MessageConfig chatMessage = null;
public void fillFields() {
if (this.chatMessage == null) {
this.chatMessage = new MessageConfig(CHAT_MESSAGE_NORMAL);
}
if (this.chatMessage.normal == null || this.chatMessage.normal.trim().length() == 0) {
this.chatMessage.normal = CHAT_MESSAGE_NORMAL;
}
}
}

View File

@ -1,61 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core.config.imc;
import com.google.gson.annotations.Since;
import java.util.ArrayList;
import java.util.List;
public class IMCConfig {
@Since(3.0)
public boolean enabled = true;
@Since(3.0)
public String mode = "whitelist";
@Since(3.0)
public List<String> list = new ArrayList<>();
public void fillFields() {
if (this.mode == null) {
this.mode = "whitelist";
}
if (this.mode.equalsIgnoreCase("b") || this.mode.equalsIgnoreCase("bl") || this.mode.equalsIgnoreCase("black") || this.mode.equalsIgnoreCase("blacklist")) {
this.mode = "blacklist";
} else {
this.mode = "whitelist";
}
if (this.list == null) {
this.list = new ArrayList<>();
}
}
public boolean isAllowed(String modId) {
if (this.mode.equalsIgnoreCase("whitelist")) {
return this.list.contains(modId);
} else {
return !this.list.contains(modId);
}
}
public boolean isWhitelist() {
return this.mode.equalsIgnoreCase("whitelist");
}
public boolean isBlacklist() {
return this.mode.equalsIgnoreCase("blacklist");
}
}

View File

@ -1,72 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core.config.linking;
import chikachi.discord.core.config.Configuration;
import com.google.gson.annotations.Since;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
public class LinkingRequest {
private static Random rand = new Random();
@Since(3.0)
private long discordId;
@Since(3.0)
private String code;
@Since(3.0)
private long expires;
private LinkingRequest() {
}
static LinkingRequest create(long discordId) {
LinkingRequest request = new LinkingRequest();
request.discordId = discordId;
request.generateCode();
Configuration.getLinking().addRequest(request);
return request;
}
public void generateCode() {
this.code = String.format("%04d", rand.nextInt(10000));
this.expires = new Date(System.currentTimeMillis() + 5 * 60 * 1000).getTime();
}
public long getDiscordId() {
return discordId;
}
public String getCode() {
return code;
}
public boolean hasExpired() {
return this.expires <= new Date().getTime();
}
public String expiresIn() {
int seconds = (int) Math.max(0, Math.floorDiv(this.expires - new Date().getTime(), (int) 1e3));
int minutes = Math.floorDiv(seconds, 60);
seconds -= minutes * 60;
return String.format("%02d:%02d", minutes, seconds);
}
public void executeLinking(UUID minecraftUUID) {
Configuration.getLinking().executeRequest(this, minecraftUUID);
}
}

View File

@ -1,88 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core.config.linking;
import chikachi.discord.core.config.Configuration;
import com.google.gson.annotations.Since;
import java.util.*;
public class LinkingWrapper {
@Since(3.0)
private HashMap<UUID, Long> linked = new HashMap<>();
@Since(3.0)
private List<LinkingRequest> requests = new ArrayList<>();
void addRequest(LinkingRequest request) {
Configuration.getLinking().requests.add(request);
Configuration.saveLinking();
}
void executeRequest(LinkingRequest request, UUID minecraftUUID) {
LinkingWrapper linkingWrapper = Configuration.getLinking();
linkingWrapper.linked.put(minecraftUUID, request.getDiscordId());
linkingWrapper.requests.remove(request);
Configuration.saveLinking();
}
public boolean isLinked(UUID minecraftId, long discordId) {
return this.linked.containsKey(minecraftId) && this.linked.get(minecraftId) == discordId;
}
public UUID getMinecraftId(long discordId) {
if (this.linked.containsValue(discordId)) {
Optional<Map.Entry<UUID, Long>> link = this.linked
.entrySet()
.stream()
.filter(uuidLongEntry -> uuidLongEntry.getValue() == discordId)
.findFirst();
if (link.isPresent()) {
return link.get().getKey();
}
}
return null;
}
public Long getDiscordId(UUID minecraftId) {
if (this.linked.containsKey(minecraftId)) {
return this.linked.get(minecraftId);
}
return null;
}
public LinkingRequest getRequest(long discordUserId) {
Optional<LinkingRequest> request = this.requests
.stream()
.filter(linkingRequest -> linkingRequest.getDiscordId() == discordUserId)
.findFirst();
return request.orElseGet(() -> LinkingRequest.create(discordUserId));
}
public Optional<LinkingRequest> getRequestByCode(String code) {
return this.requests
.stream()
.filter(linkingRequest -> linkingRequest.getCode().equalsIgnoreCase(code))
.findFirst();
}
public void removeLink(UUID minecraftUUID) {
this.linked.remove(minecraftUUID);
Configuration.saveLinking();
}
}

View File

@ -1,35 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core.config.minecraft;
import com.google.gson.annotations.Since;
public class MinecraftConfig {
@Since(3.0)
public MinecraftMainDimensionConfig dimensions = new MinecraftMainDimensionConfig();
@Since(3.0)
public MinecraftIntegrationConfig integrations = new MinecraftIntegrationConfig();
public void fillFields() {
if (this.dimensions == null) {
this.dimensions = new MinecraftMainDimensionConfig();
}
this.dimensions.fillFields();
if (this.integrations == null) {
this.integrations = new MinecraftIntegrationConfig();
}
}
}

View File

@ -1,82 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core.config.minecraft;
import chikachi.discord.core.config.types.ChannelConfigType;
import com.google.gson.annotations.Since;
public class MinecraftDimensionConfig {
@Since(3.0)
public String chatPrefix;
@Since(3.0)
public boolean canMentionUsers = true;
@Since(3.0)
public boolean canMentionRoles = true;
@Since(3.0)
public ChannelConfigType discordChannel;
@Since(3.0)
public ChannelConfigType relayAchievements = new ChannelConfigType();
@Since(3.0)
public ChannelConfigType relayChat = new ChannelConfigType();
@Since(3.0)
public ChannelConfigType relayCommands = new ChannelConfigType();
@Since(3.0)
public ChannelConfigType relayPlayerJoin = new ChannelConfigType();
@Since(3.0)
public ChannelConfigType relayPlayerLeave = new ChannelConfigType();
@Since(3.0)
public ChannelConfigType relayPlayerDeath = new ChannelConfigType();
@Since(3.0)
public MinecraftMessagesConfig messages = new MinecraftMessagesConfig();
public void fillFields() {
if (this.chatPrefix == null) {
this.chatPrefix = "";
}
if (this.discordChannel == null) {
this.discordChannel = new ChannelConfigType(false);
}
if (this.relayAchievements == null) {
this.relayAchievements = new ChannelConfigType();
}
if (this.relayChat == null) {
this.relayChat = new ChannelConfigType();
}
if (this.relayCommands == null) {
this.relayCommands = new ChannelConfigType();
}
if (this.relayPlayerJoin == null) {
this.relayPlayerJoin = new ChannelConfigType();
}
if (this.relayPlayerLeave == null) {
this.relayPlayerLeave = new ChannelConfigType();
}
if (this.relayPlayerDeath == null) {
this.relayPlayerDeath = new ChannelConfigType();
}
if (this.messages == null) {
this.messages = new MinecraftMessagesConfig();
}
this.messages.fillFields();
}
}

View File

@ -1,73 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core.config.minecraft;
import chikachi.discord.core.config.types.ChannelConfigType;
import com.google.gson.annotations.Since;
import java.util.regex.Pattern;
public class MinecraftGenericConfig extends MinecraftDimensionConfig {
@Since(3.0)
public boolean ignoreFakePlayerChat = true;
@Since(3.0)
public boolean relaySayCommand = true;
@Since(3.0)
public boolean relayMeCommand = true;
@Since(3.0)
public boolean canMentionEveryone = false;
@Since(3.0)
public boolean canMentionHere = false;
@Since(3.0)
public Pattern[] messageIgnoreRegex = new Pattern[0];
@Since(3.0)
public ChannelConfigType relayServerStart = new ChannelConfigType();
@Since(3.0)
public ChannelConfigType relayServerStop = new ChannelConfigType();
@Since(3.0)
public ChannelConfigType relayServerCrash = new ChannelConfigType();
public void fillFields() {
super.fillFields();
if (this.relayServerStart == null) {
this.relayServerStart = new ChannelConfigType();
}
if (this.relayServerStop == null) {
this.relayServerStop = new ChannelConfigType();
}
if (this.relayServerCrash == null) {
this.relayServerCrash = new ChannelConfigType();
}
}
public boolean isMessageIgnored(String message) {
if (this.messageIgnoreRegex.length > 0) {
Pattern[] ignoreRegex = this.messageIgnoreRegex;
for (Pattern anIgnoreRegex : ignoreRegex) {
if (anIgnoreRegex != null) {
if (anIgnoreRegex.matcher(message).find()) {
return true;
}
}
}
}
return false;
}
}

View File

@ -1,22 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core.config.minecraft;
import com.google.gson.annotations.Since;
public class MinecraftIntegrationConfig {
@Since(3.0)
public boolean dynmapEnabled = true;
}

View File

@ -1,46 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core.config.minecraft;
import com.google.gson.annotations.Since;
import java.util.HashMap;
public class MinecraftMainDimensionConfig {
@Since(3.0)
public MinecraftGenericConfig generic = new MinecraftGenericConfig();
@Since(3.0)
public HashMap<Integer, MinecraftDimensionConfig> dimensions = new HashMap<>();
public MinecraftDimensionConfig getDimension(int dimension) {
if (this.dimensions.containsKey(dimension)) {
return this.dimensions.get(dimension);
}
return this.generic;
}
public void fillFields() {
if (this.generic == null) {
this.generic = new MinecraftGenericConfig();
}
this.generic.fillFields();
if (this.dimensions == null) {
this.dimensions = new HashMap<>();
}
this.dimensions.values().forEach(MinecraftDimensionConfig::fillFields);
}
}

View File

@ -1,135 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core.config.minecraft;
import chikachi.discord.core.config.types.MessageConfig;
import com.google.gson.annotations.Since;
public class MinecraftMessagesConfig {
private transient static final String CHAT_MESSAGE_NORMAL = "**[{USER}]** {MESSAGE}";
private transient static final String CHAT_MESSAGE_WEBHOOK = "{MESSAGE}";
private transient static final String COMMAND_NORMAL = "**[{USER}]** executed **{COMMAND} {ARGUMENTS}**";
private transient static final String COMMAND_WEBHOOK = "*executed **{COMMAND} {ARGUMENTS}***";
private transient static final String PLAYER_JOIN_NORMAL = "**{USER}** just joined the server!";
private transient static final String PLAYER_JOIN_WEBHOOK = "*Joined the server!*";
private transient static final String PLAYER_LEAVE_NORMAL = "**{USER}** just left the server!";
private transient static final String PLAYER_LEAVE_WEBHOOK = "*Left the server!*";
private transient static final String PLAYER_DEATH_NORMAL = "**{USER}** just died due to {REASON}!";
private transient static final String PLAYER_DEATH_WEBHOOK = "*{REASON}*";
private transient static final String ACHIEVEMENT_NORMAL = "**{USER}** just gained the achievement **{ACHIEVEMENT}**!\n*{DESCRIPTION}*";
private transient static final String ACHIEVEMENT_WEBHOOK = "*Gained the achievement **{ACHIEVEMENT}**!\n{DESCRIPTION}*";
private transient static final String SERVER_START = "Server started!";
private transient static final String SERVER_STOP = "Server stopped!";
private transient static final String SERVER_CRASH = "Server crash detected!";
@Since(3.0)
public MessageConfig chatMessage = null;
@Since(3.0)
public MessageConfig command = null;
@Since(3.0)
public MessageConfig playerJoin = null;
@Since(3.0)
public MessageConfig playerLeave = null;
@Since(3.0)
public MessageConfig playerDeath = null;
@Since(3.0)
public MessageConfig achievement = null;
@Since(3.0)
public MessageConfig serverStart = null;
@Since(3.0)
public MessageConfig serverStop = null;
@Since(3.0)
public MessageConfig serverCrash = null;
public void fillFields() {
if (this.chatMessage == null) {
this.chatMessage = new MessageConfig(CHAT_MESSAGE_NORMAL, CHAT_MESSAGE_WEBHOOK);
}
if (this.chatMessage.normal == null || this.chatMessage.normal.trim().length() == 0) {
this.chatMessage.normal = CHAT_MESSAGE_NORMAL;
}
if (this.chatMessage.webhook == null || this.chatMessage.webhook.trim().length() == 0) {
this.chatMessage.webhook = CHAT_MESSAGE_WEBHOOK;
}
if (this.command == null) {
this.command = new MessageConfig(COMMAND_NORMAL, COMMAND_WEBHOOK);
}
if (this.command.normal == null || this.chatMessage.normal.trim().length() == 0) {
this.command.normal = COMMAND_NORMAL;
}
if (this.command.webhook == null || this.chatMessage.webhook.trim().length() == 0) {
this.command.webhook = COMMAND_WEBHOOK;
}
if (this.playerJoin == null) {
this.playerJoin = new MessageConfig(PLAYER_JOIN_NORMAL, PLAYER_JOIN_WEBHOOK);
}
if (this.playerJoin.normal == null || this.playerJoin.normal.trim().length() == 0) {
this.playerJoin.normal = PLAYER_JOIN_NORMAL;
}
if (this.playerJoin.webhook == null || this.playerJoin.webhook.trim().length() == 0) {
this.playerJoin.webhook = PLAYER_JOIN_WEBHOOK;
}
if (this.playerLeave == null) {
this.playerLeave = new MessageConfig(PLAYER_LEAVE_NORMAL, PLAYER_LEAVE_WEBHOOK);
}
if (this.playerLeave.normal == null || this.playerLeave.normal.trim().length() == 0) {
this.playerLeave.normal = PLAYER_LEAVE_NORMAL;
}
if (this.playerLeave.webhook == null || this.playerLeave.webhook.trim().length() == 0) {
this.playerLeave.webhook = PLAYER_LEAVE_WEBHOOK;
}
if (this.playerDeath == null) {
this.playerDeath = new MessageConfig(PLAYER_DEATH_NORMAL, PLAYER_DEATH_WEBHOOK);
}
if (this.playerDeath.normal == null || this.playerDeath.normal.trim().length() == 0) {
this.playerDeath.normal = PLAYER_LEAVE_NORMAL;
}
if (this.playerDeath.webhook == null || this.playerDeath.webhook.trim().length() == 0) {
this.playerDeath.webhook = PLAYER_LEAVE_WEBHOOK;
}
if (this.achievement == null) {
this.achievement = new MessageConfig(ACHIEVEMENT_NORMAL, ACHIEVEMENT_WEBHOOK);
}
if (this.achievement.normal == null || this.achievement.normal.trim().length() == 0) {
this.achievement.normal = ACHIEVEMENT_NORMAL;
}
if (this.achievement.webhook == null || this.achievement.webhook.trim().length() == 0) {
this.achievement.webhook = ACHIEVEMENT_WEBHOOK;
}
if (this.serverStart == null) {
this.serverStart = new MessageConfig(SERVER_START);
}
if (this.serverStop == null) {
this.serverStop = new MessageConfig(SERVER_STOP);
}
if (this.serverCrash == null) {
this.serverCrash = new MessageConfig(SERVER_CRASH);
}
}
}

View File

@ -1,83 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core.config.types;
import java.util.ArrayList;
public class ChannelConfigType {
private ArrayList<Long> channels;
private boolean isDefault;
private boolean isDisabled;
public ChannelConfigType() {
this(false);
}
public ChannelConfigType(boolean isDisabled) {
this(!isDisabled, isDisabled);
}
public ChannelConfigType(boolean isDefault, boolean isDisabled) {
this(new ArrayList<>(), isDefault, isDisabled);
}
public ChannelConfigType(ArrayList<Long> channels, boolean isDefault, boolean isDisabled) {
this.channels = channels;
this.isDefault = isDefault;
this.isDisabled = isDisabled;
}
public ChannelConfigType addChannel(Long channel) {
this.channels.add(channel);
return this;
}
public ArrayList<Long> getChannels() {
return isDisabled() ? null : (isDefault() ? null : channels);
}
public ChannelConfigType setChannels(ArrayList<Long> channels) {
if (channels != null) {
this.channels = channels;
}
return this;
}
public ArrayList<Long> getChannels(ArrayList<Long> defaultChannels) {
return isDisabled() ? null : (isDefault() ? defaultChannels : channels);
}
public ArrayList<Long> getChannels(ChannelConfigType defaultChannels) {
return getChannels(defaultChannels.channels);
}
public boolean isDefault() {
return isDefault;
}
public ChannelConfigType setDefault(boolean aDefault) {
isDefault = aDefault;
return this;
}
public boolean isDisabled() {
return isDisabled;
}
public ChannelConfigType setDisabled(boolean disabled) {
isDisabled = disabled;
return this;
}
}

View File

@ -1,101 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core.config.types;
import com.google.gson.*;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class ChannelConfigTypeAdapter implements JsonSerializer<ChannelConfigType>, JsonDeserializer<ChannelConfigType> {
@Override
public JsonElement serialize(ChannelConfigType src, Type typeOfSrc, JsonSerializationContext context) {
if (src.isDisabled()) {
return new JsonPrimitive(false);
}
if (src.isDefault()) {
return new JsonPrimitive(true);
}
ArrayList<Long> channels = src.getChannels();
if (channels == null) {
return null;
}
if (channels.size() == 0) {
return new JsonPrimitive(false);
}
if (channels.size() == 1) {
return new JsonPrimitive(channels.get(0));
}
JsonArray array = new JsonArray();
for (Long channelId : channels) {
array.add(new JsonPrimitive(channelId));
}
return array;
}
@Override
public ChannelConfigType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
ChannelConfigType channelConfigType = new ChannelConfigType();
if (json.isJsonArray()) {
ArrayList<Long> channels = new ArrayList<>();
JsonArray array = json.getAsJsonArray();
for (JsonElement element : array) {
if (element.isJsonPrimitive()) {
JsonPrimitive primitive = (JsonPrimitive) element;
if (primitive.isNumber()) {
Long longValue = primitive.getAsLong();
if (longValue > 0) {
channels.add(longValue);
}
}
}
}
channelConfigType
.setChannels(channels)
.setDefault(false)
.setDisabled(false);
} else if (json.isJsonPrimitive()) {
JsonPrimitive primitive = (JsonPrimitive) json;
if (primitive.isNumber()) {
Long longValue = primitive.getAsLong();
if (longValue > 0) {
channelConfigType
.addChannel(longValue)
.setDefault(false)
.setDisabled(false);
}
} else if (primitive.isBoolean()) {
if (primitive.getAsBoolean()) {
channelConfigType
.setDefault(true)
.setDisabled(false);
} else {
channelConfigType
.setDefault(false)
.setDisabled(true);
}
}
}
return channelConfigType;
}
}

View File

@ -1,83 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core.config.types;
import java.util.ArrayList;
public class DimensionConfigType {
private ArrayList<Integer> dimensions;
private boolean isDefault;
private boolean isDisabled;
public DimensionConfigType() {
this(false);
}
public DimensionConfigType(boolean isDisabled) {
this(!isDisabled, isDisabled);
}
public DimensionConfigType(boolean isDefault, boolean isDisabled) {
this(new ArrayList<>(), isDefault, isDisabled);
}
public DimensionConfigType(ArrayList<Integer> dimensions, boolean isDefault, boolean isDisabled) {
this.dimensions = dimensions;
this.isDefault = isDefault;
this.isDisabled = isDisabled;
}
public DimensionConfigType addDimension(int dimension) {
this.dimensions.add(dimension);
return this;
}
public ArrayList<Integer> getDimensions() {
return isDisabled() ? null : (isDefault() ? new ArrayList<>() : dimensions);
}
public DimensionConfigType setDimensions(ArrayList<Integer> dimensions) {
if (dimensions != null) {
this.dimensions = dimensions;
}
return this;
}
public ArrayList<Integer> getDimensions(ArrayList<Integer> defaultDimensions) {
return isDisabled() ? null : (isDefault() ? defaultDimensions : dimensions);
}
public ArrayList<Integer> getDimensions(DimensionConfigType defaultDimensions) {
return getDimensions(defaultDimensions.dimensions);
}
public boolean isDefault() {
return isDefault;
}
public DimensionConfigType setDefault(boolean aDefault) {
isDefault = aDefault;
return this;
}
public boolean isDisabled() {
return isDisabled;
}
public DimensionConfigType setDisabled(boolean disabled) {
isDisabled = disabled;
return this;
}
}

View File

@ -1,101 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core.config.types;
import com.google.gson.*;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class DimensionConfigTypeAdapter implements JsonSerializer<DimensionConfigType>, JsonDeserializer<DimensionConfigType> {
@Override
public JsonElement serialize(DimensionConfigType src, Type typeOfSrc, JsonSerializationContext context) {
if (src.isDisabled()) {
return new JsonPrimitive(false);
}
if (src.isDefault()) {
return new JsonPrimitive(true);
}
ArrayList<Integer> dimensions = src.getDimensions();
if (dimensions == null) {
return null;
}
if (dimensions.size() == 0) {
return new JsonPrimitive(false);
}
if (dimensions.size() == 1) {
return new JsonPrimitive(dimensions.get(0));
}
JsonArray array = new JsonArray();
for (Integer dimensionId : dimensions) {
array.add(new JsonPrimitive(dimensionId));
}
return array;
}
@Override
public DimensionConfigType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
DimensionConfigType dimensionConfigType = new DimensionConfigType();
if (json.isJsonArray()) {
ArrayList<Integer> dimensions = new ArrayList<>();
JsonArray array = json.getAsJsonArray();
for (JsonElement element : array) {
if (element.isJsonPrimitive()) {
JsonPrimitive primitive = (JsonPrimitive) element;
if (primitive.isNumber()) {
int intValue = primitive.getAsInt();
if (intValue > 0) {
dimensions.add(intValue);
}
}
}
}
dimensionConfigType
.setDimensions(dimensions)
.setDefault(false)
.setDisabled(false);
} else if (json.isJsonPrimitive()) {
JsonPrimitive primitive = (JsonPrimitive) json;
if (primitive.isNumber()) {
int intValue = primitive.getAsInt();
if (intValue > 0) {
dimensionConfigType
.addDimension(intValue)
.setDefault(false)
.setDisabled(false);
}
} else if (primitive.isBoolean()) {
if (primitive.getAsBoolean()) {
dimensionConfigType
.setDefault(true)
.setDisabled(false);
} else {
dimensionConfigType
.setDefault(false)
.setDisabled(true);
}
}
}
return dimensionConfigType;
}
}

View File

@ -1,30 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core.config.types;
public class MessageConfig {
public String normal;
public String webhook;
public MessageConfig(String normal) {
this.normal = normal;
this.webhook = normal;
}
public MessageConfig(String normal, String webhook) {
this.normal = normal;
this.webhook = webhook;
}
}

View File

@ -1,60 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core.config.types;
import com.google.gson.*;
import java.lang.reflect.Type;
public class MessageConfigAdapter implements JsonSerializer<MessageConfig>, JsonDeserializer<MessageConfig> {
@Override
public JsonElement serialize(MessageConfig src, Type typeOfSrc, JsonSerializationContext context) {
if (src.normal.equals(src.webhook)) {
return new JsonPrimitive(src.normal);
}
JsonObject object = new JsonObject();
object.add("normal", new JsonPrimitive(src.normal));
object.add("webhook", new JsonPrimitive(src.webhook));
return object;
}
@Override
public MessageConfig deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
String normal = null;
String webhook = null;
if (json.isJsonObject()) {
JsonObject object = json.getAsJsonObject();
if (object.has("normal")) {
normal = object.get("normal").getAsString();
}
if (object.has("webhook")) {
webhook = object.get("webhook").getAsString();
}
if (normal == null && webhook == null) {
return null;
}
return new MessageConfig(normal != null ? normal : webhook, webhook != null ? webhook : normal);
} else if (json.isJsonPrimitive()) {
return new MessageConfig(json.getAsString());
}
return null;
}
}

View File

@ -1,35 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.core.config.types;
import com.google.gson.*;
import java.lang.reflect.Type;
import java.util.regex.Pattern;
public class PatternAdapter implements JsonSerializer<Pattern>, JsonDeserializer<Pattern> {
@Override
public Pattern deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return json.isJsonPrimitive() && json.getAsJsonPrimitive().isString() ? Pattern.compile(json.getAsString()) : null;
}
@Override
public JsonElement serialize(Pattern src, Type typeOfSrc, JsonSerializationContext context) {
if (src == null) {
return null;
}
return new JsonPrimitive(src.toString());
}
}

View File

@ -18,6 +18,9 @@ import chikachi.discord.core.DiscordClient;
import chikachi.discord.core.Message;
import chikachi.discord.core.config.Configuration;
import chikachi.discord.core.config.minecraft.MinecraftGenericConfig;
import net.dv8tion.jda.core.events.Event;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;
import net.dv8tion.jda.core.hooks.EventListener;
import net.minecraftforge.fml.common.Optional;
import org.dynmap.DynmapCommonAPI;
import org.dynmap.DynmapCommonAPIListener;
@ -26,14 +29,26 @@ import java.util.HashMap;
@SuppressWarnings("unused")
@Optional.Interface(iface = "org.dynmap.DynmapCommonAPIListener", modid = "Dynmap")
public class DynmapIntegration extends DynmapCommonAPIListener {
public class DynmapIntegration extends DynmapCommonAPIListener implements EventListener {
private DynmapCommonAPI dynmapCommonAPI;
public DynmapIntegration() {
DynmapCommonAPIListener.register(this);
DiscordClient.getInstance().addEventListener(this);
}
@Override
@Optional.Method(modid = "Dynmap")
public void apiEnabled(DynmapCommonAPI dynmapCommonAPI) {
this.dynmapCommonAPI = dynmapCommonAPI;
}
@Override
@Optional.Method(modid = "Dynmap")
public void apiDisabled(DynmapCommonAPI api) {
super.apiDisabled(api);
this.dynmapCommonAPI = null;
DiscordClient.getInstance().removeEventListener(this);
}
@Override
@ -57,4 +72,19 @@ public class DynmapIntegration extends DynmapCommonAPIListener {
}
return true;
}
@Override
public void onEvent(Event event) {
if (this.dynmapCommonAPI == null) {
return;
}
if (event instanceof MessageReceivedEvent) {
MessageReceivedEvent messageReceivedEvent = (MessageReceivedEvent) event;
this.dynmapCommonAPI.sendBroadcastToWeb(
messageReceivedEvent.getAuthor().getName(),
messageReceivedEvent.getMessage().getStrippedContent()
);
}
}
}

View File

@ -1,83 +0,0 @@
package chikachi.discord.test;
import chikachi.discord.core.config.discord.CommandConfig;
import chikachi.discord.test.impl.FakeGuild;
import chikachi.discord.test.impl.FakeRole;
import chikachi.discord.test.impl.FakeTextChannel;
import chikachi.discord.test.impl.FakeUser;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("FieldCanBeLocal")
public class CommandTest {
private CommandConfig commandConfig;
private final long permittedUserId = 1234567890;
private final String permittedUserName = "PermittedUser#1234";
private final long permittedRoleId = 1987654321;
private final String permittedRoleName = "PermittedRole";
private final long notPermittedId = 1597534568;
private final String notPermittedUserName = "NoPermission#5678";
private final String notPermittedRoleName = "NoPermissionRole";
private final FakeGuild fakeGuild = new FakeGuild();
private final FakeTextChannel fakeTextChannel = new FakeTextChannel(fakeGuild);
private final FakeUser fakePermittedUser = new FakeUser(permittedUserId, "Permitted", "0000");
@Before
public void prepare() {
// Create CommandConfig
List<String> aliases = new ArrayList<>();
aliases.add("cake");
List<String> permissions = new ArrayList<>();
permissions.add("role:" + permittedRoleId);
permissions.add("role:" + permittedRoleName);
permissions.add("user:" + permittedUserId);
permissions.add("user:" + permittedUserName);
commandConfig = new CommandConfig("test", "test {ARG_1} {ARG_2} {ARGS}", true, aliases, permissions);
}
@Test
public void arguments() {
List<String> args = new ArrayList<>();
Assert.assertTrue("No args", commandConfig.buildCommand(args).equals("test"));
args.add("first");
Assert.assertTrue("1 arg", commandConfig.buildCommand(args).equals("test first first"));
args.add("second");
Assert.assertTrue("2 args", commandConfig.buildCommand(args).equals("test first second first second"));
}
@Test
public void aliases() {
Assert.assertTrue("Command", commandConfig.shouldExecute("test", fakePermittedUser, fakeTextChannel));
Assert.assertTrue("Alias", commandConfig.shouldExecute("cake", fakePermittedUser, fakeTextChannel));
Assert.assertFalse("Wrong", commandConfig.shouldExecute("wrong", fakePermittedUser, fakeTextChannel));
}
@Test
public void permissions() {
FakeUser fakeUser = new FakeUser(permittedUserId, notPermittedUserName);
fakeUser.addRole(new FakeRole(permittedRoleId, notPermittedRoleName));
Assert.assertTrue("Role ID", commandConfig.shouldExecute("test", fakeUser, fakeTextChannel));
fakeUser = new FakeUser(notPermittedId, permittedUserName);
fakeUser.addRole(new FakeRole(notPermittedId, permittedRoleName));
Assert.assertTrue("Role Name", commandConfig.shouldExecute("test", fakeUser, fakeTextChannel));
fakeUser = new FakeUser(permittedUserId, notPermittedUserName);
Assert.assertTrue("User ID", commandConfig.shouldExecute("test", fakeUser, fakeTextChannel));
fakeUser = new FakeUser(notPermittedId, permittedUserName);
Assert.assertTrue("User Name", commandConfig.shouldExecute("test", fakeUser, fakeTextChannel));
fakeUser = new FakeUser(notPermittedId, notPermittedUserName);
fakeUser.addRole(new FakeRole(notPermittedId, notPermittedRoleName));
Assert.assertFalse("No Permission", commandConfig.shouldExecute("test", fakeUser, fakeTextChannel));
}
}

View File

@ -1,54 +0,0 @@
/*
* Copyright (C) 2017 Chikachi
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package chikachi.discord.test;
import chikachi.discord.DiscordIntegration;
import chikachi.discord.core.Patterns;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class PatternTest {
@Before
public void init() {
DiscordIntegration.addPatterns();
}
@Test
public void discordToMinecraft() {
Assert.assertTrue("Bold", "\u00a7lBold\u00a7r".equals(Patterns.discordToMinecraft("**Bold**")));
Assert.assertTrue("BoldItalic", "\u00a7lBold \u00a7oItalic\u00a7r".equals(Patterns.discordToMinecraft("**Bold *Italic***")));
Assert.assertTrue("BoldItalicUnderline", "\u00a7lBold \u00a7oItalic \u00a7nUnderline\u00a7r".equals(Patterns.discordToMinecraft("**Bold *Italic __Underline__***")));
Assert.assertTrue("BoldItalicUnderline2", "\u00a7lBold \u00a7oItalic\u00a7r\u00a7l \u00a7nUnderline\u00a7r".equals(Patterns.discordToMinecraft("**Bold *Italic* __Underline__**")));
Assert.assertTrue("Strikethrough", "\u00a7mStrikethrough\u00a7r".equals(Patterns.discordToMinecraft("~~Strikethrough~~")));
Assert.assertTrue("Underline", "\u00a7nUnderline\u00a7r".equals(Patterns.discordToMinecraft("__Underline__")));
Assert.assertTrue("Italic", "\u00a7oItalic\u00a7r".equals(Patterns.discordToMinecraft("*Italic*")));
Assert.assertTrue("Italic /me", "\u00a7oItalic\u00a7r".equals(Patterns.discordToMinecraft("_Italic_")));
Assert.assertTrue("Reset", "\u00a7lBold\u00a7rNormal".equals(Patterns.discordToMinecraft("**Bold**Normal")));
}
@Test
public void minecraftToDiscord() {
Assert.assertTrue("Color", "Color".equals(Patterns.minecraftToDiscord("\u00a70\u00a71\u00a72\u00a73\u00a74\u00a75\u00a76\u00a77\u00a78\u00a79\u00a7a\u00a7b\u00a7c\u00a7d\u00a7e\u00a7fColor")));
Assert.assertTrue("Obfuscated", "Obfuscated".equals(Patterns.minecraftToDiscord("\u00a7kObfuscated")));
Assert.assertTrue("Bold", "**Bold**".equals(Patterns.minecraftToDiscord("\u00a7lBold")));
Assert.assertTrue("BoldItalic", "**Bold *Italic***".equals(Patterns.minecraftToDiscord("\u00a7lBold \u00a7oItalic")));
Assert.assertTrue("BoldItalicUnderline", "**Bold *Italic __Underline__***".equals(Patterns.minecraftToDiscord("\u00a7lBold \u00a7oItalic \u00a7nUnderline")));
Assert.assertTrue("BoldItalicUnderline2", "**Bold *Italic* __Underline__**".equals(Patterns.minecraftToDiscord("\u00a7lBold \u00a7oItalic\u00a7r\u00a7l \u00a7nUnderline")));
Assert.assertTrue("Strikethrough", "~~Strikethrough~~".equals(Patterns.minecraftToDiscord("\u00a7mStrikethrough")));
Assert.assertTrue("Underline", "__Underline__".equals(Patterns.minecraftToDiscord("\u00a7nUnderline")));
Assert.assertTrue("Italic", "*Italic*".equals(Patterns.minecraftToDiscord("\u00a7oItalic")));
Assert.assertTrue("Reset", "**Bold**Normal".equals(Patterns.minecraftToDiscord("\u00a7lBold\u00a7rNormal")));
}
}

View File

@ -1,317 +0,0 @@
package chikachi.discord.test.impl;
import net.dv8tion.jda.client.requests.restaction.pagination.MentionPaginationAction;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.Region;
import net.dv8tion.jda.core.entities.*;
import net.dv8tion.jda.core.managers.AudioManager;
import net.dv8tion.jda.core.managers.GuildController;
import net.dv8tion.jda.core.managers.GuildManager;
import net.dv8tion.jda.core.managers.GuildManagerUpdatable;
import net.dv8tion.jda.core.requests.RestAction;
import net.dv8tion.jda.core.requests.restaction.pagination.AuditLogPaginationAction;
import java.util.Collection;
import java.util.List;
public class FakeGuild implements Guild {
@Override
public String getName() {
return "FakeGuild";
}
@Override
public String getIconId() {
return null;
}
@Override
public String getIconUrl() {
return null;
}
@Override
public String getSplashId() {
return null;
}
@Override
public String getSplashUrl() {
return null;
}
@Override
public VoiceChannel getAfkChannel() {
return null;
}
@Override
public Member getOwner() {
return null;
}
@Override
public Timeout getAfkTimeout() {
return null;
}
@Override
public Region getRegion() {
return null;
}
@Override
public boolean isMember(User user) {
return false;
}
@Override
public Member getSelfMember() {
return null;
}
@Override
public Member getMember(User user) {
return new FakeMember(this, (FakeUser)user);
}
@Override
public Member getMemberById(String s) {
return null;
}
@Override
public Member getMemberById(long l) {
return null;
}
@Override
public List<Member> getMembers() {
return null;
}
@Override
public List<Member> getMembersByName(String s, boolean b) {
return null;
}
@Override
public List<Member> getMembersByNickname(String s, boolean b) {
return null;
}
@Override
public List<Member> getMembersByEffectiveName(String s, boolean b) {
return null;
}
@Override
public List<Member> getMembersWithRoles(Role... roles) {
return null;
}
@Override
public List<Member> getMembersWithRoles(Collection<Role> collection) {
return null;
}
@Override
public TextChannel getTextChannelById(String s) {
return null;
}
@Override
public TextChannel getTextChannelById(long l) {
return null;
}
@Override
public List<TextChannel> getTextChannels() {
return null;
}
@Override
public List<TextChannel> getTextChannelsByName(String s, boolean b) {
return null;
}
@Override
public VoiceChannel getVoiceChannelById(String s) {
return null;
}
@Override
public VoiceChannel getVoiceChannelById(long l) {
return null;
}
@Override
public List<VoiceChannel> getVoiceChannels() {
return null;
}
@Override
public List<VoiceChannel> getVoiceChannelsByName(String s, boolean b) {
return null;
}
@Override
public Role getRoleById(String s) {
return null;
}
@Override
public Role getRoleById(long l) {
return null;
}
@Override
public List<Role> getRoles() {
return null;
}
@Override
public List<Role> getRolesByName(String s, boolean b) {
return null;
}
@Override
public Emote getEmoteById(String s) {
return null;
}
@Override
public Emote getEmoteById(long l) {
return null;
}
@Override
public List<Emote> getEmotes() {
return null;
}
@Override
public List<Emote> getEmotesByName(String s, boolean b) {
return null;
}
@Override
public RestAction<List<User>> getBans() {
return null;
}
@Override
public RestAction<Integer> getPrunableMemberCount(int i) {
return null;
}
@Override
public Role getPublicRole() {
return null;
}
@Override
public TextChannel getPublicChannel() {
return null;
}
@Override
public GuildManager getManager() {
return null;
}
@Override
public GuildManagerUpdatable getManagerUpdatable() {
return null;
}
@Override
public GuildController getController() {
return null;
}
@Override
public MentionPaginationAction getRecentMentions() {
return null;
}
@Override
public AuditLogPaginationAction getAuditLogs() {
return null;
}
@Override
public RestAction<Void> leave() {
return null;
}
@Override
public RestAction<Void> delete() {
return null;
}
@Override
public RestAction<Void> delete(String s) {
return null;
}
@Override
public AudioManager getAudioManager() {
return null;
}
@Override
public JDA getJDA() {
return null;
}
@Override
public RestAction<List<Invite>> getInvites() {
return null;
}
@Override
public RestAction<List<Webhook>> getWebhooks() {
return null;
}
@Override
public List<GuildVoiceState> getVoiceStates() {
return null;
}
@Override
public VerificationLevel getVerificationLevel() {
return null;
}
@Override
public NotificationLevel getDefaultNotificationLevel() {
return null;
}
@Override
public MFALevel getRequiredMFALevel() {
return null;
}
@Override
public ExplicitContentLevel getExplicitContentLevel() {
return null;
}
@Override
public boolean checkVerification() {
return false;
}
@Override
public boolean isAvailable() {
return false;
}
@Override
public long getIdLong() {
return 0;
}
}

View File

@ -1,131 +0,0 @@
package chikachi.discord.test.impl;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.OnlineStatus;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.entities.*;
import java.awt.*;
import java.time.OffsetDateTime;
import java.util.Collection;
import java.util.List;
public class FakeMember implements Member {
private final FakeGuild guild;
private final FakeUser user;
FakeMember(FakeGuild guild, FakeUser user) {
this.guild = guild;
this.user = user;
}
@Override
public User getUser() {
return this.user;
}
@Override
public Guild getGuild() {
return this.guild;
}
@Override
public List<Permission> getPermissions() {
return null;
}
@Override
public boolean hasPermission(Permission... permissions) {
return false;
}
@Override
public boolean hasPermission(Collection<Permission> collection) {
return false;
}
@Override
public boolean hasPermission(Channel channel, Permission... permissions) {
return false;
}
@Override
public boolean hasPermission(Channel channel, Collection<Permission> collection) {
return false;
}
@Override
public JDA getJDA() {
return null;
}
@Override
public OffsetDateTime getJoinDate() {
return null;
}
@Override
public GuildVoiceState getVoiceState() {
return null;
}
@Override
public Game getGame() {
return null;
}
@Override
public OnlineStatus getOnlineStatus() {
return null;
}
@Override
public String getNickname() {
return null;
}
@Override
public String getEffectiveName() {
return null;
}
@Override
public List<Role> getRoles() {
return this.user.getRoles();
}
@Override
public Color getColor() {
return null;
}
@Override
public List<Permission> getPermissions(Channel channel) {
return null;
}
@Override
public boolean canInteract(Member member) {
return false;
}
@Override
public boolean canInteract(Role role) {
return false;
}
@Override
public boolean canInteract(Emote emote) {
return false;
}
@Override
public boolean isOwner() {
return false;
}
@Override
public String getAsMention() {
return this.user.getAsMention();
}
}

View File

@ -1,140 +0,0 @@
package chikachi.discord.test.impl;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.entities.Channel;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.Role;
import net.dv8tion.jda.core.managers.RoleManager;
import net.dv8tion.jda.core.managers.RoleManagerUpdatable;
import net.dv8tion.jda.core.requests.restaction.AuditableRestAction;
import org.jetbrains.annotations.NotNull;
import java.awt.*;
import java.util.Collection;
import java.util.List;
public class FakeRole implements Role {
private final long id;
private final String name;
public FakeRole(long id, String name) {
this.id = id;
this.name = name;
}
@Override
public int getPosition() {
return 0;
}
@Override
public int getPositionRaw() {
return 0;
}
@Override
public String getName() {
return this.name;
}
@Override
public boolean isManaged() {
return false;
}
@Override
public boolean isHoisted() {
return false;
}
@Override
public boolean isMentionable() {
return false;
}
@Override
public long getPermissionsRaw() {
return 0;
}
@Override
public Color getColor() {
return null;
}
@Override
public boolean isPublicRole() {
return false;
}
@Override
public boolean canInteract(Role role) {
return false;
}
@Override
public Guild getGuild() {
return null;
}
@Override
public List<Permission> getPermissions() {
return null;
}
@Override
public boolean hasPermission(Permission... permissions) {
return false;
}
@Override
public boolean hasPermission(Collection<Permission> collection) {
return false;
}
@Override
public boolean hasPermission(Channel channel, Permission... permissions) {
return false;
}
@Override
public boolean hasPermission(Channel channel, Collection<Permission> collection) {
return false;
}
@Override
public RoleManager getManager() {
return null;
}
@Override
public RoleManagerUpdatable getManagerUpdatable() {
return null;
}
@Override
public AuditableRestAction<Void> delete() {
return null;
}
@Override
public JDA getJDA() {
return null;
}
@Override
public int compareTo(@NotNull Role o) {
return 0;
}
@Override
public String getAsMention() {
return null;
}
@Override
public long getIdLong() {
return this.id;
}
}

View File

@ -1,187 +0,0 @@
package chikachi.discord.test.impl;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.entities.*;
import net.dv8tion.jda.core.managers.ChannelManager;
import net.dv8tion.jda.core.managers.ChannelManagerUpdatable;
import net.dv8tion.jda.core.requests.RestAction;
import net.dv8tion.jda.core.requests.restaction.AuditableRestAction;
import net.dv8tion.jda.core.requests.restaction.InviteAction;
import net.dv8tion.jda.core.requests.restaction.PermissionOverrideAction;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
import java.util.List;
public class FakeTextChannel implements TextChannel {
private final Guild guild;
public FakeTextChannel(Guild guild) {
this.guild = guild;
}
@Override
public String getTopic() {
return "";
}
@Override
public boolean isNSFW() {
return false;
}
@Override
public RestAction<List<Webhook>> getWebhooks() {
return null;
}
@Override
public RestAction<Void> deleteMessages(Collection<Message> collection) {
return null;
}
@Override
public RestAction<Void> deleteMessagesByIds(Collection<String> collection) {
return null;
}
@Override
public AuditableRestAction<Void> deleteWebhookById(String s) {
return null;
}
@Override
public RestAction<Void> clearReactionsById(String s) {
return null;
}
@Override
public boolean canTalk() {
return false;
}
@Override
public boolean canTalk(Member member) {
return false;
}
@Override
public int compareTo(@NotNull TextChannel o) {
return 0;
}
@Override
public ChannelType getType() {
return null;
}
@Override
public long getLatestMessageIdLong() {
return 0;
}
@Override
public boolean hasLatestMessage() {
return false;
}
@Override
public String getName() {
return null;
}
@Override
public Guild getGuild() {
return this.guild;
}
@Override
public List<Member> getMembers() {
return null;
}
@Override
public int getPosition() {
return 0;
}
@Override
public int getPositionRaw() {
return 0;
}
@Override
public JDA getJDA() {
return null;
}
@Override
public PermissionOverride getPermissionOverride(Member member) {
return null;
}
@Override
public PermissionOverride getPermissionOverride(Role role) {
return null;
}
@Override
public List<PermissionOverride> getPermissionOverrides() {
return null;
}
@Override
public List<PermissionOverride> getMemberPermissionOverrides() {
return null;
}
@Override
public List<PermissionOverride> getRolePermissionOverrides() {
return null;
}
@Override
public ChannelManager getManager() {
return null;
}
@Override
public ChannelManagerUpdatable getManagerUpdatable() {
return null;
}
@Override
public AuditableRestAction<Void> delete() {
return null;
}
@Override
public PermissionOverrideAction createPermissionOverride(Member member) {
return null;
}
@Override
public PermissionOverrideAction createPermissionOverride(Role role) {
return null;
}
@Override
public InviteAction createInvite() {
return null;
}
@Override
public RestAction<List<Invite>> getInvites() {
return null;
}
@Override
public String getAsMention() {
return null;
}
@Override
public long getIdLong() {
return 0;
}
}

View File

@ -1,114 +0,0 @@
package chikachi.discord.test.impl;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.PrivateChannel;
import net.dv8tion.jda.core.entities.Role;
import net.dv8tion.jda.core.entities.User;
import net.dv8tion.jda.core.requests.RestAction;
import java.util.ArrayList;
import java.util.List;
public class FakeUser implements User {
private final long id;
private final String name;
private final String discriminator;
private final List<Role> roles = new ArrayList<>();
public FakeUser(long id, String nameWithDiscriminator) {
this.id = id;
String[] parts = nameWithDiscriminator.split("#");
this.name = parts[0];
this.discriminator = parts[1];
}
public FakeUser(long id, String name, String discriminator) {
this.id = id;
this.name = name;
this.discriminator = discriminator;
}
@Override
public String getName() {
return this.name;
}
@Override
public String getDiscriminator() {
return this.discriminator;
}
@Override
public String getAvatarId() {
return null;
}
@Override
public String getAvatarUrl() {
return null;
}
@Override
public String getDefaultAvatarId() {
return null;
}
@Override
public String getDefaultAvatarUrl() {
return null;
}
@Override
public String getEffectiveAvatarUrl() {
return null;
}
@Override
public boolean hasPrivateChannel() {
return false;
}
@Override
public RestAction<PrivateChannel> openPrivateChannel() {
return null;
}
@Override
public List<Guild> getMutualGuilds() {
return null;
}
@Override
public boolean isBot() {
return false;
}
@Override
public JDA getJDA() {
return null;
}
@Override
public boolean isFake() {
return true;
}
@Override
public String getAsMention() {
return "<@" + this.id + ">";
}
@Override
public long getIdLong() {
return this.id;
}
List<Role> getRoles() {
return this.roles;
}
public void addRole(Role role) {
this.roles.add(role);
}
}