Skip to content

Commit

Permalink
Merge branch 'main' into forkmain
Browse files Browse the repository at this point in the history
# Conflicts:
#	src/main/java/one/devos/nautical/teabridge/mixin/ServerPlayerMixin.java
  • Loading branch information
sisby-folk committed Jul 28, 2023
2 parents dd7031f + 6bf3a80 commit 19f3790
Show file tree
Hide file tree
Showing 18 changed files with 210 additions and 101 deletions.
11 changes: 8 additions & 3 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ repositories {
url = "https://maven.nucleoid.xyz/"
content { includeGroup "eu.pb4" }
}
maven {
url = "https://maven.proxyfox.dev/"
content { includeGroup "dev.proxyfox" }
}
}

dependencies {
Expand All @@ -31,10 +35,11 @@ dependencies {
modImplementation(fabricApi.module("fabric-api-base", project.fabric_version))
modImplementation(fabricApi.module("fabric-command-api-v2", project.fabric_version))
modImplementation(fabricApi.module("fabric-lifecycle-events-v1", project.fabric_version))
modImplementation(fabricApi.module("fabric-message-api-v1", project.fabric_version))

modImplementation(include("eu.pb4:placeholder-api:2.0.0-pre.1+1.19.2"))
include(implementation("dev.proxyfox:MarKt:1.4"))

include(implementation("net.dv8tion:JDA:5.0.0-beta.2"){
include(implementation("net.dv8tion:JDA:5.0.0-beta.12"){
exclude module: "opus-java"
})
include("net.sf.trove4j:trove4j:3.0.3")
Expand All @@ -45,7 +50,7 @@ dependencies {
include("com.squareup.okhttp3:okhttp:4.9.3")
include("com.squareup.okio:okio-jvm:3.2.0")
include("com.neovisionaries:nv-websocket-client:2.14")
// for "squareup.x" libs (they all use kotlin)
// for "squareup.x" libs (they all use kotlin) and MarKt
modLocalRuntime("net.fabricmc:fabric-language-kotlin:1.9.1+kotlin.1.8.10")
}

Expand Down
2 changes: 1 addition & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ org.gradle.jvmargs=-Xmx4G
fabric_version=0.86.0+1.20.1

# Mod Properties
mod_version = 1.1.0
mod_version = 1.2.0
maven_group = one.devos.nautical
archives_base_name = teabridge
3 changes: 3 additions & 0 deletions src/main/java/one/devos/nautical/teabridge/Config.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,14 @@ public static void load() throws Exception {
@Expose public Game game = new Game();
@Expose public Crashes crashes = new Crashes();

@Expose public boolean debug = false;

public static class Discord {
@Expose public String token = "";
@Expose public String webhook = "";

@Expose public int pkMessageDelay = 0;
@Expose public boolean pkMessageDelayMilliseconds = true;
}

public static class Avatars {
Expand Down
72 changes: 68 additions & 4 deletions src/main/java/one/devos/nautical/teabridge/PlatformUtil.java
Original file line number Diff line number Diff line change
@@ -1,20 +1,27 @@
package one.devos.nautical.teabridge;

import java.nio.file.Path;
import java.util.List;
import java.util.function.Consumer;

import com.mojang.brigadier.CommandDispatcher;

import eu.pb4.placeholders.api.node.LiteralNode;
import eu.pb4.placeholders.api.node.parent.ParentNode;
import eu.pb4.placeholders.api.parsers.MarkdownLiteParserV1;
import dev.proxyfox.markt.MarkdownNode;
import dev.proxyfox.markt.MarkdownParser;
import dev.proxyfox.markt.MentionNode;
import dev.proxyfox.markt.SymbolNode;
import net.fabricmc.api.DedicatedServerModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.fabric.api.message.v1.ServerMessageEvents;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.ChatFormatting;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.HoverEvent;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.Style;
import net.minecraft.resources.ResourceLocation;

public class PlatformUtil implements DedicatedServerModInitializer {
public static Path getConfigDir() {
Expand All @@ -29,8 +36,60 @@ public static MutableComponent literal(String text) {
return Component.literal(text);
}

public static MutableComponent translatable(String key) {
return Component.translatable(key);
}

// private static MutableComponent formatMarkdownNodes(List<MarkdownNode> nodes) {
// var formatted = empty();
// for (MarkdownNode node : nodes) {
// System.out.println(node);
// if (node instanceof SymbolNode symbolNode) {
// var formattedChildren = formatMarkdownNodes(symbolNode.getNodes()); // this variable name is cursed
// System.out.println(symbolNode.getLeft());
// System.out.println(symbolNode.getRight());
// switch (symbolNode.getLeft()) {
// case "**":
// formattedChildren = formattedChildren.withStyle(ChatFormatting.BOLD);
// break;
// case "`":
// case "``":
// case "```":
// formattedChildren = formattedChildren.withStyle(ChatFormatting.GRAY, ChatFormatting.ITALIC);
// break;
// case "||":
// formattedChildren = (literal("[").append(translatable("options.hidden")).append("]"))
// .withStyle(Style.EMPTY.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, formattedChildren)))
// .withStyle(ChatFormatting.GRAY, ChatFormatting.ITALIC);
// break;
// case "*":
// case "_":
// formattedChildren = formattedChildren.withStyle(ChatFormatting.ITALIC);
// break;
// case "__":
// formattedChildren = formattedChildren.withStyle(ChatFormatting.UNDERLINE);
// break;
// case "~~":
// formattedChildren = formattedChildren.withStyle(ChatFormatting.STRIKETHROUGH);
// break;
// default:
// break;
// }
// formatted = formatted.append(formattedChildren);
// } else if (node instanceof MentionNode mentionNode) {
// formatted = formatted.append(node.toString());
// } else {
// formatted = formatted.append(node.toString());
// }
// }
// return formatted;
// }

public static MutableComponent formatText(String text) {
return new ParentNode(MarkdownLiteParserV1.ALL.parseNodes(new LiteralNode(text))).toText(null, true).copy();
// var parser = MarkdownParser.Companion.getGlobalInstance();
// var root = parser.parse(text);
// return formatMarkdownNodes(root.getNodes());
return literal(text);
}

public static void registerCommand(Consumer<CommandDispatcher<CommandSourceStack>> consumer) {
Expand All @@ -44,5 +103,10 @@ public void onInitializeServer() {
ServerLifecycleEvents.SERVER_STARTING.register(TeaBridge::onServerStarting);
ServerLifecycleEvents.SERVER_STARTED.register(TeaBridge::onServerStart);
ServerLifecycleEvents.SERVER_STOPPED.register(TeaBridge::onServerStop);

var phaseId = new ResourceLocation("teabridge", "mirror");
ServerMessageEvents.CHAT_MESSAGE.addPhaseOrdering(new ResourceLocation("switchy_proxy", "set_args"), phaseId);
ServerMessageEvents.CHAT_MESSAGE.addPhaseOrdering(phaseId, new ResourceLocation("switchy_proxy", "clear"));
ServerMessageEvents.CHAT_MESSAGE.register(phaseId, TeaBridge::onChatMessage);
}
}
16 changes: 15 additions & 1 deletion src/main/java/one/devos/nautical/teabridge/TeaBridge.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,16 @@
import net.minecraft.ChatFormatting;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.ChatType;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.PlayerChatMessage;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import one.devos.nautical.teabridge.discord.ChannelListener;
import one.devos.nautical.teabridge.discord.Discord;
import one.devos.nautical.teabridge.duck.PlayerWebHook;
import one.devos.nautical.teabridge.util.CrashHandler;
import one.devos.nautical.teabridge.util.StyledChatCompat;

public class TeaBridge {
public static final Logger LOGGER = LoggerFactory.getLogger("TeaBridge");
Expand All @@ -38,6 +43,7 @@ public static void initialize() {
}

public static void onServerStarting(MinecraftServer server) {
if (Config.INSTANCE.debug) TeaBridge.LOGGER.warn("DEBUG MODE IS ENABLED, THIS WILL LOG EVERYTHING WILL CAUSE LAG SPIKES!!!!!!");
Discord.send(Config.INSTANCE.game.serverStartingMessage);
}

Expand All @@ -51,13 +57,21 @@ public static void onServerStop(MinecraftServer server) {
Discord.stop();
}

public static void onChatMessage(PlayerChatMessage message, ServerPlayer sender, ChatType.Bound params) {
if (sender != null) {
((PlayerWebHook) sender).send(message);
} else {
Discord.send(StyledChatCompat.modify(message).getLeft());
}
}

private static void registerCommands(CommandDispatcher<CommandSourceStack> dispatcher) {
dispatcher.register(Commands.literal("teabridge").then(
Commands.literal("reloadConfig").executes(command -> {
try {
Config.load();
command.getSource().sendSuccess(() -> Component.literal("Config reloaded!").withStyle(ChatFormatting.GREEN), false);
command.getSource().sendSystemMessage(Component.literal("Warning: options in the discord category will not be reloaded!").withStyle(ChatFormatting.YELLOW));
command.getSource().sendSystemMessage(Component.literal("Warning: options in the discord category except pk message delay will not be reloaded!").withStyle(ChatFormatting.YELLOW));
} catch (Exception e) {
command.getSource().sendFailure(Component.literal("Failed to reload config!").withStyle(ChatFormatting.RED));
LOGGER.warn("Failed to reload config : ", e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.server.MinecraftServer;
import one.devos.nautical.teabridge.PlatformUtil;
import one.devos.nautical.teabridge.duck.MessageEventProxyTag;
import one.devos.nautical.teabridge.util.FormattingUtils;

public class ChannelListener extends ListenerAdapter {
Expand All @@ -26,16 +25,16 @@ void setChannel(long channel) {
}

@Override
public void onMessageReceived(MessageReceivedEvent event) {
PKCompat.await(event, proxiedEvent -> {
public void onMessageReceived(MessageReceivedEvent receivedEvent) {
PKCompat.await(receivedEvent, (event, proxied) -> {
if (server == null) return;

if (
!event.isFromGuild() ||
event.getChannel().getIdLong() != channel ||
(event.isWebhookMessage() && !((MessageEventProxyTag) (Object) event).teabridge$isProxied()) ||
(!event.isWebhookMessage() && ((MessageEventProxyTag) (Object) event).teabridge$isProxied())
) return;
(event.isWebhookMessage() && !proxied) ||
(!event.isWebhookMessage() && proxied)
) return;

final var playerList = server.getPlayerList();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public static void start() {
.build(), HttpResponse.BodyHandlers.ofString());
if (response.statusCode() / 100 != 2) throw new Exception("Non-success status code from request " + response);
var webHookDataResponse = JsonUtils.GSON.fromJson(response.body(), WebHookDataResponse.class);
if (Config.INSTANCE.debug) TeaBridge.LOGGER.warn("Webhook response : " + response.body());
guild = Long.parseLong(webHookDataResponse.guildId);
ChannelListener.INSTANCE.setChannel(Long.parseLong(webHookDataResponse.channelId));

Expand All @@ -60,6 +61,8 @@ public static void start() {
} catch (Exception e) {
TeaBridge.LOGGER.error("Exception initializing JDA", e);
}

PKCompat.initIfEnabled(() -> jda != null);
}

public static void send(String message) {
Expand All @@ -69,11 +72,13 @@ public static void send(String message) {
public static void send(WebHook webHook, String message) {
if (jda != null) {
try {
if (Config.INSTANCE.debug) TeaBridge.LOGGER.warn("Sent webhook message json : " + webHook.jsonWithContent(message));
var response = TeaBridge.CLIENT.send(HttpRequest.newBuilder()
.uri(URI.create(Config.INSTANCE.discord.webhook))
.POST(HttpRequest.BodyPublishers.ofString(webHook.jsonWithContent(message)))
.header("Content-Type", "application/json; charset=utf-8")
.build(), HttpResponse.BodyHandlers.ofString());
if (Config.INSTANCE.debug) TeaBridge.LOGGER.warn("Webhook message response : " + response.body());
if (response.statusCode() / 100 != 2) throw new Exception("Non-success status code from request " + response);
} catch (Exception e) {
TeaBridge.LOGGER.warn("Failed to send webhook message to discord : ", e);
Expand Down
53 changes: 31 additions & 22 deletions src/main/java/one/devos/nautical/teabridge/discord/PKCompat.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,41 +3,53 @@
import java.net.URI;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.time.Instant;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.function.BiConsumer;
import java.util.function.BooleanSupplier;

import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import one.devos.nautical.teabridge.Config;
import one.devos.nautical.teabridge.TeaBridge;
import one.devos.nautical.teabridge.duck.MessageEventProxyTag;


class PKCompat {
private static final String MESSAGE_ENDPOINT = "https://api.pluralkit.me/v2/messages/{id}";

private static final Object2ObjectOpenHashMap<MessageReceivedEvent, Consumer<MessageReceivedEvent>> AWAITING = new Object2ObjectOpenHashMap<>();
private static final ConcurrentLinkedQueue<ScheduledEvent> scheduled = new ConcurrentLinkedQueue<>();

static void await(MessageReceivedEvent event, Consumer<MessageReceivedEvent> handler) {
if (Config.INSTANCE.discord.pkMessageDelay > 0) {
AWAITING.put(event, handler);
} else {
handler.accept(event);
}
static void initIfEnabled(BooleanSupplier running) {
if (Config.INSTANCE.discord.pkMessageDelay > 0)
new Thread(() -> {
while (running.getAsBoolean()) {
scheduled.removeIf(scheduledEvent -> {
if (Instant.now().compareTo(scheduledEvent.instant) >= 0) {
scheduledEvent.handler.accept(scheduledEvent.event, isProxied(scheduledEvent.event.getMessageId()));
return true;
}
return false;
});
}
}).start();
}

private static void check() {
for (MessageReceivedEvent event : AWAITING.keySet()) {
if (proxied(event.getMessageIdLong())) ((MessageEventProxyTag) event).teabridge$setProxied();
AWAITING.remove(event).accept(event);
static void await(MessageReceivedEvent event, BiConsumer<MessageReceivedEvent, Boolean> handler) {
if (Config.INSTANCE.discord.pkMessageDelay > 0) {
scheduled.add(new ScheduledEvent(
event,
handler,
Config.INSTANCE.discord.pkMessageDelayMilliseconds ?
Instant.now().plusMillis(Config.INSTANCE.discord.pkMessageDelay) : Instant.now().plusSeconds(Config.INSTANCE.discord.pkMessageDelay)
));
return;
}
handler.accept(event, isProxied(event.getMessageId()));
}

private static boolean proxied(long messageId) {
private static boolean isProxied(String messageId) {
try {
var response = TeaBridge.CLIENT.send(HttpRequest.newBuilder()
.uri(URI.create(MESSAGE_ENDPOINT.replace("{id}", Long.toString(messageId))))
.uri(URI.create(MESSAGE_ENDPOINT.replace("{id}", messageId)))
.GET()
.build(), HttpResponse.BodyHandlers.ofString());
return response.statusCode() != 404;
Expand All @@ -46,8 +58,5 @@ private static boolean proxied(long messageId) {
}
}

static {
if (Config.INSTANCE.discord.pkMessageDelay > 0)
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(PKCompat::check, 0, Config.INSTANCE.discord.pkMessageDelay, TimeUnit.SECONDS);
}
private record ScheduledEvent(MessageReceivedEvent event, BiConsumer<MessageReceivedEvent, Boolean> handler, Instant instant) { }
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package one.devos.nautical.teabridge.duck;

import java.util.List;
import java.util.Optional;

import com.google.common.collect.Lists;

import net.minecraft.network.chat.PlayerChatMessage;
import one.devos.nautical.teabridge.discord.Discord;
import one.devos.nautical.teabridge.discord.WebHook;
import one.devos.nautical.teabridge.util.StyledChatCompat;

public interface PlayerWebHook {
final List<PlayerWebHook> ONLINE = Lists.newArrayList();
Expand All @@ -18,6 +20,10 @@ default void send(String message) {
}

default void send(PlayerChatMessage message) {
send(message.signedContent());
var modified = StyledChatCompat.modify(message);

StyledChatCompat.TEMP_USERNAME = modified.getRight();
send(modified.getLeft());
StyledChatCompat.TEMP_USERNAME = Optional.empty();
}
}
Loading

0 comments on commit 19f3790

Please sign in to comment.