fabric, part 2

This commit is contained in:
Draycia authored and Josua Parks committed 2021-11-16 20:46:15 -08:00
1 parent 3559fe3423
commit cea0b49ac5
11 files changed
+682 -31

No files matched your search

@@ -68,7 +68,7 @@ public final class CarbonChatBukkit extends JavaPlugin implements CarbonChat {
CarbonChatProvider.register(this);
this.injector = Guice.createInjector(new CarbonChatBukkitModule(this, this.getDataFolder().toPath()));
this.injector = Guice.createInjector(new CarbonChatBukkitModule(this, this.dataDirectory()));
this.logger = LogManager.getLogger("CarbonChat");
this.messageService = this.injector.getInstance(CarbonMessageService.class);
this.channelRegistry = this.injector.getInstance(ChannelRegistry.class);
@@ -0,0 +1,201 @@
/*
* Copyright (C) 2018 Velocity Contributors
*
* The Velocity API is licensed under the terms of the MIT License. For more details,
* reference the LICENSE file in the api top-level directory.
*/
package net.draycia.carbon.common.util;
import java.util.Arrays;
import java.util.UUID;
/*
* The MIT License (MIT)
*
* Copyright (c) 2018 Jon Chambers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* This is a modified FastUUID implementation. The primary difference is that it does not dash its
* UUIDs. As the native Java 9+ UUID.toString() implementation dashes its UUIDs, we use the FastUUID
* methods, which ought to be faster than a String.replace().
*/
public final class FastUuidSansHyphens {
private static final int MOJANG_BROKEN_UUID_LENGTH = 32;
private static final char[] HEX_DIGITS =
new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
private static final long[] HEX_VALUES = new long[128];
static {
Arrays.fill(HEX_VALUES, -1);
HEX_VALUES['0'] = 0x0;
HEX_VALUES['1'] = 0x1;
HEX_VALUES['2'] = 0x2;
HEX_VALUES['3'] = 0x3;
HEX_VALUES['4'] = 0x4;
HEX_VALUES['5'] = 0x5;
HEX_VALUES['6'] = 0x6;
HEX_VALUES['7'] = 0x7;
HEX_VALUES['8'] = 0x8;
HEX_VALUES['9'] = 0x9;
HEX_VALUES['a'] = 0xa;
HEX_VALUES['b'] = 0xb;
HEX_VALUES['c'] = 0xc;
HEX_VALUES['d'] = 0xd;
HEX_VALUES['e'] = 0xe;
HEX_VALUES['f'] = 0xf;
HEX_VALUES['A'] = 0xa;
HEX_VALUES['B'] = 0xb;
HEX_VALUES['C'] = 0xc;
HEX_VALUES['D'] = 0xd;
HEX_VALUES['E'] = 0xe;
HEX_VALUES['F'] = 0xf;
}
private FastUuidSansHyphens() {
// A private constructor prevents callers from accidentally instantiating FastUUID instances
}
/**
* Parses a UUID from the given character sequence. The character sequence must represent a
* Mojang UUID.
*
* @param uuidSequence the character sequence from which to parse a UUID
*
* @return the UUID represented by the given character sequence
*
* @throws IllegalArgumentException if the given character sequence does not conform to the string
* representation of a Mojang UUID.
*/
public static UUID parseUuid(final CharSequence uuidSequence) {
if (uuidSequence.length() != MOJANG_BROKEN_UUID_LENGTH) {
throw new IllegalArgumentException("Illegal UUID string: " + uuidSequence);
}
long mostSignificantBits = getHexValueForChar(uuidSequence.charAt(0)) << 60;
mostSignificantBits |= getHexValueForChar(uuidSequence.charAt(1)) << 56;
mostSignificantBits |= getHexValueForChar(uuidSequence.charAt(2)) << 52;
mostSignificantBits |= getHexValueForChar(uuidSequence.charAt(3)) << 48;
mostSignificantBits |= getHexValueForChar(uuidSequence.charAt(4)) << 44;
mostSignificantBits |= getHexValueForChar(uuidSequence.charAt(5)) << 40;
mostSignificantBits |= getHexValueForChar(uuidSequence.charAt(6)) << 36;
mostSignificantBits |= getHexValueForChar(uuidSequence.charAt(7)) << 32;
mostSignificantBits |= getHexValueForChar(uuidSequence.charAt(8)) << 28;
mostSignificantBits |= getHexValueForChar(uuidSequence.charAt(9)) << 24;
mostSignificantBits |= getHexValueForChar(uuidSequence.charAt(10)) << 20;
mostSignificantBits |= getHexValueForChar(uuidSequence.charAt(11)) << 16;
mostSignificantBits |= getHexValueForChar(uuidSequence.charAt(12)) << 12;
mostSignificantBits |= getHexValueForChar(uuidSequence.charAt(13)) << 8;
mostSignificantBits |= getHexValueForChar(uuidSequence.charAt(14)) << 4;
mostSignificantBits |= getHexValueForChar(uuidSequence.charAt(15));
long leastSignificantBits = getHexValueForChar(uuidSequence.charAt(16)) << 60;
leastSignificantBits |= getHexValueForChar(uuidSequence.charAt(17)) << 56;
leastSignificantBits |= getHexValueForChar(uuidSequence.charAt(18)) << 52;
leastSignificantBits |= getHexValueForChar(uuidSequence.charAt(19)) << 48;
leastSignificantBits |= getHexValueForChar(uuidSequence.charAt(20)) << 44;
leastSignificantBits |= getHexValueForChar(uuidSequence.charAt(21)) << 40;
leastSignificantBits |= getHexValueForChar(uuidSequence.charAt(22)) << 36;
leastSignificantBits |= getHexValueForChar(uuidSequence.charAt(23)) << 32;
leastSignificantBits |= getHexValueForChar(uuidSequence.charAt(24)) << 28;
leastSignificantBits |= getHexValueForChar(uuidSequence.charAt(25)) << 24;
leastSignificantBits |= getHexValueForChar(uuidSequence.charAt(26)) << 20;
leastSignificantBits |= getHexValueForChar(uuidSequence.charAt(27)) << 16;
leastSignificantBits |= getHexValueForChar(uuidSequence.charAt(28)) << 12;
leastSignificantBits |= getHexValueForChar(uuidSequence.charAt(29)) << 8;
leastSignificantBits |= getHexValueForChar(uuidSequence.charAt(30)) << 4;
leastSignificantBits |= getHexValueForChar(uuidSequence.charAt(31));
return new UUID(mostSignificantBits, leastSignificantBits);
}
/**
* Returns a string representation of the given UUID. The returned string is formatted as a
* Mojang-style UUID.
*
* @param uuid the UUID to represent as a string
*
* @return a string representation of the given UUID
*/
public static String toString(final UUID uuid) {
final long mostSignificantBits = uuid.getMostSignificantBits();
final long leastSignificantBits = uuid.getLeastSignificantBits();
final char[] uuidChars = new char[MOJANG_BROKEN_UUID_LENGTH];
uuidChars[0] = HEX_DIGITS[(int) ((mostSignificantBits & 0xf000000000000000L) >>> 60)];
uuidChars[1] = HEX_DIGITS[(int) ((mostSignificantBits & 0x0f00000000000000L) >>> 56)];
uuidChars[2] = HEX_DIGITS[(int) ((mostSignificantBits & 0x00f0000000000000L) >>> 52)];
uuidChars[3] = HEX_DIGITS[(int) ((mostSignificantBits & 0x000f000000000000L) >>> 48)];
uuidChars[4] = HEX_DIGITS[(int) ((mostSignificantBits & 0x0000f00000000000L) >>> 44)];
uuidChars[5] = HEX_DIGITS[(int) ((mostSignificantBits & 0x00000f0000000000L) >>> 40)];
uuidChars[6] = HEX_DIGITS[(int) ((mostSignificantBits & 0x000000f000000000L) >>> 36)];
uuidChars[7] = HEX_DIGITS[(int) ((mostSignificantBits & 0x0000000f00000000L) >>> 32)];
uuidChars[8] = HEX_DIGITS[(int) ((mostSignificantBits & 0x00000000f0000000L) >>> 28)];
uuidChars[9] = HEX_DIGITS[(int) ((mostSignificantBits & 0x000000000f000000L) >>> 24)];
uuidChars[10] = HEX_DIGITS[(int) ((mostSignificantBits & 0x0000000000f00000L) >>> 20)];
uuidChars[11] = HEX_DIGITS[(int) ((mostSignificantBits & 0x00000000000f0000L) >>> 16)];
uuidChars[12] = HEX_DIGITS[(int) ((mostSignificantBits & 0x000000000000f000L) >>> 12)];
uuidChars[13] = HEX_DIGITS[(int) ((mostSignificantBits & 0x0000000000000f00L) >>> 8)];
uuidChars[14] = HEX_DIGITS[(int) ((mostSignificantBits & 0x00000000000000f0L) >>> 4)];
uuidChars[15] = HEX_DIGITS[(int) (mostSignificantBits & 0x000000000000000fL)];
uuidChars[16] = HEX_DIGITS[(int) ((leastSignificantBits & 0xf000000000000000L) >>> 60)];
uuidChars[17] = HEX_DIGITS[(int) ((leastSignificantBits & 0x0f00000000000000L) >>> 56)];
uuidChars[18] = HEX_DIGITS[(int) ((leastSignificantBits & 0x00f0000000000000L) >>> 52)];
uuidChars[19] = HEX_DIGITS[(int) ((leastSignificantBits & 0x000f000000000000L) >>> 48)];
uuidChars[20] = HEX_DIGITS[(int) ((leastSignificantBits & 0x0000f00000000000L) >>> 44)];
uuidChars[21] = HEX_DIGITS[(int) ((leastSignificantBits & 0x00000f0000000000L) >>> 40)];
uuidChars[22] = HEX_DIGITS[(int) ((leastSignificantBits & 0x000000f000000000L) >>> 36)];
uuidChars[23] = HEX_DIGITS[(int) ((leastSignificantBits & 0x0000000f00000000L) >>> 32)];
uuidChars[24] = HEX_DIGITS[(int) ((leastSignificantBits & 0x00000000f0000000L) >>> 28)];
uuidChars[25] = HEX_DIGITS[(int) ((leastSignificantBits & 0x000000000f000000L) >>> 24)];
uuidChars[26] = HEX_DIGITS[(int) ((leastSignificantBits & 0x0000000000f00000L) >>> 20)];
uuidChars[27] = HEX_DIGITS[(int) ((leastSignificantBits & 0x00000000000f0000L) >>> 16)];
uuidChars[28] = HEX_DIGITS[(int) ((leastSignificantBits & 0x000000000000f000L) >>> 12)];
uuidChars[29] = HEX_DIGITS[(int) ((leastSignificantBits & 0x0000000000000f00L) >>> 8)];
uuidChars[30] = HEX_DIGITS[(int) ((leastSignificantBits & 0x00000000000000f0L) >>> 4)];
uuidChars[31] = HEX_DIGITS[(int) (leastSignificantBits & 0x000000000000000fL)];
return new String(uuidChars);
}
private static long getHexValueForChar(final char c) {
try {
if (HEX_VALUES[c] < 0) {
throw new IllegalArgumentException("Illegal hexadecimal digit: " + c);
}
} catch (final ArrayIndexOutOfBoundsException e) {
throw new IllegalArgumentException("Illegal hexadecimal digit: " + c);
}
return HEX_VALUES[c];
}
}
@@ -0,0 +1,110 @@
package net.draycia.carbon.fabric;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.TypeLiteral;
import java.nio.file.Path;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonChatProvider;
import net.draycia.carbon.api.CarbonServer;
import net.draycia.carbon.api.channels.ChannelRegistry;
import net.draycia.carbon.api.events.CarbonEventHandler;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.api.util.RenderedMessage;
import net.draycia.carbon.api.util.SourcedAudience;
import net.draycia.carbon.common.channels.CarbonChannelRegistry;
import net.draycia.carbon.common.messages.CarbonMessageService;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.util.CloudUtils;
import net.draycia.carbon.common.util.ListenerUtils;
import net.draycia.carbon.fabric.callback.FabricChatCallback;
import net.draycia.carbon.fabric.listeners.FabricChatListener;
import net.fabricmc.api.ModInitializer;
import net.kyori.adventure.text.Component;
import net.kyori.moonshine.message.IMessageRenderer;
import net.minecraft.server.MinecraftServer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public final class CarbonChatFabric implements ModInitializer, CarbonChat {
private final CarbonEventHandler eventHandler = new CarbonEventHandler();
private @MonotonicNonNull Injector injector;
private @MonotonicNonNull UserManager<CarbonPlayerCommon> userManager;
private @MonotonicNonNull Logger logger;
private @MonotonicNonNull CarbonServerFabric carbonServerFabric;
private @MonotonicNonNull CarbonMessageService messageService;
private @MonotonicNonNull ChannelRegistry channelRegistry;
@Override
public void onInitialize() {
CarbonChatProvider.register(this);
this.injector = Guice.createInjector(new CarbonChatFabricModule(this, this.dataDirectory()));
this.logger = LogManager.getLogger("CarbonChat");
this.messageService = this.injector.getInstance(CarbonMessageService.class);
this.channelRegistry = this.injector.getInstance(ChannelRegistry.class);
this.carbonServerFabric = this.injector.getInstance(CarbonServerFabric.class);
this.userManager = this.injector.getInstance(com.google.inject.Key.get(new TypeLiteral<UserManager<CarbonPlayerCommon>>() {}));
// Platform Listeners
FabricChatCallback.setup();
FabricChatCallback.INSTANCE.registerListener(new FabricChatListener());
// Listeners
ListenerUtils.registerCommonListeners(this.injector);
// Commands
CloudUtils.registerCommands(this.injector);
// TODO: save player data, find scheduler or use java's
// Load channels
((CarbonChannelRegistry) this.channelRegistry()).loadChannels();
// TODO: save player data on shutdown
}
@Override
public Logger logger() {
return this.logger;
}
@Override
public Path dataDirectory() {
return this.dataDirectory;
}
@Override
public CarbonEventHandler eventHandler() {
return this.eventHandler;
}
@Override
public CarbonServer server() {
return this.carbonServerFabric;
}
@Override
public ChannelRegistry channelRegistry() {
return this.channelRegistry;
}
@Override
public IMessageRenderer<SourcedAudience, String, RenderedMessage, Component> messageRenderer() {
return this.injector.getInstance(FabricMessageRenderer.class);
}
public MinecraftServer minecraftServer() {
}
public CarbonMessageService messageService() {
return this.messageService;
}
}
@@ -0,0 +1,84 @@
package net.draycia.carbon.fabric;
import cloud.commandframework.CommandManager;
import cloud.commandframework.brigadier.CloudBrigadierManager;
import cloud.commandframework.execution.AsynchronousCommandExecutionCoordinator;
import cloud.commandframework.fabric.FabricServerCommandManager;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import java.nio.file.Path;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.CarbonServer;
import net.draycia.carbon.common.CarbonCommonModule;
import net.draycia.carbon.common.ForCarbon;
import net.draycia.carbon.common.command.Commander;
import net.draycia.carbon.common.util.CloudUtils;
import net.draycia.carbon.fabric.command.FabricCommander;
import net.draycia.carbon.fabric.command.FabricPlayerCommander;
import net.minecraft.world.entity.player.Player;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public final class CarbonChatFabricModule extends AbstractModule {
private final Logger logger = LogManager.getLogger("CarbonChat");
private final CarbonChatFabric carbonChat;
private final Path dataDirectory;
CarbonChatFabricModule(
final CarbonChatFabric carbonChat,
final Path dataDirectory
) {
this.carbonChat = carbonChat;
this.dataDirectory = dataDirectory;
}
@Provides
@Singleton
public CommandManager<Commander> commandManager() {
final FabricServerCommandManager<Commander> commandManager;
try {
commandManager = new FabricServerCommandManager<>(
AsynchronousCommandExecutionCoordinator.<Commander>newBuilder().build(),
commandSource -> {
if (commandSource.getEntity() instanceof Player player) {
return new FabricPlayerCommander(this.carbonChat.minecraftServer(), this.carbonChat, player);
}
return FabricCommander.from(this.carbonChat.minecraftServer(), commandSource);
},
commander -> ((FabricCommander) commander).commandSourceStack()
);
} catch (final Exception ex) {
throw new RuntimeException("Failed to initialize command manager.", ex);
}
CloudUtils.decorateCommandManager(commandManager, this.carbonChat.messageService());
final @Nullable CloudBrigadierManager<Commander, ?> brigadierManager =
commandManager.brigadierManager();
if (brigadierManager != null) {
brigadierManager.setNativeNumberSuggestions(false);
}
return commandManager;
}
@Override
public void configure() {
this.install(new CarbonCommonModule());
this.bind(CarbonChat.class).toInstance(this.carbonChat);
this.bind(CarbonChatFabric.class).toInstance(this.carbonChat);
this.bind(Logger.class).toInstance(this.logger);
this.bind(Path.class).annotatedWith(ForCarbon.class).toInstance(this.dataDirectory);
this.bind(CarbonServer.class).to(CarbonServerFabric.class);
}
}
@@ -1,28 +0,0 @@
package net.draycia.carbon.fabric;
import net.draycia.carbon.fabric.callback.FabricChatCallback;
import net.fabricmc.api.ModInitializer;
import net.kyori.adventure.platform.fabric.FabricServerAudiences;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
import static net.kyori.adventure.text.Component.translatable;
@DefaultQualifier(NonNull.class)
public final class CarbonFabricEntry implements ModInitializer {
@Override
public void onInitialize() {
FabricChatCallback.setup();
final FabricChatCallback.Chat.MessageFormatter formatter = (sender, message, viewer) -> translatable(
"chat.type.text",
FabricServerAudiences.of(sender.server).toAdventure(sender.getDisplayName()),
MiniMessage.miniMessage().deserialize(message)
);
FabricChatCallback.INSTANCE.registerListener(chat -> chat.formatter(formatter));
}
}
@@ -0,0 +1,196 @@
package net.draycia.carbon.fabric;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import net.draycia.carbon.api.CarbonServer;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.users.ComponentPlayerResult;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.util.FastUuidSansHyphens;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience;
import net.kyori.adventure.platform.fabric.FabricServerAudiences;
import net.kyori.adventure.text.Component;
import net.minecraft.world.entity.player.Player;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.framework.qual.DefaultQualifier;
import org.jetbrains.annotations.NotNull;
import static net.kyori.adventure.text.Component.text;
@Singleton
@DefaultQualifier(NonNull.class)
public final class CarbonServerFabric implements CarbonServer, ForwardingAudience.Single {
private final CarbonChatFabric carbonChatFabric;
private final UserManager<CarbonPlayerCommon> userManager;
private final Map<UUID, CarbonPlayerFabric> userCache = new ConcurrentHashMap<>();
private final HttpClient client = HttpClient.newHttpClient();
private final Gson gson = new Gson();
@Inject
private CarbonServerFabric(final CarbonChatFabric carbonChatFabric, final UserManager<CarbonPlayerCommon> userManager) {
this.carbonChatFabric = carbonChatFabric;
this.userManager = userManager;
}
@Override
public @NotNull Audience audience() {
return FabricServerAudiences.of(this.carbonChatFabric.minecraftServer()).all();
}
@Override
public Audience console() {
return FabricServerAudiences.of(this.carbonChatFabric.minecraftServer()).console();
}
@Override
public List<? extends CarbonPlayer> players() {
final var players = new ArrayList<CarbonPlayer>();
for (final var player : this.carbonChatFabric.minecraftServer().getPlayerList().getPlayers()) {
final @Nullable ComponentPlayerResult<CarbonPlayer> result = this.player(player).join();
if (result.player() != null) {
players.add(result.player());
}
}
return players;
}
private CompletableFuture<ComponentPlayerResult<CarbonPlayer>> wrapPlayer(final UUID uuid) {
return CompletableFuture.supplyAsync(() -> {
final @Nullable CarbonPlayerFabric cachedPlayer = this.userCache.get(uuid);
if (cachedPlayer != null) {
return new ComponentPlayerResult<>(cachedPlayer, Component.empty());
}
final ComponentPlayerResult<CarbonPlayerCommon> result = this.userManager.carbonPlayer(uuid).join();
if (result.player() != null) {
final CarbonPlayerFabric carbonPlayerFabric = new CarbonPlayerFabric(result.player());
this.userCache.put(uuid, carbonPlayerFabric);
return new ComponentPlayerResult<>(carbonPlayerFabric, Component.empty());
}
final @Nullable String name = this.resolveName(uuid).join();
if (name != null) {
final CarbonPlayerCommon player = new CarbonPlayerCommon(name, uuid);
final CarbonPlayerFabric carbonPlayerFabric = new CarbonPlayerFabric(player);
this.userCache.put(uuid, carbonPlayerFabric);
return new ComponentPlayerResult<>(carbonPlayerFabric, Component.empty());
}
return new ComponentPlayerResult<>(null, text("Name not found for uuid!"));
});
}
@Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayer>> player(final UUID uuid) {
return this.wrapPlayer(uuid);
}
@Override
public CompletableFuture<ComponentPlayerResult<CarbonPlayer>> player(final String username) {
return CompletableFuture.supplyAsync(() -> {
final @Nullable UUID uuid = this.resolveUUID(username).join();
if (uuid != null) {
return this.player(uuid).join();
}
return new ComponentPlayerResult<>(null, text("No UUID found for name."));
});
}
public CompletableFuture<ComponentPlayerResult<CarbonPlayer>> player(final Player player) {
return this.player(player.getUUID());
}
@Override
public CompletableFuture<@Nullable UUID> resolveUUID(final String username) {
return CompletableFuture.supplyAsync(() -> {
final var serverPlayer = this.server.getPlayer(username);
if (serverPlayer.isPresent()) {
return serverPlayer.get().getUniqueId();
}
try {
final @Nullable JsonObject json = this.queryMojang(new URI("https://api.mojang.com/users/profiles/minecraft/" + username));
return FastUuidSansHyphens.parseUuid(json.get("uuid").getAsString());
} catch (final URISyntaxException exception) {
exception.printStackTrace();
}
return null;
});
}
@Override
public CompletableFuture<@Nullable String> resolveName(final UUID uuid) {
return CompletableFuture.supplyAsync(() -> {
final var serverPlayer = this.server.getPlayer(uuid);
if (serverPlayer.isPresent()) {
return serverPlayer.get().getUsername();
}
try {
final @Nullable JsonObject json = this.queryMojang(new URI("https://sessionserver.mojang.com/session/minecraft/profile/" + UuidUtils.toUndashed(uuid)));
return json.get("name").getAsString();
} catch (final URISyntaxException exception) {
exception.printStackTrace();
}
return null;
});
}
private @Nullable JsonObject queryMojang(final URI uri) {
final HttpRequest request = HttpRequest
.newBuilder(uri)
.GET()
.build();
try {
final HttpResponse<String> response =
this.client.send(request, HttpResponse.BodyHandlers.ofString());
final String mojangResponse = response.body();
final JsonArray jsonArray = this.gson.fromJson(mojangResponse, JsonObject.class).getAsJsonArray();
return (JsonObject) jsonArray.get(1);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
return null;
}
}
}
@@ -0,0 +1,32 @@
package net.draycia.carbon.fabric.command;
import net.draycia.carbon.common.command.Commander;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience;
import net.kyori.adventure.platform.fabric.FabricServerAudiences;
import net.minecraft.commands.CommandSource;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.server.MinecraftServer;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.framework.qual.DefaultQualifier;
@DefaultQualifier(NonNull.class)
public interface FabricCommander extends Commander, ForwardingAudience.Single {
static FabricCommander from(final MinecraftServer server, final CommandSourceStack commandSourceStack) {
return new FabricCommanderImpl(server, commandSourceStack);
}
CommandSourceStack commandSourceStack();
record FabricCommanderImpl(MinecraftServer server, CommandSourceStack commandSourceStack) implements FabricCommander {
// TODO: Client support, middleman the FabricServerAudiences and return client or server depending on env?
@Override
public Audience audience() {
return FabricServerAudiences.of(this.server).audience(this.commandSourceStack);
}
}
}
@@ -0,0 +1,35 @@
package net.draycia.carbon.fabric.command;
import net.draycia.carbon.api.CarbonChat;
import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.common.command.PlayerCommander;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.platform.fabric.FabricServerAudiences;
import net.minecraft.commands.CommandSource;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.entity.player.Player;
import org.checkerframework.checker.nullness.qual.NonNull;
import static java.util.Objects.requireNonNull;
public record FabricPlayerCommander(
@NonNull MinecraftServer server,
@NonNull CarbonChat carbon,
@NonNull CommandSource commandSource
) implements PlayerCommander, FabricCommander {
@Override
public @NonNull CommandSource commandSource() {
return this.commandSource;
}
@Override
public @NonNull Audience audience() {
return FabricServerAudiences.of(this.server).audience(this.commandSource);
}
@Override
public @NonNull CarbonPlayer carbonPlayer() {
return requireNonNull(this.carbon.server().player(((Player) this.commandSource).getUUID()).join().player(), "No CarbonPlayer for logged in Player!");
}
}
@@ -0,0 +1,20 @@
package net.draycia.carbon.fabric.listeners;
import java.util.function.Consumer;
import net.draycia.carbon.fabric.callback.FabricChatCallback;
import net.kyori.adventure.platform.fabric.FabricServerAudiences;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
public class FabricChatListener implements Consumer<FabricChatCallback.Chat> {
@Override
public void accept(FabricChatCallback.Chat chat) {
final FabricChatCallback.Chat.MessageFormatter formatter = (sender, message, viewer) -> Component.translatable(
"chat.type.text",
FabricServerAudiences.of(sender.server).toAdventure(sender.getDisplayName()),
MiniMessage.miniMessage().deserialize(message)
);
}
}
+1 -1
View File
@@ -16,7 +16,7 @@
"environment": "server",
"entrypoints": {
"main": [
"net.draycia.carbon.fabric.CarbonFabricEntry"
"net.draycia.carbon.fabric.CarbonChatFabric"
]
},
"mixins": [
@@ -22,6 +22,7 @@ import net.draycia.carbon.api.users.CarbonPlayer;
import net.draycia.carbon.api.users.ComponentPlayerResult;
import net.draycia.carbon.api.users.UserManager;
import net.draycia.carbon.common.users.CarbonPlayerCommon;
import net.draycia.carbon.common.util.FastUuidSansHyphens;
import net.draycia.carbon.velocity.users.CarbonPlayerVelocity;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.audience.ForwardingAudience;
@@ -127,7 +128,7 @@ public final class CarbonServerVelocity implements CarbonServer, ForwardingAudie
try {
final @Nullable JsonObject json = this.queryMojang(new URI("https://api.mojang.com/users/profiles/minecraft/" + username));
return UuidUtils.fromUndashed(json.get("uuid").getAsString());
return FastUuidSansHyphens.parseUuid(json.get("uuid").getAsString());
} catch (final URISyntaxException exception) {
exception.printStackTrace();
}