Java Code Examples for com.comphenix.protocol.events.PacketEvent

The following are top voted examples for showing how to use com.comphenix.protocol.events.PacketEvent. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: DynamicAC   File: MovementListener.java   View source code 7 votes vote down vote up
public static void listenPackets() {
    ProtocolLibrary.getProtocolManager().addPacketListener(new PacketAdapter(DynamicAC.instance, ListenerPriority.NORMAL, PacketType.Play.Client.POSITION, PacketType.Play.Client.POSITION_LOOK) {
        @Override
        public void onPacketReceiving(PacketEvent e) {
            Player p = e.getPlayer();
            Location cur = e.getPlayer().getLocation();
            if(!MOVE_COUNT.containsKey(p)) {
                MOVE_COUNT.put(p, 1);
            } else {
                MOVE_COUNT.put(p, MOVE_COUNT.get(p) + 1);
                if(MOVE_COUNT.get(p) > MagicNumbers.BLINK_PACKET)  {
                    for(Player player : DynamicAC.instance.onlinestaff) {
                        player.sendMessage(DynamicAC.prefix + p.getName() + " failed Blink test, sent too many " +
                                "packets in one place!");
                    }
                    MOVE_COUNT.remove(p);
                    e.setCancelled(true);
                    e.getPlayer().teleport(cur);
                }
            }
        }
    });
}
 
Example 2
Project: NeverLag   File: AntiAUWMod.java   View source code 6 votes vote down vote up
private static void onSetCreativeSlotPacket(PacketEvent e) {
	if (!e.getPlayer().isOp()) {
		try {
			StructureModifier<ItemStack> structureModifier = e.getPacket().getItemModifier();
			if (structureModifier != null) {
				ItemStack item = structureModifier.read(0);
				if (item != null) {
					Object craftItem = method_asNMSCopy.invoke(null, item);
					if (craftItem != null) {
						Object hasTag = method_hasTag.invoke(craftItem);
						if (hasTag != null && (Boolean) hasTag) {
							e.setCancelled(true);
						}
					}
				}
			}
		} catch (Exception ex) {
			// ignore
		}
	}
}
 
Example 3
Project: RPGInventory   File: PlayerLoader.java   View source code 6 votes vote down vote up
@Override
public void onPacketSending(PacketEvent event) {
    WrapperPlayServerResourcePackSend packet = new WrapperPlayServerResourcePackSend(event.getPacket());
    if (!packet.getUrl().equals(Config.getConfig().getString("resource-pack.url"))) {
        return;
    }

    final Player player = event.getPlayer();
    packet.setHash(Config.getConfig().getString("resource-pack.hash"));
    final LoadData loadData = new LoadData();
    loadList.put(player.getUniqueId(), loadData);

    new BukkitRunnable() {
        @Override
        public void run() {
            loadData.setPrepared();
        }
    }.runTaskLater(RPGInventory.getInstance(), Config.getConfig().getInt("resource-pack.delay") * 20);
}
 
Example 4
Project: RPGInventory   File: CraftListener.java   View source code 6 votes vote down vote up
@Override
public void onPacketSending(PacketEvent event) {
    Player player = event.getPlayer();
    //noinspection ConstantConditions
    if (event.isCancelled() || !InventoryManager.playerIsLoaded(player)
            || isNotNeededHere(player)) {
        return;
    }

    WrapperPlayServerWindowItems packet = new WrapperPlayServerWindowItems(event.getPacket());
    if (player.getOpenInventory().getType() == InventoryType.WORKBENCH) {
        List<ItemStack> contents = packet.getSlotData();

        List<CraftExtension> extensions = CraftManager.getExtensions(player);
        for (CraftExtension extension : extensions) {
            for (int slot : extension.getSlots()) {
                contents.set(slot, extension.getCapItem());
            }
        }

        packet.setSlotData(contents);
    }
}
 
Example 5
Project: MultiLineAPI   File: PacketListener.java   View source code 6 votes vote down vote up
@Override
public void onPacketReceiving(PacketEvent packetEvent) {
    Player p = packetEvent.getPlayer();
    PacketContainer packet = packetEvent.getPacket();
    if (packet.getType().equals(PacketType.Play.Client.USE_ENTITY)) {
        UUID u = tagMap.get(packet.getIntegers().read(0));
        if (u == null) return;
        Entity e = p.getNearbyEntities(8, 8, 8).stream().filter(entity -> entity.getUniqueId().equals(u)).findAny
                ().orElse(null);
        if (e == null) return;
        if (!HitboxUtil.isLookingAt(p, e)) return;
        packet.getIntegers().write(0, e.getEntityId());
        if (e.getType() == EntityType.ARMOR_STAND)
            packet.getEntityUseActions().write(0, EnumWrappers.EntityUseAction.ATTACK);
    }
}
 
Example 6
Project: Mega-Walls   File: EntityHider.java   View source code 6 votes vote down vote up
/**
 * Construct the packet listener that will be used to intercept every entity-related packet.
 *
 * @param plugin - the parent plugin.
 *
 * @return The packet listener.
 */
private PacketAdapter constructProtocol(Plugin plugin)
{
    return new PacketAdapter(plugin, ENTITY_PACKETS)
    {
        @Override
        public void onPacketSending(PacketEvent event)
        {
            int entityID = event.getPacket().getIntegers().read(0);

            // See if this packet should be cancelled
            if (!isVisible(event.getPlayer(), entityID))
            {
                event.setCancelled(true);
            }
        }
    };
}
 
Example 7
Project: NerdMoods   File: NerdMoods.java   View source code 6 votes vote down vote up
/**
 * @see org.bukkit.plugin.java.JavaPlugin#onEnable()
 */
@Override
public void onEnable() {
    saveDefaultConfig();
    CONFIG = new Configuration(this);
    CONFIG.reload();

    _protocolManager = ProtocolLibrary.getProtocolManager();
    _protocolManager.addPacketListener(new PacketAdapter(this, ListenerPriority.NORMAL, PacketType.Play.Server.UPDATE_TIME) {
        @Override
        public void onPacketSending(PacketEvent event) {
            if (event.getPacketType() == PacketType.Play.Server.UPDATE_TIME &&
                _ignoringTime.contains(event.getPlayer()) &&
                event.getPacket().getLongs().read(1) >= 0) {
                event.setCancelled(true);
            }
        }
    });
}
 
Example 8
Project: AudioConnect   File: VerifyRequestPacketListener.java   View source code 6 votes vote down vote up
@Override
public void onPacketSending(PacketEvent event) {
    String verifyCode = verifyCodeSupplier.get();
    if (verifyCode != null) {
        try {
            WrappedServerPing ping = event.getPacket().getServerPings().read(0);

            Object motd = jsonParser.parse(ping.getMotD().getJson());
            if (motd instanceof JSONObject) {
                JSONObject component = (JSONObject) motd;
                component.put("text", verifyCode + ChatColor.RESET + component.get("text"));
                ping.setMotD(WrappedChatComponent.fromJson(component.toJSONString()));
            } else {
                // Legacy String format
                ping.setMotD(verifyCode + ChatColor.RESET + motd);
            }
        } catch (ParseException e) {
            ac.getLogger().log(Level.WARNING, "Failed to parse MOTD for verify request", e);
        }
    }
}
 
Example 9
Project: SimpleAntiAura   File: AntiAura.java   View source code 6 votes vote down vote up
public void register() {
    ProtocolLibrary.getProtocolManager().addPacketListener(
            new PacketAdapter(this, WrapperPlayClientUseEntity.TYPE) {
                @Override
                public void onPacketReceiving(PacketEvent event) {
                    if (event.getPacketType() == WrapperPlayClientUseEntity.TYPE) {
                        WrapperPlayClientUseEntity packet = new WrapperPlayClientUseEntity(event.getPacket());
                        int entID = packet.getTarget();
                        if (running.containsKey(event.getPlayer().getUniqueId()) && packet.getType() == EntityUseAction.ATTACK) {
                            running.get(event.getPlayer().getUniqueId()).markAsKilled(entID);
                        }
                    }
                }

            });
    this.isRegistered = true;
}
 
Example 10
Project: I18N   File: InterceptorChat.java   View source code 6 votes vote down vote up
@Override
public void onPacketSending( PacketEvent event ) {
	final Player                  player = event.getPlayer();
	final PacketContainer packet = event.getPacket();
	
	String message     = this.restoreTextFromChatComponent( packet.getChatComponents().read( 0 ) );
	String translation = this.translateMessageIfAppropriate( this.i18n.getLocale( player.getUniqueId() ), message );
	
	if ( message != translation ) {
		// Yes, the test of instance equality is what I want to do here
		// as it saves me time determining whether the message was actually
		// translated or not:
		
		// Issue #4:
		//  https://github.com/BlackyPaw/I18N/issues/4
		//
		// Do this ugly conversion thing here in order to enforce usage of JSON color tags
		// over the legacy chat format. Invoking WrappedChatComponent.fromText( ... ) for
		// example, would result in a JSON such as {"text":"§cExample"} which can, if long enough
		// and automatically put onto a new line by Minecraft, lose its formatting on the addtional
		// line of chat. This issue does only arise for chat currently as it is the only place where
		// multiple lines are even supported. In case this issue should arise again somewhere else
		// one will simply have to do this conversion there, too:
		packet.getChatComponents().write( 0, ComponentConverter.fromBaseComponent( TextComponent.fromLegacyText( translation ) ) );
	}
}
 
Example 11
Project: I18N   File: InterceptorSign.java   View source code 6 votes vote down vote up
private void onMapChunk( PacketEvent event ) {
	final Player          player = event.getPlayer();
	final PacketContainer packet = event.getPacket();
	final Locale          locale = this.i18n.getLocale( player.getUniqueId() );
	
	List handleList = packet.getSpecificModifier( List.class ).read( 0 );
	for ( Object compoundHandle : handleList ) {
		NbtCompound compound = NbtFactory.fromNMSCompound( compoundHandle );
		String id = compound.getString( "id" );
		if ( id.equals( "minecraft:sign" ) || id.equals( "Sign" ) ) {
			for ( int i = 1; i <= 4; ++i ) {
				final String key = "Text" + i;
				String message    = this.gson.fromJson( compound.getString( key ), ChatComponent.class ).getUnformattedText();
				String translated = this.translateMessageIfAppropriate( locale, message );
				
				if ( message != translated ) {
					compound.put( key, WrappedChatComponent.fromText( translated ).getJson() );
				}
			}
		}
	}
}
 
Example 12
Project: I18N   File: InterceptorChat.java   View source code 6 votes vote down vote up
@Override
public void onPacketSending( PacketEvent event ) {
	final Player                  player = event.getPlayer();
	final PacketContainer packet = event.getPacket();
	
	String message     = this.restoreTextFromChatComponent( packet.getChatComponents().read( 0 ) );
	String translation = this.translateMessageIfAppropriate( this.i18n.getLocale( player.getUniqueId() ), message );
	
	if ( message != translation ) {
		// Yes, the test of instance equality is what I want to do here
		// as it saves me time determining whether the message was actually
		// translated or not:
		
		// Issue #4:
		//  https://github.com/BlackyPaw/I18N/issues/4
		//
		// Do this ugly conversion thing here in order to enforce usage of JSON color tags
		// over the legacy chat format. Invoking WrappedChatComponent.fromText( ... ) for
		// example, would result in a JSON such as {"text":"§cExample"} which can, if long enough
		// and automatically put onto a new line by Minecraft, lose its formatting on the addtional
		// line of chat. This issue does only arise for chat currently as it is the only place where
		// multiple lines are even supported. In case this issue should arise again somewhere else
		// one will simply have to do this conversion there, too:
		packet.getChatComponents().write( 0, ComponentConverter.fromBaseComponent( TextComponent.fromLegacyText( translation ) ) );
	}
}
 
Example 13
Project: I18N   File: InterceptorSign.java   View source code 6 votes vote down vote up
@Override
public void onPacketSending( PacketEvent event ) {
	final Player          player = event.getPlayer();
	final PacketContainer packet = event.getPacket();
	
	// Translate all four lines if necessary:
	boolean                changed        = false;
	WrappedChatComponent[] chatComponents = packet.getChatComponentArrays().read( 0 );
	for ( int i = 0; i < chatComponents.length; ++i ) {
		WrappedChatComponent chat = chatComponents[i];
		if ( chat != null ) {
			String message    = this.restoreTextFromChatComponent( chat );
			String translated = this.translateMessageIfAppropriate( this.i18n.getLocale( player.getUniqueId() ), message );
			
			if ( message != translated ) {
				chatComponents[i] = WrappedChatComponent.fromText( translated );
				changed = true;
			}
		}
	}
	
	if ( changed ) {
		// Only write back when really needed:
		packet.getChatComponentArrays().write( 0, chatComponents );
	}
}
 
Example 14
Project: I18N   File: InterceptorChat.java   View source code 6 votes vote down vote up
@Override
public void onPacketSending( PacketEvent event ) {
	final Player                  player = event.getPlayer();
	final PacketContainer packet = event.getPacket();
	
	String message     = this.restoreTextFromChatComponent( packet.getChatComponents().read( 0 ) );
	String translation = this.translateMessageIfAppropriate( this.i18n.getLocale( player.getUniqueId() ), message );
	
	if ( message != translation ) {
		// Yes, the test of instance equality is what I want to do here
		// as it saves me time determining whether the message was actually
		// translated or not:
		
		// Issue #4:
		//  https://github.com/BlackyPaw/I18N/issues/4
		//
		// Do this ugly conversion thing here in order to enforce usage of JSON color tags
		// over the legacy chat format. Invoking WrappedChatComponent.fromText( ... ) for
		// example, would result in a JSON such as {"text":"§cExample"} which can, if long enough
		// and automatically put onto a new line by Minecraft, lose its formatting on the addtional
		// line of chat. This issue does only arise for chat currently as it is the only place where
		// multiple lines are even supported. In case this issue should arise again somewhere else
		// one will simply have to do this conversion there, too:
		packet.getChatComponents().write( 0, ComponentConverter.fromBaseComponent( TextComponent.fromLegacyText( translation ) ) );
	}
}
 
Example 15
Project: I18N   File: InterceptorSign.java   View source code 6 votes vote down vote up
private void onMapChunk( PacketEvent event ) {
	final Player          player = event.getPlayer();
	final PacketContainer packet = event.getPacket();
	final Locale          locale = this.i18n.getLocale( player.getUniqueId() );
	
	List handleList = packet.getSpecificModifier( List.class ).read( 0 );
	for ( Object compoundHandle : handleList ) {
		NbtCompound compound = NbtFactory.fromNMSCompound( compoundHandle );
		String id = compound.getString( "id" );
		if ( id.equals( "minecraft:sign" ) || id.equals( "Sign" ) ) {
			for ( int i = 1; i <= 4; ++i ) {
				final String key = "Text" + i;
				String message    = this.gson.fromJson( compound.getString( key ), ChatComponent.class ).getUnformattedText();
				String translated = this.translateMessageIfAppropriate( locale, message );
				
				if ( message != translated ) {
					compound.put( key, WrappedChatComponent.fromText( translated ).getJson() );
				}
			}
		}
	}
}
 
Example 16
Project: K-Security   File: TransactionAntiBot.java   View source code 6 votes vote down vote up
@Override
public void onPacketReceiving(PacketEvent event) {
    Player player = event.getPlayer();
    int id = event.getPacketID();
    holder.holdIfPresent(event);
    if (id == Packets.Client.HANDSHAKE) {
        cacher.caching(player);
    }
    if (id == Packets.Client.TRANSACTION) {
        PacketContainer packet = event.getPacket();
        int pId = packet.getShorts().read(0);
        if (pId == Short.MIN_VALUE) {
            latch.countDown(player);
        }
    }
}
 
Example 17
Project: NoGlint   File: EquipmentListener.java   View source code 6 votes vote down vote up
@Override
public void onPacketSending( PacketEvent event ) {
    PacketContainer packet = event.getPacket();

    int entityID = packet.getIntegers().read( 0 );
    ItemStack item = packet.getItemModifier().read( 0 );

    //Run this check first to save on performance.
    if( plugin.getGlintManager().isGlintDisabled( event.getPlayer().getUniqueId() ) ) {
        Player player = GlintUtils.getPlayerByEntityID( entityID );

        if ( player != null && item != null && !item.getType().equals( Material.AIR )) {
            GlintUtils.removeGlint( item );
        }
    }

}
 
Example 18
Project: NoGlint   File: ItemListener.java   View source code 6 votes vote down vote up
@Override
public void onPacketSending( PacketEvent event ) {
    PacketContainer packet = event.getPacket();

    int entityID = packet.getIntegers().read( 0 );
    int type = packet.getIntegers().read( 9 );

    /*
    ItemStacks are ID'd as 2.
     */
    if( type == 2 ) {
        Entity entity = packet.getEntityModifier( event ).read( 0 );
        //Lets just make sure
        if( entity instanceof Item ) {
            ItemStack item = ( (Item) entity ).getItemStack();
            if( plugin.getGlintManager().isGlintDisabled( event.getPlayer().getUniqueId() ) ) {
                GlintUtils.removeGlint( item );
            }
        }
    }
}
 
Example 19
Project: BukkitLib   File: ProtocolLibUtilImplementation.java   View source code 6 votes vote down vote up
@Override
public void init(Plugin plugin) {
	ProtocolLibrary.getProtocolManager().addPacketListener(
			new PacketAdapter(PacketAdapter
					.params(plugin, PacketType.Play.Server.SET_SLOT,
							PacketType.Play.Server.WINDOW_ITEMS)
							.serverSide().listenerPriority(ListenerPriority.HIGH)) {

				@Override
				public void onPacketSending(PacketEvent event) {
					if (event.getPacketType().equals(PacketType.Play.Server.SET_SLOT)) {
						addGlow(new ItemStack[] { event.getPacket().getItemModifier().read(0) });
					} else {
						addGlow(event.getPacket().getItemArrayModifier().read(0));
					}
				}
			});
	
	_signManager = new ProtocolLibSignGUI(plugin);
	
	Bukkit.getServicesManager().register(SignGUI.class, _signManager, plugin, ServicePriority.Highest);
}
 
Example 20
Project: DDCustomPlugin   File: JailSigns.java   View source code 6 votes vote down vote up
public void enable() {
	ProtocolLibrary.getProtocolManager().addPacketListener(
			new PacketAdapter(plugin, ConnectionSide.SERVER_SIDE, ListenerPriority.NORMAL, new Integer[] {
					Integer.valueOf(130) 
			})
			{
				public void onPacketSending(PacketEvent event) {
					if (event.getPacketID() == 130)
						try {
							event.setPacket(modify(event.getPacket(), event.getPlayer().getName()));
						} catch (FieldAccessException e) {
							plugin.getLogger().log(Level.SEVERE, "Couldn't access field.", e);
						}
				}
			});
	log("Enabled");
}
 
Example 21
Project: BetonQuest   File: EntityHider.java   View source code 6 votes vote down vote up
/**
 * Construct the packet listener that will be used to intercept every
 * entity-related packet.
 * 
 * @param plugin
 *            - the parent plugin.
 * @return The packet listener.
 */
private PacketAdapter constructProtocol(Plugin plugin) {
    return new PacketAdapter(plugin, ENTITY_PACKETS) {

        @Override
        public void onPacketSending(PacketEvent event) {
            int index = event.getPacketType() == COMBAT_EVENT ? 1 : 0;

            Integer entityID = event.getPacket().getIntegers().readSafely(index);
            if (entityID != null) {
                if (!isVisible(event.getPlayer(), entityID)) {
                    event.setCancelled(true);
                }
            }
        }
    };
}
 
Example 22
Project: AntiAura   File: AntiAura.java   View source code 6 votes vote down vote up
public void register() {
    ProtocolLibrary.getProtocolManager().addPacketListener(
            new PacketAdapter(this, WrapperPlayClientUseEntity.TYPE) {
                @Override
                public void onPacketReceiving(PacketEvent event) {
                    if (event.getPacketType() == WrapperPlayClientUseEntity.TYPE) {
                        WrapperPlayClientUseEntity packet = new WrapperPlayClientUseEntity(event.getPacket());
                        int entID = packet.getTargetID();
                        if (running.containsKey(event.getPlayer().getUniqueId()) && packet.getType() == EntityUseAction.ATTACK) {
                            running.get(event.getPlayer().getUniqueId()).markAsKilled(entID);
                        }
                    }
                }

            });
    this.isRegistered = true;
}
 
Example 23
Project: sensibletoolbox   File: SoundMufflerListener.java   View source code 6 votes vote down vote up
@Override
public void onPacketSending(PacketEvent event) {
    int distance = SoundMuffler.DISTANCE * SoundMuffler.DISTANCE;
    if (event.getPacketType() == PacketType.Play.Server.NAMED_SOUND_EFFECT) {
        int x = event.getPacket().getIntegers().read(0) >> 3;
        int y = event.getPacket().getIntegers().read(1) >> 3;
        int z = event.getPacket().getIntegers().read(2) >> 3;
        Location loc = new Location(event.getPlayer().getWorld(), x, y, z);
        for (SoundMuffler sm : mufflers) {
            if (loc.getWorld().equals(sm.getLocation().getWorld()) && loc.distanceSquared(sm.getLocation()) < distance) {
                if (sm.getVolume() == 0) {
                    event.setCancelled(true);
                } else {
                    event.getPacket().getFloat().write(0, (float) sm.getVolume() / 100.0f);
                }
            }
        }
    }
}
 
Example 24
Project: DeadHorses   File: DeadHorses.java   View source code 6 votes vote down vote up
/**
 * Examine an EntityMetadata packet and if it is for a dead horse, modify it to reflect the actual
 * value of the horse's armor.
 * 
 * @param event PacketEvent to examine and potentially modify.
 */
private void handleMetadataPacket(PacketEvent event) {
  Entity entity = event.getPacket().getEntityModifier(event).read(ENTITY_INDEX);
  if (entity != null && entity.getType() == EntityType.HORSE) {
    switch (((Horse) entity).getVariant()) {
      default:
        return;
      case SKELETON_HORSE:
      case UNDEAD_HORSE:
        List<WrappedWatchableObject> watchables =
            event.getPacket().getWatchableCollectionModifier().read(WATCHABLE_INDEX);
        for (WrappedWatchableObject watchable : watchables) {
          if (watchable.getIndex() == ARMOR_INDEX) {
            int armor = getArmorMetadataValue((Horse) entity);
            // if (!watchable.getValue().equals(armor)) {
            watchable.setValue(armor, true);
            // }
            return;
          }
        }
    }
  }
}
 
Example 25
Project: DeadHorses   File: DeadHorses.java   View source code 6 votes vote down vote up
/**
 * Set up packet listening for ENTITY_METADATA packets so they can be modified to actually contain
 * the dead horses' equipped armor.
 */
private void setupPacketModification() {
  if (getServer().getPluginManager().getPlugin(PROTOCOL_LIB) instanceof ProtocolLibrary) {
    fancyLog("ProtocolLib detected, creating hook for entity metadata packets.");
    ProtocolManager manager = ProtocolLibrary.getProtocolManager();
    manager.addPacketListener(new PacketAdapter(new PacketAdapter.AdapterParameteters()
        .plugin(this).serverSide().types(PacketType.Play.Server.ENTITY_METADATA)) {
      @Override
      public void onPacketSending(PacketEvent event) {
        if (config.isPacketModificationEnabled()) {
          handleMetadataPacket(event);
        }
      }
    });
    hookedProtocolLib = true;
    fancyLog("Entity metadata packet hooked.");
  }
}
 
Example 26
Project: ScoreboardStats   File: PacketListener.java   View source code 6 votes vote down vote up
@Override
public void onPacketSending(PacketEvent packetEvent) {
    Player player = packetEvent.getPlayer();
    if (packetEvent.isCancelled() || player instanceof Factory) {
        return;
    }

    PacketContainer packet = packetEvent.getPacket();
    if (packet.hasMetadata("ScoreboardStats")) {
        //it's our own packet
        return;
    }

    UUID playerUUID = player.getUniqueId();

    //handle async packets by other plugins
    if (Bukkit.isPrimaryThread()) {
        ensureMainThread(playerUUID, packet);
    } else {
        PacketContainer clone = packet.deepClone();
        Bukkit.getScheduler().runTask(plugin, () -> ensureMainThread(playerUUID, clone));
    }
}
 
Example 27
Project: Crescent   File: BehaviourListeners.java   View source code 5 votes vote down vote up
public void registerPacketListeners() {
	final ProtocolManager protocolManager = ProtocolLibrary.getProtocolManager();
	for (PacketType packetType : new PacketType[] { PacketType.Play.Client.POSITION }) {
		protocolManager
				.addPacketListener(new PacketAdapter(Crescent.getInstance(), ListenerPriority.NORMAL, packetType) {
					@Override
					public void onPacketReceiving(PacketEvent event) {
						if (event.getPacketType() == packetType) {
							Bukkit.getPluginManager()
									.callEvent(new PlayerPacketEvent(event.getPlayer(), event.getPacket()));
						}
					}
				});
	}
}
 
Example 28
Project: EscapeLag   File: RecipeDupePatch.java   View source code 5 votes vote down vote up
public RecipeDupePatch() {
    keepers = Sets.newHashSet();
    
    ProtocolLibrary.getProtocolManager().addPacketListener(new PacketAdapter(EscapeLag.MainThis, Play.Client.AUTO_RECIPE) {
        @Override
        public void onPacketReceiving(PacketEvent evt) {
            if (!ConfigPatch.autoRecipePatch) return;
            keepers.add(evt.getPlayer());
        }
    });
}
 
Example 29
Project: AuthMeGUI   File: SignLoginWindow.java   View source code 5 votes vote down vote up
public SignLoginWindow(ProtocolManager protocolManager, Plugin plugin) {
	super(protocolManager, plugin);
	protocolManager.addPacketListener(
			new PacketAdapter(plugin, ListenerPriority.NORMAL, PacketType.Play.Client.UPDATE_SIGN) {
				@Override
				public void onPacketReceiving(PacketEvent event) {
					if (event.getPacketType() != PacketType.Play.Client.UPDATE_SIGN) {
						return;
					}
					if (AuthMeApi.getInstance().isAuthenticated(event.getPlayer())) {
						return;
					}
					PacketContainer packet = event.getPacket();
					String[] strings = packet.getStringArrays().read(0);
					if (strings[Variables.signLoginLine - 1].isEmpty()) {
						return;
					}
					boolean registered = AuthMeApi.getInstance().isRegistered(event.getPlayer().getName());
					String password = strings[Variables.signLoginLine - 1].substring(SignLoginWindow.this
							.getInfoFor(event.getPlayer(), Variables.signInfo.get(Variables.signLoginLine - 1))
							.length());
					if (!registered & !password.isEmpty()) {
						AuthMeApi.getInstance().registerPlayer(event.getPlayer().getName(), password);
					}
					Bukkit.getPluginCommand("login").execute(event.getPlayer(), "login", new String[] { password });
				}
			});
}
 
Example 30
Project: NeverLag   File: AntiAUWMod.java   View source code 5 votes vote down vote up
public static void register() {
	ProtocolUtils.get().addPacketListener(
		new PacketAdapter(NeverLag.getInstance(), PacketType.Play.Client.SET_CREATIVE_SLOT) {
			@Override
			public void onPacketReceiving(PacketEvent e) {
				onSetCreativeSlotPacket(e);
			}
		});
}
 
Example 31
Project: HCFCore   File: ProtocolLibHook.java   View source code 5 votes vote down vote up
/**
 * Hooks ProtocolLibrary into a {@link JavaPlugin}.
 *
 * @param kairos
 *            the plugin to hook into
 */
public static void hook(HCF kairos) {
    ProtocolManager protocolManager = ProtocolLibrary.getProtocolManager();
    protocolManager.addPacketListener(new PacketAdapter(kairos, ListenerPriority.NORMAL, PacketType.Play.Client.BLOCK_DIG) {
        @Override
        public void onPacketReceiving(PacketEvent event) {
            PacketContainer packet = event.getPacket();
            StructureModifier<Integer> modifier = packet.getIntegers();
            Player player = event.getPlayer();

            try {
                int status = modifier.read(4);
                // int face = modifier.read(3);
                if (status == STARTED_DIGGING || status == FINISHED_DIGGING) {
                    int x, y, z;
                    Location location = new Location(player.getWorld(), x = modifier.read(0), y = modifier.read(1), z = modifier.read(2));

                    // Validation
                    VisualBlock visualBlock = kairos.getVisualiseHandler().getVisualBlockAt(player, location);
                    if (visualBlock == null)
                        return;

                    event.setCancelled(true);
                    VisualBlockData data = visualBlock.getBlockData();
                    if (status == FINISHED_DIGGING) {
                        player.sendBlockChange(location, data.getBlockType(), data.getData());
                    } else if (status == STARTED_DIGGING) { // we check this because Blocks that broke pretty much straight away do not send a FINISHED for some weird reason.
                        EntityPlayer entityPlayer = ((CraftPlayer) player).getHandle();
                        if (player.getGameMode() == GameMode.CREATIVE
                                || net.minecraft.server.v1_7_R4.Block.getById(data.getItemTypeId()).getDamage(entityPlayer, entityPlayer.world, x, y, z) > 1.0F) {

                            player.sendBlockChange(location, data.getBlockType(), data.getData());
                        }
                    }
                }
            } catch (FieldAccessException ignored) {
            }
        }
    });
}
 
Example 32
Project: HCFCore   File: ProtocolLibHook.java   View source code 5 votes vote down vote up
/**
 * Hooks ProtocolLibrary into a {@link JavaPlugin}.
 *
 * @param kairos
 *            the plugin to hook into
 */
public static void hook(HCF kairos) {
    ProtocolManager protocolManager = ProtocolLibrary.getProtocolManager();
    protocolManager.addPacketListener(new PacketAdapter(kairos, ListenerPriority.NORMAL, PacketType.Play.Client.BLOCK_DIG) {
        @Override
        public void onPacketReceiving(PacketEvent event) {
            PacketContainer packet = event.getPacket();
            StructureModifier<Integer> modifier = packet.getIntegers();
            Player player = event.getPlayer();

            try {
                int status = modifier.read(4);
                // int face = modifier.read(3);
                if (status == STARTED_DIGGING || status == FINISHED_DIGGING) {
                    int x, y, z;
                    Location location = new Location(player.getWorld(), x = modifier.read(0), y = modifier.read(1), z = modifier.read(2));

                    // Validation
                    VisualBlock visualBlock = kairos.getVisualiseHandler().getVisualBlockAt(player, location);
                    if (visualBlock == null)
                        return;

                    event.setCancelled(true);
                    VisualBlockData data = visualBlock.getBlockData();
                    if (status == FINISHED_DIGGING) {
                        player.sendBlockChange(location, data.getBlockType(), data.getData());
                    } else if (status == STARTED_DIGGING) { // we check this because Blocks that broke pretty much straight away do not send a FINISHED for some weird reason.
                        EntityPlayer entityPlayer = ((CraftPlayer) player).getHandle();
                        if (player.getGameMode() == GameMode.CREATIVE
                                || net.minecraft.server.v1_7_R4.Block.getById(data.getItemTypeId()).getDamage(entityPlayer, entityPlayer.world, x, y, z) > 1.0F) {

                            player.sendBlockChange(location, data.getBlockType(), data.getData());
                        }
                    }
                }
            } catch (FieldAccessException ignored) {
            }
        }
    });
}
 
Example 33
Project: ZorahPractice   File: EntityHider.java   View source code 5 votes vote down vote up
/**
 * Construct the packet listener that will be used to intercept every entity-related packet.
 * @param plugin - the parent plugin.
 * @return The packet listener.
 */
private PacketAdapter constructProtocol(Plugin plugin) {
	return new PacketAdapter(plugin, ENTITY_PACKETS) {
		@Override
		public void onPacketSending(PacketEvent event) {
			int entityID = event.getPacket().getIntegers().read(0);

			// See if this packet should be cancelled
			if (!isVisible(event.getPlayer(), entityID)) {
				event.setCancelled(true);
			}
		}
	};
}
 
Example 34
Project: mirage   File: BlockDigAdapter.java   View source code 5 votes vote down vote up
@Override
public void onPacketReceiving(PacketEvent event) {
    StructureModifier<Integer> modifier = event.getPacket().getIntegers();

    try {
        int status = modifier.read(4);
        if (status == STARTED_DIGGING || status == FINISHED_DIGGING) {
            Player player = event.getPlayer();
            int x = modifier.read(0), y = modifier.read(1), z = modifier.read(2);
            Location location = new Location(player.getWorld(), x, y, z);
            
            Optional<FakeBlockSender> sender = FakeBlockSender.getFrom(player);
            if (!sender.isPresent()) {
                return;
            }
            
            FakeBlock visualBlock = sender.get().getBlockAt(location.toVector());
            if (visualBlock != null) {
                event.setCancelled(true);
                FakeBlock.Data data = visualBlock.getData();
                if (status == FINISHED_DIGGING || player.getGameMode() == GameMode.CREATIVE) {
                    player.sendBlockChange(location, data.getType(), data.getData());
                }
            }
        }
    } catch (FieldAccessException ex) {
        ex.printStackTrace();
    }
}
 
Example 35
Project: AntiLaby   File: ProtocolLibSupport.java   View source code 5 votes vote down vote up
@Override
public void onPacketReceiving(PacketEvent event) {
	final Object handle = event.getPacket().getHandle();
	final LanguageManager lm = LanguageManager.INSTANCE;
	final Player p = event.getPlayer();
	final String old = lm.getLanguageForPlayer(p) != null ? lm.getLanguageForPlayer(p).name().toLowerCase(
			Locale.ROOT) : "";
	try {
		final String lang = (String) handle.getClass().getMethod("a").invoke(handle);
		if(!old.equals(lang)) lm.setLanguageForPlayer(event.getPlayer(), lang);

	} catch(final ReflectiveOperationException e) {
		LOG.error("could not retrieve language, falling back to possibly inaccurate events: " + e.getMessage());
	}
}
 
Example 36
Project: RadarJammer   File: VisibilityManager.java   View source code 5 votes vote down vote up
public AntiBypassThread() {
	ProtocolLibrary.getProtocolManager().addPacketListener(new PacketAdapter(plugin, ListenerPriority.NORMAL,
			PacketType.Play.Client.LOOK, PacketType.Play.Client.POSITION_LOOK) {
		@Override
		public void onPacketReceiving(PacketEvent event) {
			PacketContainer packet = event.getPacket();
			float yaw = packet.getFloat().read(0);
			updatePlayer(event.getPlayer().getUniqueId(), yaw);
		}
	});
}
 
Example 37
Project: RadarJammer   File: PlayerListManager.java   View source code 5 votes vote down vote up
@Override
public void onPacketSending(PacketEvent event) {
	if(event.getPacketType() == PacketType.Play.Server.PLAYER_INFO) {
		PacketContainer packet = event.getPacket();
		PlayerInfoAction action = packet.getPlayerInfoAction().read(0);
		Player player = Bukkit.getPlayer(packet.getPlayerInfoDataLists().read(0).get(0).getProfile().getUUID());
		boolean online = player != null && player.isOnline();
		if(online && action == PlayerInfoAction.REMOVE_PLAYER) event.setCancelled(true);
	}
}
 
Example 38
Project: ChatItem   File: HandshakeListener.java   View source code 5 votes vote down vote up
@Override
public void onPacketReceiving(final PacketEvent e){
    PacketType.Protocol p = e.getPacket().getProtocols().read(0);
    if(p == PacketType.Protocol.STATUS || p == PacketType.Protocol.LEGACY){
        return;
    }
    final int version = e.getPacket().getIntegers().readSafely(0);
    //Delay the mapping to make sure the true address of the player was received when using bungeecord or other types of proxies
    Bukkit.getScheduler().scheduleSyncDelayedTask(ChatItem.getInstance(), () ->
            ProtocolVersion.getPlayerVersionMap().put(ProtocolVersion.stringifyAdress(e.getPlayer().getAddress()), version), 10L);

}
 
Example 39
Project: SkullExploitPatch   File: SkullExploitListener.java   View source code 5 votes vote down vote up
@Override
public void onPacketReceiving(PacketEvent event) {
    ItemStack stack = event.getPacket().getItemModifier().read(0);
    // Check for skull
    if (((SkullExploitPatch) getPlugin()).isExploit(stack)) {
        getPlugin().getLogger().warning("Player " + event.getPlayer().getName() + " just tried to use the skull exploit!");
    }
}
 
Example 40
Project: I18N   File: InterceptorTitle.java   View source code 5 votes vote down vote up
@Override
public void onPacketSending( PacketEvent event ) {
	final Player          player = event.getPlayer();
	final PacketContainer packet = event.getPacket();
	
	EnumWrappers.TitleAction action = packet.getTitleActions().read( 0 );
	if ( action == EnumWrappers.TitleAction.TITLE || action == EnumWrappers.TitleAction.SUBTITLE ) {
		String message     = this.restoreTextFromChatComponent( packet.getChatComponents().read( 0 ) );
		String translation = this.translateMessageIfAppropriate( this.i18n.getLocale( player.getUniqueId() ), message );
		
		if ( message != translation ) {
			packet.getChatComponents().write( 0, WrappedChatComponent.fromText( translation ) );
		}
	}
}