com.velocitypowered.api.event.Subscribe Java Examples

The following examples show how to use com.velocitypowered.api.event.Subscribe. 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 File: PluginMessageMessenger.java    From LuckPerms with MIT License 6 votes vote down vote up
@Subscribe
public void onPluginMessage(PluginMessageEvent e) {
    // compare the underlying text representation of the channel
    // the namespaced representation is used by legacy servers too, so we
    // are able to support both. :)
    if (!e.getIdentifier().getId().equals(CHANNEL.getId())) {
        return;
    }

    e.setResult(ForwardResult.handled());

    if (e.getSource() instanceof Player) {
        return;
    }

    ByteArrayDataInput in = e.dataAsDataStream();
    String msg = in.readUTF();

    if (this.consumer.consumeIncomingMessageAsString(msg)) {
        // Forward to other servers
        this.plugin.getBootstrap().getScheduler().executeAsync(() -> dispatchMessage(e.getData()));
    }
}
 
Example #2
Source File: VelocityPlugin.java    From ViaVersion with MIT License 6 votes vote down vote up
@Subscribe
public void onProxyInit(ProxyInitializeEvent e) {
    PROXY = proxy;
    VelocityCommandHandler commandHandler = new VelocityCommandHandler();
    PROXY.getCommandManager().register(commandHandler, "viaver", "vvvelocity", "viaversion");
    api = new VelocityViaAPI();
    conf = new VelocityViaConfig(configDir.toFile());
    logger = new LoggerWrapper(loggerslf4j);
    connectionManager = new ViaConnectionManager();
    Via.init(ViaManager.builder()
            .platform(this)
            .commandHandler(commandHandler)
            .loader(new VelocityViaLoader())
            .injector(new VelocityViaInjector()).build());

    if (proxy.getPluginManager().getPlugin("ViaBackwards").isPresent()) {
        MappingDataLoader.enableMappingsCache();
    }
}
 
Example #3
Source File: ElytraPatch.java    From ViaVersion with MIT License 6 votes vote down vote up
@Subscribe(order = PostOrder.LAST)
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 #4
Source File: VelocityServerHandler.java    From ViaVersion with 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 #5
Source File: VelocityPingCounter.java    From Plan with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Subscribe
public void onPlayerJoin(ServerConnectedEvent joinEvent) {
    Player player = joinEvent.getPlayer();
    Long pingDelay = config.get(TimeSettings.PING_PLAYER_LOGIN_DELAY);
    if (pingDelay >= TimeUnit.HOURS.toMillis(2L)) {
        return;
    }
    runnableFactory.create("Add Player to Ping list", new AbsRunnable() {
        @Override
        public void run() {
            if (player.isActive()) {
                addPlayer(player);
            }
        }
    }).runTaskLater(TimeAmount.toTicks(pingDelay, TimeUnit.MILLISECONDS));
}
 
Example #6
Source File: GameProfileRequest.java    From SkinsRestorerX with GNU General Public License v3.0 6 votes vote down vote up
@Subscribe
public void onGameProfileRequest(GameProfileRequestEvent e) {
    String nick = e.getUsername();

    if (Config.DISABLE_ONJOIN_SKINS) {
        return;
    }

    if (e.isOnlineMode()) {
        return;
    }

    // Don't change skin if player has no custom skin-name set and his username is invalid
    if (plugin.getSkinStorage().getPlayerSkin(nick) == null && !C.validUsername(nick)) {
        System.out.println("[SkinsRestorer] Not applying skin to " + nick + " (invalid username).");
        return;
    }

    String skin = plugin.getSkinStorage().getDefaultSkinNameIfEnabled(nick);
    e.setGameProfile(plugin.getSkinApplier().updateProfileSkin(e.getGameProfile(), skin));
}
 
Example #7
Source File: PlayerOnlineListener.java    From Plan with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Subscribe(order = PostOrder.LAST)
public void onLogout(DisconnectEvent event) {
    try {
        actOnLogout(event);
    } catch (Exception e) {
        errorLogger.log(L.ERROR, e, ErrorContext.builder().related(event).build());
    }
}
 
Example #8
Source File: VelocityConnectionListener.java    From LuckPerms with MIT License 5 votes vote down vote up
@Subscribe
public void onPlayerPostLogin(LoginEvent e) {
    final Player player = e.getPlayer();
    final User user = this.plugin.getUserManager().getIfLoaded(e.getPlayer().getUniqueId());

    if (this.plugin.getConfiguration().get(ConfigKeys.DEBUG_LOGINS)) {
        this.plugin.getLogger().info("Processing post-login for " + player.getUniqueId() + " - " + player.getUsername());
    }

    if (!e.getResult().isAllowed()) {
        return;
    }

    if (user == null) {
        if (!getUniqueConnections().contains(player.getUniqueId())) {
            this.plugin.getLogger().warn("User " + player.getUniqueId() + " - " + player.getUsername() +
                    " doesn't have data pre-loaded, they have never been processed during pre-login in this session.");
        } else {
            this.plugin.getLogger().warn("User " + player.getUniqueId() + " - " + player.getUsername() +
                    " doesn't currently have data pre-loaded, but they have been processed before in this session.");
        }

        if (this.plugin.getConfiguration().get(ConfigKeys.CANCEL_FAILED_LOGINS)) {
            // disconnect the user
            e.setResult(ResultedEvent.ComponentResult.denied(Message.LOADING_STATE_ERROR.asComponent(this.plugin.getLocaleManager())));
        } else {
            // just send a message
            this.plugin.getBootstrap().getScheduler().asyncLater(() -> {
                if (!player.isActive()) {
                    return;
                }

                this.plugin.getSenderFactory().wrap(player).sendMessage(Message.LOADING_STATE_ERROR.asComponent(this.plugin.getLocaleManager()));
            }, 1, TimeUnit.SECONDS);
        }
    }
}
 
Example #9
Source File: MonitoringPermissionCheckListener.java    From LuckPerms with MIT License 5 votes vote down vote up
@Subscribe(order = PostOrder.LAST)
public void onOtherPermissionSetup(PermissionsSetupEvent e) {
    // players are handled separately
    if (e.getSubject() instanceof Player) {
        return;
    }

    e.setProvider(new MonitoredPermissionProvider(e.getProvider()));
}
 
Example #10
Source File: LPVelocityBootstrap.java    From LuckPerms with MIT License 5 votes vote down vote up
@Subscribe(order = PostOrder.FIRST)
public void onEnable(ProxyInitializeEvent e) {
    this.startTime = Instant.now();
    try {
        this.plugin.load();
    } finally {
        this.loadLatch.countDown();
    }

    try {
        this.plugin.enable();
    } finally {
        this.enableLatch.countDown();
    }
}
 
Example #11
Source File: UpdateListener.java    From ViaVersion with MIT License 5 votes vote down vote up
@Subscribe
public void onJoin(PostLoginEvent e) {
    if (e.getPlayer().hasPermission("viaversion.update")
            && Via.getConfig().isCheckForUpdates()) {
        UpdateUtil.sendUpdateMessage(e.getPlayer().getUniqueId());
    }
}
 
Example #12
Source File: VelocityServerHandler.java    From ViaVersion with MIT License 5 votes vote down vote up
@Subscribe(order = PostOrder.LATE)
public void connectedEvent(ServerConnectedEvent e) {
    UserConnection user = Via.getManager().getConnection(e.getPlayer().getUniqueId());
    CompletableFuture.runAsync(() -> {
        try {
            checkServerChange(e, Via.getManager().getConnection(e.getPlayer().getUniqueId()));
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }, user.getChannel().eventLoop()).join();
}
 
Example #13
Source File: PlayerOnlineListener.java    From Plan with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Subscribe(order = PostOrder.LAST)
public void onServerSwitch(ServerConnectedEvent event) {
    try {
        actOnServerSwitch(event);
    } catch (Exception e) {
        errorLogger.log(L.ERROR, e, ErrorContext.builder().related(event).build());
    }
}
 
Example #14
Source File: PlayerOnlineListener.java    From Plan with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Subscribe(order = PostOrder.NORMAL)
public void beforeLogout(DisconnectEvent event) {
    Player player = event.getPlayer();
    UUID playerUUID = player.getUniqueId();
    String playerName = player.getUsername();
    processing.submitNonCritical(() -> extensionService.updatePlayerValues(playerUUID, playerName, CallEvents.PLAYER_LEAVE));
}
 
Example #15
Source File: PlayerOnlineListener.java    From Plan with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Subscribe(order = PostOrder.LAST)
public void onPostLogin(PostLoginEvent event) {
    try {
        actOnLogin(event);
    } catch (Exception e) {
        errorLogger.log(L.ERROR, e, ErrorContext.builder().related(event).build());
    }
}
 
Example #16
Source File: VelocityPlugin.java    From ViaRewind with MIT License 5 votes vote down vote up
@Subscribe(order = PostOrder.LATE)
public void onProxyStart(ProxyInitializeEvent e) {
	// Setup Logger
	this.logger = new LoggerWrapper(loggerSlf4j);
	// Init!
	ViaRewindConfigImpl conf = new ViaRewindConfigImpl(configDir.resolve("config.yml").toFile());
	conf.reloadConfig();
	this.init(conf);
}
 
Example #17
Source File: VotifierPlugin.java    From NuVotifier with GNU General Public License v3.0 5 votes vote down vote up
@Subscribe
public void onServerStart(ProxyInitializeEvent event) {
    this.scheduler = new VelocityScheduler(server, this);
    this.loggingAdapter = new SLF4JLogger(logger);

    this.getServer().getCommandManager().register(new NVReloadCmd(this), "pnvreload");
    this.getServer().getCommandManager().register(new TestVoteCmd(this), "ptestvote");

    if (!loadAndBind())
        gracefulExit();
}
 
Example #18
Source File: PluginMessenger.java    From TAB with Apache License 2.0 5 votes vote down vote up
@Subscribe
public void on(PluginMessageEvent event){
	if (!event.getIdentifier().getId().equalsIgnoreCase(Shared.CHANNEL_NAME)) return;
	ByteArrayDataInput in = ByteStreams.newDataInput(event.getData());
	String subChannel = in.readUTF();
	if (event.getTarget() instanceof Player && subChannel.equalsIgnoreCase("Placeholder")){
		event.setResult(ForwardResult.handled());
		ITabPlayer receiver = Shared.getPlayer(((Player) event.getTarget()).getUniqueId());
		if (receiver == null) return;
		String placeholder = in.readUTF();
		String output = in.readUTF();
		long cpu = in.readLong();
		PlayerPlaceholder pl = (PlayerPlaceholder) Placeholders.getPlaceholder(placeholder); //all bridge placeholders are marked as player
		if (pl != null) {
			pl.lastValue.put(receiver.getName(), output);
			pl.lastValue.put("null", output);
			Set<Refreshable> update = PlaceholderManager.getPlaceholderUsage(pl.getIdentifier());
			Shared.featureCpu.runTask("refreshing", new Runnable() {

				@Override
				public void run() {
					for (Refreshable r : update) {
						long startTime = System.nanoTime();
						r.refresh(receiver, false);
						Shared.featureCpu.addTime(r.getRefreshCPU(), System.nanoTime()-startTime);
					}
				}
			});
			Shared.bukkitBridgePlaceholderCpu.addTime(pl.getIdentifier(), cpu);
		} else {
			Shared.debug("Received output for unknown placeholder " + placeholder);
		}
	}
}
 
Example #19
Source File: Main.java    From TAB with Apache License 2.0 5 votes vote down vote up
@Subscribe
public void a(DisconnectEvent e){
	if (Shared.disabled) return;
	ITabPlayer disconnectedPlayer = Shared.getPlayer(e.getPlayer().getUniqueId());
	if (disconnectedPlayer == null) return; //player connected to bungeecord successfully, but not to the bukkit server anymore ? idk the check is needed
	Shared.data.remove(e.getPlayer().getUniqueId());
	Shared.quitListeners.forEach(f -> f.onQuit(disconnectedPlayer));
}
 
Example #20
Source File: VelocityBootstrap.java    From AntiVPN with MIT License 5 votes vote down vote up
@Subscribe(order = PostOrder.LATE)
public void onDisable(ProxyShutdownEvent event) {
    try {
        concreteClass.getMethod("onDisable").invoke(concrete);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) {
        logger.error(ex.getMessage(), ex);
        throw new RuntimeException("Could not invoke onDisable.");
    }
}
 
Example #21
Source File: VelocityBootstrap.java    From AntiVPN with MIT License 5 votes vote down vote up
@Subscribe(order = PostOrder.EARLY)
public void onEnable(ProxyInitializeEvent event) {
    try {
        concreteClass.getMethod("onEnable").invoke(concrete);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) {
        logger.error(ex.getMessage(), ex);
        throw new RuntimeException("Could not invoke onEnable.");
    }

    if (ExternalAPI.getInstance() == null) {
        ExternalAPI.setInstance(proxiedClassLoader);
    }
}
 
Example #22
Source File: GeyserVelocityPlugin.java    From Geyser with MIT License 4 votes vote down vote up
@Subscribe
public void onInit(ProxyInitializeEvent event) {
    onEnable();
}
 
Example #23
Source File: PluginMessagingForwardingSource.java    From NuVotifier with GNU General Public License v3.0 4 votes vote down vote up
@Subscribe
public void onServerConnected(final ServerConnectedEvent e) { //Attempt to resend any votes that were previously cached.
    onServerConnect(new VelocityBackendServer(plugin.getServer(), e.getServer()));
}
 
Example #24
Source File: VelocityConnectionListener.java    From LuckPerms with MIT License 4 votes vote down vote up
@Subscribe(order = PostOrder.LAST)
public void onPlayerQuit(DisconnectEvent e) {
    handleDisconnect(e.getPlayer().getUniqueId());
}
 
Example #25
Source File: VelocityPlugin.java    From ServerListPlus with GNU General Public License v3.0 4 votes vote down vote up
@Subscribe
public void onPlayerLogin(LoginEvent event) {
    handleConnection(event.getPlayer());
}
 
Example #26
Source File: LPVelocityBootstrap.java    From LuckPerms with MIT License 4 votes vote down vote up
@Subscribe(order = PostOrder.LAST)
public void onDisable(ProxyShutdownEvent e) {
    this.plugin.disable();
}
 
Example #27
Source File: VelocityPlugin.java    From ServerListPlus with GNU General Public License v3.0 4 votes vote down vote up
@Subscribe
public void shutdown(ProxyShutdownEvent event) {
    try {
        core.stop();
    } catch (ServerListPlusException ignored) {}
}
 
Example #28
Source File: VotifierPlugin.java    From NuVotifier with GNU General Public License v3.0 4 votes vote down vote up
@Subscribe
public void onProxyReload(ProxyReloadEvent event) {
    this.reload();
}
 
Example #29
Source File: VotifierPlugin.java    From NuVotifier with GNU General Public License v3.0 4 votes vote down vote up
@Subscribe
public void onServerStop(ProxyShutdownEvent event) {
    this.halt();
    logger.info("Votifier disabled.");
}
 
Example #30
Source File: VelocityPlugin.java    From ViaBackwards with MIT License 4 votes vote down vote up
@Subscribe(order = PostOrder.LATE)
public void onProxyStart(ProxyInitializeEvent e) {
    // Setup Logger
    this.logger = new LoggerWrapper(loggerSlf4j);
    Via.getManager().addEnableListener(() -> this.init(configPath.resolve("config.yml").toFile()));
}