Java Code Examples for us.myles.ViaVersion.api.data.UserConnection

The following examples show how to use us.myles.ViaVersion.api.data.UserConnection. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: ViaVersion   Author: ViaVersion   File: ChatRewriter.java    License: MIT License 6 votes vote down vote up
/**
 * Rewrite chat being sent to the client so that gamemode issues don't occur.
 *
 * @param obj  The json object being sent by the server
 * @param user The player involved. (Required for Gamemode info)
 */
public static void toClient(JsonObject obj, UserConnection user) {
    //Check gamemode change
    if (obj.get("translate") != null && obj.get("translate").getAsString().equals("gameMode.changed")) {
        String gameMode = user.get(EntityTracker1_9.class).getGameMode().getText();

        JsonObject gameModeObject = new JsonObject();
        gameModeObject.addProperty("text", gameMode);
        gameModeObject.addProperty("color", "gray");
        gameModeObject.addProperty("italic", true);

        JsonArray array = new JsonArray();
        array.add(gameModeObject);

        obj.add("with", array);
    }
}
 
Example #2
Source Project: ViaVersion   Author: ViaVersion   File: ConnectionData.java    License: MIT License 6 votes vote down vote up
public static void update(UserConnection user, Position position) {
    for (BlockFace face : BlockFace.values()) {
        Position pos = position.getRelative(face);
        int blockState = blockConnectionProvider.getBlockData(user, pos.getX(), pos.getY(), pos.getZ());
        ConnectionHandler handler = connectionHandlerMap.get(blockState);
        if (handler == null) continue;

        int newBlockState = handler.connect(user, pos, blockState);
        PacketWrapper blockUpdatePacket = new PacketWrapper(0x0B, null, user);
        blockUpdatePacket.write(Type.POSITION, pos);
        blockUpdatePacket.write(Type.VAR_INT, newBlockState);
        try {
            blockUpdatePacket.send(Protocol1_13To1_12_2.class, true, true);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
 
Example #3
Source Project: ViaVersion   Author: ViaVersion   File: WorldPackets.java    License: MIT License 6 votes vote down vote up
private static int checkStorage(UserConnection user, Position position, int newId) {
    BlockStorage storage = user.get(BlockStorage.class);
    if (storage.contains(position)) {
        BlockStorage.ReplacementData data = storage.get(position);

        if (data.getOriginal() == newId) {
            if (data.getReplacement() != -1) {
                return data.getReplacement();
            }
        } else {
            storage.remove(position);
            // Check if the new id has to be stored
            if (storage.isWelcome(newId))
                storage.store(position, newId);
        }
    } else if (storage.isWelcome(newId))
        storage.store(position, newId);
    return newId;
}
 
Example #4
Source Project: ViaRewind   Author: ViaVersion   File: Windows.java    License: MIT License 6 votes vote down vote up
public static void updateBrewingStand(UserConnection user, Item blazePowder, short windowId) {
	if (blazePowder != null && blazePowder.getIdentifier() != 377) return;
	int amount = blazePowder == null ? 0 : blazePowder.getAmount();
	PacketWrapper openWindow = new PacketWrapper(0x2D, null, user);
	openWindow.write(Type.UNSIGNED_BYTE, windowId);
	openWindow.write(Type.STRING, "minecraft:brewing_stand");
	openWindow.write(Type.STRING, "[{\"translate\":\"container.brewing\"},{\"text\":\": \",\"color\":\"dark_gray\"},{\"text\":\"§4" + amount + " \",\"color\":\"dark_red\"},{\"translate\":\"item.blazePowder.name\",\"color\":\"dark_red\"}]");
	openWindow.write(Type.UNSIGNED_BYTE, (short) 420);
	PacketUtil.sendPacket(openWindow, Protocol1_8TO1_9.class);

	Item[] items = user.get(Windows.class).getBrewingItems(windowId);
	for (int i = 0; i < items.length; i++) {
		PacketWrapper setSlot = new PacketWrapper(0x2F, null, user);
		setSlot.write(Type.BYTE, (byte) windowId);
		setSlot.write(Type.SHORT, (short) i);
		setSlot.write(Type.ITEM, items[i]);
		PacketUtil.sendPacket(setSlot, Protocol1_8TO1_9.class);
	}
}
 
Example #5
Source Project: ViaBackwards   Author: ViaVersion   File: PistonHandler.java    License: MIT License 6 votes vote down vote up
@Override
public CompoundTag transform(UserConnection user, int blockId, CompoundTag tag) {
    CompoundTag blockState = tag.get("blockState");
    String dataFromTag = getDataFromTag(blockState);
    if (dataFromTag == null) return tag;

    Integer id = pistonIds.get(dataFromTag);
    if (id == null) {
        //TODO see why this could be null and if this is bad
        return tag;
    }

    tag.put(new IntTag("blockId", id >> 4));
    tag.put(new IntTag("blockData", id & 15));
    return tag;
}
 
Example #6
Source Project: ViaVersion   Author: ViaVersion   File: BungeeChannelInitializer.java    License: MIT License 6 votes vote down vote up
@Override
protected void initChannel(Channel socketChannel) throws Exception {
    UserConnection info = new UserConnection(socketChannel);
    // init protocol
    new ProtocolPipeline(info);
    // Add originals
    this.method.invoke(this.original, socketChannel);

    if (socketChannel.pipeline().get("packet-encoder") == null) return; // Don't inject if no packet-encoder
    if (socketChannel.pipeline().get("packet-decoder") == null) return; // Don't inject if no packet-decoder
    // Add our transformers
    BungeeEncodeHandler encoder = new BungeeEncodeHandler(info);
    BungeeDecodeHandler decoder = new BungeeDecodeHandler(info);

    socketChannel.pipeline().addBefore("packet-encoder", "via-encoder", encoder);
    socketChannel.pipeline().addBefore("packet-decoder", "via-decoder", decoder);
}
 
Example #7
Source Project: ViaBackwards   Author: ViaVersion   File: BungeePlugin.java    License: MIT License 6 votes vote down vote up
@EventHandler(priority = -110) // Slightly later than VV
public void serverConnected(ServerConnectedEvent event) {
    ProxiedPlayer player = event.getPlayer();
    if (player.getServer() == null) return;

    UserConnection connection = Via.getManager().getConnection(player.getUniqueId());
    if (connection == null) return;

    ProtocolInfo info = connection.getProtocolInfo();
    if (info == null || !info.getPipeline().contains(Protocol1_15_2To1_16.class)) return;

    // Need to send a dummy respawn with a different dimension before the actual respawn
    // We also don't know what dimension it's sent to, so just send 2 dummies :>
    sendRespawn(connection, -1);
    sendRespawn(connection, 0);
}
 
Example #8
Source Project: ViaVersion   Author: ViaVersion   File: ElytraPatch.java    License: MIT License 6 votes vote down vote up
@EventHandler(priority = EventPriority.HIGH)
public void onServerConnected(ServerConnectedEvent event) {
    UserConnection user = Via.getManager().getConnection(event.getPlayer().getUniqueId());
    if (user == null) return;

    try {
        if (user.getProtocolInfo().getPipeline().contains(Protocol1_9To1_8.class)) {
            int entityId = user.get(EntityTracker1_9.class).getProvidedEntityId();

            PacketWrapper wrapper = new PacketWrapper(0x39, null, user);

            wrapper.write(Type.VAR_INT, entityId);
            wrapper.write(Types1_9.METADATA_LIST, Collections.singletonList(new Metadata(0, MetaType1_9.Byte, (byte) 0)));

            wrapper.send(Protocol1_9To1_8.class);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #9
Source Project: ViaVersion   Author: ViaVersion   File: VelocityServerHandler.java    License: MIT License 6 votes vote down vote up
@Subscribe
public void preServerConnect(ServerPreConnectEvent e) {
    try {
        UserConnection user = Via.getManager().getConnection(e.getPlayer().getUniqueId());
        if (user == null) return;
        if (!user.has(VelocityStorage.class)) {
            user.put(new VelocityStorage(user, e.getPlayer()));
        }

        int protocolId = ProtocolDetectorService.getProtocolId(e.getOriginalServer().getServerInfo().getName());
        List<Pair<Integer, Protocol>> protocols = ProtocolRegistry.getProtocolPath(user.getProtocolInfo().getProtocolVersion(), protocolId);

        // Check if ViaVersion can support that version
        Object connection = getMinecraftConnection.invoke(e.getPlayer());
        setNextProtocolVersion.invoke(connection, ProtocolVersion.getProtocolVersion(protocols == null
                ? user.getProtocolInfo().getProtocolVersion()
                : protocolId));

    } catch (IllegalAccessException | InvocationTargetException e1) {
        e1.printStackTrace();
    }
}
 
Example #10
Source Project: ViaVersion   Author: ViaVersion   File: SpongeChannelInitializer.java    License: MIT License 6 votes vote down vote up
@Override
protected void initChannel(Channel channel) throws Exception {
    // Ensure ViaVersion is loaded
    if (ProtocolRegistry.SERVER_PROTOCOL != -1
            && channel instanceof SocketChannel) { // channel can be LocalChannel on internal server
        UserConnection info = new UserConnection((SocketChannel) channel);
        // init protocol
        new ProtocolPipeline(info);
        // Add originals
        this.method.invoke(this.original, channel);
        // Add our transformers
        MessageToByteEncoder encoder = new SpongeEncodeHandler(info, (MessageToByteEncoder) channel.pipeline().get("encoder"));
        ByteToMessageDecoder decoder = new SpongeDecodeHandler(info, (ByteToMessageDecoder) channel.pipeline().get("decoder"));
        SpongePacketHandler chunkHandler = new SpongePacketHandler(info);

        channel.pipeline().replace("encoder", "encoder", encoder);
        channel.pipeline().replace("decoder", "decoder", decoder);
        channel.pipeline().addAfter("packet_handler", "viaversion_packet_handler", chunkHandler);
    } else {
        this.method.invoke(this.original, channel);
    }
}
 
Example #11
Source Project: ViaBackwards   Author: ViaVersion   File: SkullHandler.java    License: MIT License 6 votes vote down vote up
@Override
public CompoundTag transform(UserConnection user, int blockId, CompoundTag tag) {
    int diff = blockId - SKULL_START;
    int pos = diff % 20;
    byte type = (byte) Math.floor(diff / 20f);

    // Set type
    tag.put(new ByteTag("SkullType", type));

    // Remove wall skulls
    if (pos < 4) {
        return tag;
    }

    // Add rotation for normal skulls
    tag.put(new ByteTag("Rot", (byte) ((pos - 4) & 255)));

    return tag;
}
 
Example #12
Source Project: ViaVersion   Author: ViaVersion   File: VelocityVersionProvider.java    License: MIT License 5 votes vote down vote up
@Override
public int getServerProtocol(UserConnection user) throws Exception {
    int playerVersion = user.getProtocolInfo().getProtocolVersion();

    IntStream versions = com.velocitypowered.api.network.ProtocolVersion.SUPPORTED_VERSIONS.stream()
            .mapToInt(com.velocitypowered.api.network.ProtocolVersion::getProtocol);

    // Modern forwarding mode needs 1.13 Login plugin message
    if (VelocityViaInjector.getPlayerInfoForwardingMode != null
            && ((Enum<?>) VelocityViaInjector.getPlayerInfoForwardingMode.invoke(VelocityPlugin.PROXY.getConfiguration()))
            .name().equals("MODERN")) {
        versions = versions.filter(ver -> ver >= ProtocolVersion.v1_13.getId());
    }
    int[] compatibleProtocols = versions.toArray();

    // Bungee supports it
    if (Arrays.binarySearch(compatibleProtocols, playerVersion) >= 0)
        return playerVersion;

    // Older than bungee supports, get the lowest version
    if (playerVersion < compatibleProtocols[0]) {
        return compatibleProtocols[0];
    }

    // Loop through all protocols to get the closest protocol id that bungee supports (and that viaversion does too)

    // TODO: This needs a better fix, i.e checking ProtocolRegistry to see if it would work.
    // This is more of a workaround for snapshot support by bungee.
    for (int i = compatibleProtocols.length - 1; i >= 0; i--) {
        int protocol = compatibleProtocols[i];
        if (playerVersion > protocol && ProtocolVersion.isRegistered(protocol))
            return protocol;
    }

    Via.getPlatform().getLogger().severe("Panic, no protocol id found for " + playerVersion);
    return playerVersion;
}
 
Example #13
Source Project: ViaVersion   Author: ViaVersion   File: FireConnectionHandler.java    License: MIT License 5 votes vote down vote up
@Override
public int connect(UserConnection user, Position position, int blockState) {
    byte states = 0;
    if (flammableBlocks.contains(getBlockData(user, position.getRelative(BlockFace.EAST)))) states |= 1;
    if (flammableBlocks.contains(getBlockData(user, position.getRelative(BlockFace.NORTH)))) states |= 2;
    if (flammableBlocks.contains(getBlockData(user, position.getRelative(BlockFace.SOUTH)))) states |= 4;
    if (flammableBlocks.contains(getBlockData(user, position.getRelative(BlockFace.TOP)))) states |= 8;
    if (flammableBlocks.contains(getBlockData(user, position.getRelative(BlockFace.WEST)))) states |= 16;
    return connectedBlocks.get(states);
}
 
Example #14
Source Project: ViaVersion   Author: ViaVersion   File: FlowerPotHandler.java    License: MIT License 5 votes vote down vote up
@Override
public int transform(UserConnection user, CompoundTag tag) {
    Object item = tag.contains("Item") ? tag.get("Item").getValue() : null;
    Object data = tag.contains("Data") ? tag.get("Data").getValue() : null;

    // Convert item to String without namespace or to Byte
    if (item instanceof String) {
        item = ((String) item).replace("minecraft:", "");
    } else if (item instanceof Number) {
        item = ((Number) item).byteValue();
    } else {
        item = (byte) 0;
    }

    // Convert data to Byte
    if (data instanceof Number) {
        data = ((Number) data).byteValue();
    } else {
        data = (byte) 0;
    }

    Integer flower = flowers.get(new Pair<>(item, (byte) data));
    if (flower != null) return flower;
    flower = flowers.get(new Pair<>(item, (byte) 0));
    if (flower != null) return flower;

    return 5265; // Fallback to empty pot
}
 
Example #15
Source Project: ViaVersion   Author: ViaVersion   File: Protocol1_13_1To1_13.java    License: MIT License 5 votes vote down vote up
@Override
public void init(UserConnection userConnection) {
    userConnection.put(new EntityTracker1_13(userConnection));
    if (!userConnection.has(ClientWorld.class)) {
        userConnection.put(new ClientWorld(userConnection));
    }
}
 
Example #16
Source Project: ViaVersion   Author: ViaVersion   File: VelocityBossBarProvider.java    License: MIT License 5 votes vote down vote up
@Override
public void handleAdd(UserConnection user, UUID barUUID) {
    if (user.has(VelocityStorage.class)) {
        VelocityStorage storage = user.get(VelocityStorage.class);
        // Check if bossbars are supported by bungee, static maybe
        if (storage.getBossbar() != null) {
            storage.getBossbar().add(barUUID);
        }
    }
}
 
Example #17
Source Project: ViaVersion   Author: ViaVersion   File: VineConnectionHandler.java    License: MIT License 5 votes vote down vote up
@Override
public int connect(UserConnection user, Position position, int blockState) {
    if (isAttachedToBlock(user, position)) return blockState;

    Position upperPos = position.getRelative(BlockFace.TOP);
    int upperBlock = getBlockData(user, upperPos);
    if (vines.contains(upperBlock) && isAttachedToBlock(user, upperPos)) return blockState;

    // Map to air if not attached to block, and upper block is also not a vine attached to a block
    return 0;
}
 
Example #18
Source Project: ViaBackwards   Author: ViaVersion   File: BlockItemPackets1_11.java    License: MIT License 5 votes vote down vote up
private boolean isLlama(UserConnection user) {
    WindowTracker tracker = user.get(WindowTracker.class);
    if (tracker.getInventory() != null && tracker.getInventory().equals("EntityHorse")) {
        EntityTracker.ProtocolEntityTracker entTracker = user.get(EntityTracker.class).get(getProtocol());
        EntityTracker.StoredEntity storedEntity = entTracker.getEntity(tracker.getEntityId());
        return storedEntity != null && storedEntity.getType().is(Entity1_11Types.EntityType.LIAMA);
    }
    return false;
}
 
Example #19
Source Project: ViaVersion   Author: ViaVersion   File: ConnectionData.java    License: MIT License 5 votes vote down vote up
public static void connectBlocks(UserConnection user, Chunk chunk) {
    long xOff = chunk.getX() << 4;
    long zOff = chunk.getZ() << 4;

    for (int i = 0; i < chunk.getSections().length; i++) {
        ChunkSection section = chunk.getSections()[i];
        if (section == null) continue;

        boolean willConnect = false;

        for (int p = 0; p < section.getPaletteSize(); p++) {
            int id = section.getPaletteEntry(p);
            if (ConnectionData.connects(id)) {
                willConnect = true;
                break;
            }
        }
        if (!willConnect) continue;

        long yOff = i << 4;

        for (int y = 0; y < 16; y++) {
            for (int z = 0; z < 16; z++) {
                for (int x = 0; x < 16; x++) {
                    int block = section.getFlatBlock(x, y, z);

                    ConnectionHandler handler = ConnectionData.getConnectionHandler(block);
                    if (handler != null) {
                        block = handler.connect(user, new Position(
                                (int) (xOff + x),
                                (short) (yOff + y),
                                (int) (zOff + z)
                        ), block);
                        section.setFlatBlock(x, y, z, block);
                    }
                }
            }
        }
    }
}
 
Example #20
Source Project: ViaVersion   Author: ViaVersion   File: GlassConnectionHandler.java    License: MIT License 5 votes vote down vote up
@Override
protected byte getStates(UserConnection user, Position position, int blockState) {
    byte states = super.getStates(user, position, blockState);
    if (states != 0) return states;

    ProtocolInfo protocolInfo = user.getProtocolInfo();
    return protocolInfo.getServerProtocolVersion() <= 47
            && protocolInfo.getServerProtocolVersion() != -1 ? 0xF : states;
}
 
Example #21
Source Project: ViaVersion   Author: ViaVersion   File: StairConnectionHandler.java    License: MIT License 5 votes vote down vote up
@Override
public int connect(UserConnection user, Position position, int blockState) {
    StairData stairData = stairDataMap.get(blockState);
    if (stairData == null) return blockState;

    short s = 0;
    if (stairData.isBottom()) s |= 1;
    s |= getShape(user, position, stairData) << 1;
    s |= stairData.getType() << 4;
    s |= stairData.getFacing().ordinal() << 9;

    Integer newBlockState = connectedBlocks.get(s);
    return newBlockState == null ? blockState : newBlockState;
}
 
Example #22
Source Project: ViaBackwards   Author: ViaVersion   File: Protocol1_11To1_11_1.java    License: MIT License 5 votes vote down vote up
@Override
public void init(UserConnection user) {
    // Register ClientWorld
    if (!user.has(ClientWorld.class)) {
        user.put(new ClientWorld(user));
    }

    // Register EntityTracker if it doesn't exist yet.
    if (!user.has(EntityTracker.class)) {
        user.put(new EntityTracker(user));
    }

    // Init protocol in EntityTracker
    user.get(EntityTracker.class).initProtocol(this);
}
 
Example #23
Source Project: ViaBackwards   Author: ViaVersion   File: BungeePlugin.java    License: MIT License 5 votes vote down vote up
private void sendRespawn(UserConnection connection, int dimension) {
    PacketWrapper packet = new PacketWrapper(ClientboundPackets1_15.RESPAWN.ordinal(), null, connection);
    packet.write(Type.INT, dimension);
    packet.write(Type.LONG, 0L);
    packet.write(Type.UNSIGNED_BYTE, (short) 0);
    packet.write(Type.STRING, "default");
    try {
        packet.send(Protocol1_15_2To1_16.class, true, true);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #24
Source Project: ViaVersion   Author: ViaVersion   File: BungeeBossBarProvider.java    License: MIT License 5 votes vote down vote up
@Override
public void handleRemove(UserConnection user, UUID barUUID) {
    if (user.has(BungeeStorage.class)) {
        BungeeStorage storage = user.get(BungeeStorage.class);
        if (storage.getBossbar() != null) {
            storage.getBossbar().remove(barUUID);
        }
    }
}
 
Example #25
Source Project: ViaVersion   Author: ViaVersion   File: BungeeStorage.java    License: MIT License 5 votes vote down vote up
public BungeeStorage(UserConnection user, ProxiedPlayer player) {
    super(user);
    this.player = player;
    this.currentServer = "";

    // Get bossbar list if it's supported
    if (bossField != null) {
        try {
            bossbar = (Set<UUID>) bossField.get(player);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
 
Example #26
Source Project: ViaVersion   Author: ViaVersion   File: ViaIdleThread.java    License: MIT License 5 votes vote down vote up
@Override
public void run() {
    for (UserConnection info : Via.getManager().getConnections()) {
        ProtocolInfo protocolInfo = info.getProtocolInfo();
        if (protocolInfo != null && protocolInfo.getPipeline().contains(Protocol1_9To1_8.class)) {
            long nextIdleUpdate = info.get(MovementTracker.class).getNextIdlePacket();
            if (nextIdleUpdate <= System.currentTimeMillis()) {
                if (info.getChannel().isOpen()) {
                    Via.getManager().getProviders().get(MovementTransmitterProvider.class).sendPlayer(info);
                }
            }
        }
    }
}
 
Example #27
Source Project: ViaFabric   Author: ViaVersion   File: UserCommandSender.java    License: MIT License 4 votes vote down vote up
public UserCommandSender(UserConnection con) {
    this.con = con;
}
 
Example #28
Source Project: ViaFabric   Author: ViaVersion   File: VRViaAPI.java    License: MIT License 4 votes vote down vote up
@Override
public void sendRawPacket(UUID uuid, ByteBuf byteBuf) throws IllegalArgumentException {
    UserConnection ci = Via.getManager().getConnection(uuid);
    ci.sendRawPacket(byteBuf);
}
 
Example #29
Source Project: ViaVersion   Author: ViaVersion   File: BaseProtocol.java    License: MIT License 4 votes vote down vote up
@Override
public void init(UserConnection userConnection) {
    // Nothing gets added, ProtocolPipeline handles ProtocolInfo
}
 
Example #30
Source Project: ViaFabric   Author: ViaVersion   File: VRVersionProvider.java    License: MIT License 4 votes vote down vote up
@Override
public int getServerProtocol(UserConnection connection) throws Exception {
    if (connection instanceof VRClientSideUserConnection)
        return ViaFabric.config.getClientSideVersion();
    return super.getServerProtocol(connection);
}