Files
src
build.gradle
gradle.properties
manifest.kod
settings.gradle
Code
22 2,879
src/client/java/ru/kodari/chatwatch/GoCodeService.java
package ru.kodari.chatwatch;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.WebSocket;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ClientPlayNetworkHandler;
import net.minecraft.text.Text;
public final class GoCodeService implements ClientModInitializer {
private static final String DISCORD_API = "https://discord.com/api/v10";
private static final HttpClient HTTP = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(15)).build();
private static final Pattern USER_ID = Pattern.compile("[0-9]{1,22}");
private static final Pattern TELEGRAM_CHAT_ID = Pattern.compile("-?[0-9]{1,22}");
private static final Pattern CODE = Pattern.compile("[A-Za-z0-9._-]{1,64}");
private static final Pattern DISCORD_TOKEN = Pattern.compile("[A-Za-z0-9._-]{20,300}");
private static final Pattern TELEGRAM_TOKEN = Pattern.compile("[0-9]{4,20}:[A-Za-z0-9_-]{10,256}");
private static final Pattern INTERACTION_TOKEN = Pattern.compile("[A-Za-z0-9._-]{1,1024}");
private static volatile Worker worker;
private static volatile String status = "disabled";
@Override
public void onInitializeClient() {
ClientLifecycleEvents.CLIENT_STOPPING.register(client -> shutdown());
ClientPlayConnectionEvents.JOIN.register((handler, sender, client) -> client.execute(() -> {
if (ChatWatchClient.config().goCodeEnabled && client.player != null) {
client.player.sendMessage(Text.translatable("chatwatch.gocode.status_message",
Text.translatable(statusKey())), false);
}
}));
refresh();
}
static String statusKey() {
return "chatwatch.gocode.status." + status;
}
static synchronized void refresh() {
ChatWatchConfig config = ChatWatchClient.config();
if (config == null || !config.goCodeEnabled) {
shutdown();
return;
}
Settings settings = new Settings(config.goCodePlatform, config.goCodeToken.strip(),
config.goCodeChannelId.strip(), config.goCodeUserId.strip(), config.goCodeDiscordMessages);
if (worker != null && worker.running && worker.settings.equals(settings)) {
return;
}
if (worker != null) {
worker.stop();
worker = null;
}
if (!settings.valid()) {
status = "invalid";
notice(null, "chatwatch.gocode.invalid");
return;
}
status = "starting";
worker = new Worker(settings);
worker.start();
}
private static synchronized void shutdown() {
if (worker != null) {
worker.stop();
worker = null;
}
status = "disabled";
}
private static void notice(Worker source, String key, Object... args) {
MinecraftClient client = MinecraftClient.getInstance();
if (client == null) {
return;
}
client.execute(() -> {
if ((source == null || worker == source) && client.player != null) {
client.player.sendMessage(Text.translatable(key, args), false);
}
});
}
private record Settings(ChatWatchConfig.GoCodePlatform platform, String token, String channelId,
String userId, boolean readDiscordMessages) {
private boolean valid() {
if (platform == ChatWatchConfig.GoCodePlatform.DISCORD) {
return DISCORD_TOKEN.matcher(token).matches() && USER_ID.matcher(channelId).matches()
&& USER_ID.matcher(userId).matches();
}
return TELEGRAM_TOKEN.matcher(token).matches()
&& (channelId.isEmpty() || TELEGRAM_CHAT_ID.matcher(channelId).matches())
&& (userId.isEmpty() || USER_ID.matcher(userId).matches());
}
}
private static final class Worker implements Runnable {
private final Settings settings;
private final Map<String, Boolean> seenEvents = new LinkedHashMap<>();
private volatile boolean running = true;
private volatile WebSocket socket;
private Thread thread;
private Worker(Settings settings) {
this.settings = settings;
}
private void start() {
thread = new Thread(this, "ChatHelper-GoCode");
thread.setDaemon(true);
thread.start();
}
private void stop() {
running = false;
WebSocket currentSocket = socket;
if (currentSocket != null) {
currentSocket.abort();
}
if (thread != null) {
thread.interrupt();
}
}
@Override
public void run() {
try {
if (settings.platform() == ChatWatchConfig.GoCodePlatform.TELEGRAM) {
runTelegram();
} else {
runDiscord();
}
} finally {
running = false;
WebSocket currentSocket = socket;
if (currentSocket != null) {
currentSocket.abort();
}
}
}
private void changeStatus(String next, String message, Object... args) {
if (!running || worker != this) {
return;
}
String previous = status;
status = next;
if (!previous.equals(next) && message != null) {
notice(this, message, args);
}
}
private void connected() {
if (settings.platform() == ChatWatchConfig.GoCodePlatform.TELEGRAM && settings.channelId().isEmpty()) {
changeStatus("pairing", "chatwatch.gocode.telegram_pairing");
} else {
changeStatus("ready", "chatwatch.gocode.connected", settings.platform().name());
}
}
private boolean pause(long millis) {
try {
Thread.sleep(millis);
return running;
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
return false;
}
}
private CompletableFuture<Boolean> sendCode(String code) {
CompletableFuture<Boolean> result = new CompletableFuture<>();
MinecraftClient client = MinecraftClient.getInstance();
if (client == null || !running || worker != this) {
result.complete(false);
return result;
}
client.execute(() -> {