Skip to content

Instantly share code, notes, and snippets.

@Densamisten
Created September 26, 2024 00:46
Show Gist options
  • Save Densamisten/9dfb3a3cfeba7affa9b9b49e44a6b8aa to your computer and use it in GitHub Desktop.
Save Densamisten/9dfb3a3cfeba7affa9b9b49e44a6b8aa to your computer and use it in GitHub Desktop.
package exonihility.client.event;
import net.minecraft.network.packet.Packet;
import net.minecraft.network.packet.c2s.common.CustomPayloadC2SPacket;
import net.minecraft.network.packet.CustomPayload;
import net.minecraft.network.packet.BrandCustomPayload;
import net.minecraft.network.packet.UnknownCustomPayload;
import net.minecraft.network.packet.s2c.common.CustomPayloadS2CPacket;
import net.minecraft.util.Identifier;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class PacketUtils {
private static final Logger LOGGER = LogManager.getLogger("Packet Utils");
/**
* Extracts channel information from CustomPayloadC2SPacket or CustomPayloadS2CPacket using their payloads.
*
* @param packet The packet to extract from.
* @return The identifier of the payload if available, null otherwise.
*/
public static Identifier getChannelFromPacket(Packet<?> packet) {
try {
// Handle CustomPayloadC2SPacket by extracting its CustomPayload
if (packet instanceof CustomPayloadC2SPacket customPayloadC2SPacket) {
CustomPayload payload = customPayloadC2SPacket.payload();
return extractChannelIdentifier(payload);
}
// Handle CustomPayloadS2CPacket similarly, if needed
else if (packet instanceof CustomPayloadS2CPacket customPayloadS2CPacket) {
CustomPayload payload = customPayloadS2CPacket.payload();
return extractChannelIdentifier(payload);
}
} catch (Exception e) {
LOGGER.error("Failed to extract channel from packet: {}", packet.getClass().getName(), e);
}
return null;
}
/**
* Extracts the identifier from CustomPayload, if available.
*
* @param payload The CustomPayload object.
* @return The identifier of the channel, if available.
*/
private static Identifier extractChannelIdentifier(CustomPayload payload) {
// Check if payload is a known type that contains a channel identifier
if (payload instanceof BrandCustomPayload) {
// Access the channel from BrandCustomPayload if applicable
return CustomPayload.id(Identifier.DEFAULT_NAMESPACE).id(); // Replace with the actual method that returns the identifier if different
} else if (payload instanceof UnknownCustomPayload unknownPayload) {
// Access the channel from UnknownCustomPayload
return unknownPayload.id(); // Replace with the actual method that returns the identifier if different
}
// If no known type matches, log and return null
LOGGER.warn("Unknown CustomPayload type: {}", payload.getClass().getName());
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment