Skip to content

Commit

Permalink
Add option to use mojang api in player name lookup
Browse files Browse the repository at this point in the history
  • Loading branch information
andantet committed Feb 23, 2024
1 parent 19efe94 commit 77e9bb8
Show file tree
Hide file tree
Showing 3 changed files with 105 additions and 42 deletions.
2 changes: 1 addition & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@ fabric_kotlin_version=1.10.17+kotlin.1.9.22
kache_version=1.0.5

# Mod Properties
mod_version=2.4.0
mod_version=2.5.0
maven_group=dev.andante
85 changes: 71 additions & 14 deletions src/main/java/dev/andante/audience/player/PlayerReference.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package dev.andante.audience.player;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.mojang.authlib.GameProfile;
import dev.andante.audience.Audience;
import dev.andante.audience.AudienceInitializer;
Expand All @@ -10,6 +14,10 @@
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Collections;
import java.util.Optional;
import java.util.UUID;
Expand Down Expand Up @@ -55,31 +63,80 @@ default ServerPlayerEntity getPlayer() {
}

/**
* The name of this player. If they are not online, 'Unknown'.
* The name of this player. If they are not online and the username cannot be found, "Unknown".
*/
default String getPlayerName() {
default String getPlayerName(boolean useApi) {
ServerPlayerEntity player = this.getPlayer();
if (player == null) {
// attempt to retrieve username from user cache
MinecraftServer server = AudienceInitializer.INSTANCE.getServer();
UserCache userCache = server.getUserCache();
if (userCache != null) {
UUID uuid = this.getReferenceUuid();
Optional<GameProfile> maybeProfile = userCache.getByUuid(uuid);
if (maybeProfile.isPresent()) {
GameProfile profile = maybeProfile.get();
return profile.getName();
// check user cache
String userCacheName = getUserCachePlayerName();
if (userCacheName != null) {
return userCacheName;
} else {
if (useApi) {
// check mojang api
String apiName = getMojangApiPlayerName();
if (apiName != null) {
return apiName;
}
}
}

// concede and return unknown
return "Unknown";
// concede and return unknown
return "Unknown";
}
} else {
// return online name
return player.getGameProfile().getName();
}
}

/**
* The name of this player. If they are not online and the username cannot be found, "Unknown".
*/
default String getPlayerName() {
return this.getPlayerName(false);
}

/**
* The name of this player as stored in the server's user cache.
*/
@Nullable
default String getUserCachePlayerName() {
MinecraftServer server = AudienceInitializer.INSTANCE.getServer();
UserCache userCache = server.getUserCache();
if (userCache != null) {
UUID uuid = this.getReferenceUuid();
Optional<GameProfile> maybeProfile = userCache.getByUuid(uuid);
if (maybeProfile.isPresent()) {
GameProfile profile = maybeProfile.get();
return profile.getName();
}
}

return null;
}

@Nullable
default String getMojangApiPlayerName() {
UUID uuid = this.getReferenceUuid();
String urlString = "https://sessionserver.mojang.com/session/minecraft/profile/" + uuid;
try {
URL url = new URL(urlString);
try (InputStream stream = url.openStream()) {
InputStreamReader reader = new InputStreamReader(stream);
JsonElement jsonElement = JsonParser.parseReader(reader);
if (jsonElement instanceof JsonObject json) {
if (json.has("name")) {
return json.get("name").getAsString();
}
}
}
} catch (IOException | UnsupportedOperationException | IllegalStateException | JsonParseException ignored) {
}

return null;
}

/**
* @return whether the player referenced is online
*/
Expand Down
60 changes: 33 additions & 27 deletions src/test/kotlin/dev/andante/audience/test/AudienceTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,46 +8,49 @@ import dev.andante.audience.resource.ResourcePack
import dev.andante.audience.resource.ResourcePackServer
import net.fabricmc.api.ModInitializer
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents
import net.minecraft.server.MinecraftServer.ServerResourcePackProperties
import org.slf4j.LoggerFactory
import java.nio.file.Path
import kotlin.io.path.readBytes
import kotlin.time.measureTimedValue

object AudienceTest : ModInitializer {
private const val TEST_RESOURCE_PACK: Boolean = false

private val logger = LoggerFactory.getLogger("Audience Test")

private val byteArray = try {
Path.of("resources.zip").readBytes()
} catch (exception: Exception) {
logger.error("No resources.zip", exception)
throw exception
}
override fun onInitialize() {
LoggerFactory.getLogger("Audience Test").info("Initializing")

private val resourcePack = ResourcePack(byteArray)
private val properties: ServerResourcePackProperties
if (TEST_RESOURCE_PACK) {
val byteArray = try {
Path.of("resources.zip").readBytes()
} catch (exception: Exception) {
logger.error("No resources.zip", exception)
throw exception
}

private val otherByteArray = try {
Path.of("resources2.zip").readBytes()
} catch (exception: Exception) {
logger.error("No resources2.zip", exception)
throw exception
}
val resourcePack = ResourcePack(byteArray)

private val otherResourcePack = ResourcePack(otherByteArray)
private val otherProperties: ServerResourcePackProperties
val otherByteArray = try {
Path.of("resources2.zip").readBytes()
} catch (exception: Exception) {
logger.error("No resources2.zip", exception)
throw exception
}

private val resourcePackServer = ResourcePackServer("localhost", 25566).apply {
properties = registerResourcePack(resourcePack)
otherProperties = registerResourcePack(otherResourcePack)
}
val otherResourcePack = ResourcePack(otherByteArray)

override fun onInitialize() {
LoggerFactory.getLogger("Audience Test").info("Initializing")
resourcePackServer.startServer()
println("Started server on port ${resourcePackServer.port}")
val resourcePackServer = ResourcePackServer("localhost", 25566).apply {
registerResourcePack(resourcePack)
registerResourcePack(otherResourcePack)
}

ServerLifecycleEvents.SERVER_STOPPING.register {
resourcePackServer.stopServer()
resourcePackServer.startServer()
println("Started server on port ${resourcePackServer.port}")

ServerLifecycleEvents.SERVER_STOPPING.register {
resourcePackServer.stopServer()
}
}

// test player reference codec IO (ensure possible migration of old uuids)
Expand All @@ -67,5 +70,8 @@ object AudienceTest : ModInitializer {
val list = PlayerList(listOf(inputReference))
val listJson = PlayerList.CODEC.encodeStart(JsonOps.INSTANCE, list).resultOrPartial(logger::error).orElseThrow()
println(listJson)

val measuredApi = measureTimedValue(inputReference::getMojangApiPlayerName)
println("Took ${measuredApi.duration.inWholeMilliseconds} ms to fetch \"${measuredApi.value}\"")
}
}

0 comments on commit 77e9bb8

Please sign in to comment.