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 Project: SkinsRestorerX   Author: SkinsRestorer   File: GameProfileRequest.java    License: 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 #2
Source Project: Plan   Author: plan-player-analytics   File: VelocityPingCounter.java    License: 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 #3
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 #4
Source Project: ViaVersion   Author: ViaVersion   File: ElytraPatch.java    License: 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 #5
Source Project: ViaVersion   Author: ViaVersion   File: VelocityPlugin.java    License: 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 #6
Source Project: LuckPerms   Author: lucko   File: PluginMessageMessenger.java    License: 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 #7
Source Project: TAB   Author: NEZNAMY   File: PluginMessenger.java    License: 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 #8
Source Project: TAB   Author: NEZNAMY   File: Main.java    License: 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 #9
Source Project: AntiVPN   Author: egg82   File: VelocityBootstrap.java    License: 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 #10
Source Project: AntiVPN   Author: egg82   File: VelocityBootstrap.java    License: 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 #11
Source Project: ViaRewind   Author: ViaVersion   File: VelocityPlugin.java    License: 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 #12
Source Project: Plan   Author: plan-player-analytics   File: PlayerOnlineListener.java    License: 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 #13
Source Project: Plan   Author: plan-player-analytics   File: PlayerOnlineListener.java    License: 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 #14
Source Project: Plan   Author: plan-player-analytics   File: PlayerOnlineListener.java    License: 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 #15
Source Project: Plan   Author: plan-player-analytics   File: PlayerOnlineListener.java    License: 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 #16
Source Project: ViaVersion   Author: ViaVersion   File: VelocityServerHandler.java    License: 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 #17
Source Project: ViaVersion   Author: ViaVersion   File: UpdateListener.java    License: 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 #18
Source Project: LuckPerms   Author: lucko   File: VelocityConnectionListener.java    License: 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 #19
Source Project: LuckPerms   Author: lucko   File: MonitoringPermissionCheckListener.java    License: 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 #20
Source Project: LuckPerms   Author: lucko   File: LPVelocityBootstrap.java    License: 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 #21
Source Project: NuVotifier   Author: NuVotifier   File: VotifierPlugin.java    License: 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 #22
Source Project: Geyser   Author: GeyserMC   File: GeyserVelocityPlugin.java    License: MIT License 4 votes vote down vote up
@Subscribe
public void onInit(ProxyInitializeEvent event) {
    onEnable();
}
 
Example #23
Source Project: Geyser   Author: GeyserMC   File: GeyserVelocityPlugin.java    License: MIT License 4 votes vote down vote up
@Subscribe
public void onShutdown(ProxyShutdownEvent event) {
    onDisable();
}
 
Example #24
Source Project: TAB   Author: NEZNAMY   File: Main.java    License: Apache License 2.0 4 votes vote down vote up
@Subscribe
	public void onProxyInitialization(ProxyInitializeEvent event) {
		try {
			Class.forName("org.yaml.snakeyaml.Yaml");
			me.neznamy.tab.shared.ProtocolVersion.SERVER_VERSION = me.neznamy.tab.shared.ProtocolVersion.values()[1];
			Shared.mainClass = this;
			Shared.separatorType = "server";
			Shared.command = new TabCommand();
			server.getCommandManager().register("btab", new Command() {
				public void execute(CommandSource sender, String[] args) {
					if (Shared.disabled) {
						if (args.length == 1 && args[0].toLowerCase().equals("reload")) {
							if (sender.hasPermission("tab.reload")) {
								Shared.unload();
								Shared.load(false);
								if (Shared.disabled) {
									if (sender instanceof Player) {
										sender.sendMessage(TextComponent.of(Placeholders.color(Configs.reloadFailed.replace("%file%", Shared.brokenFile))));
									}
								} else {
									sender.sendMessage(TextComponent.of(Placeholders.color(Configs.reloaded)));
								}
							} else {
								sender.sendMessage(TextComponent.of(Placeholders.color(Configs.no_perm)));
							}
						} else {
							if (sender.hasPermission("tab.admin")) {
								sender.sendMessage(TextComponent.of(Placeholders.color("&m                                                                                ")));
								sender.sendMessage(TextComponent.of(Placeholders.color(" &c&lPlugin is disabled due to a broken configuration file (" + Shared.brokenFile + ")")));
								sender.sendMessage(TextComponent.of(Placeholders.color(" &8>> &3&l/tab reload")));
								sender.sendMessage(TextComponent.of(Placeholders.color("      - &7Reloads plugin and config")));
								sender.sendMessage(TextComponent.of(Placeholders.color("&m                                                                                ")));
							}
						}
					} else {
						Shared.command.execute(sender instanceof Player ? Shared.getPlayer(((Player)sender).getUniqueId()) : null, args);
					}
				}
/*				public List<String> suggest(CommandSource sender, String[] args) {
					List<String> sug = command.complete(sender instanceof Player ? Shared.getPlayer(((Player)sender).getUniqueId()) : null, args);
					if (sug == null) {
						sug = new ArrayList<String>();
						for (Player p : server.getAllPlayers()) {
							sug.add(p.getUsername());
						}
					}
					return sug;
				}*/
			});
			registerPackets();
			plm = new PluginMessenger(this);
			Shared.load(true);
		} catch (ClassNotFoundException e) {
			sendConsoleMessage("&c[TAB] The plugin requires Velocity 1.1.0 and up to work ! Get it at https://ci.velocitypowered.com/job/velocity-1.1.0/");
		}
	}
 
Example #25
Source Project: spark   Author: lucko   File: VelocitySparkPlugin.java    License: GNU General Public License v3.0 4 votes vote down vote up
@Subscribe(order = PostOrder.FIRST)
public void onEnable(ProxyInitializeEvent e) {
    this.platform = new SparkPlatform(this);
    this.platform.enable();
    this.proxy.getCommandManager().register(this, "sparkv", "sparkvelocity");
}
 
Example #26
Source Project: spark   Author: lucko   File: VelocitySparkPlugin.java    License: GNU General Public License v3.0 4 votes vote down vote up
@Subscribe(order = PostOrder.LAST)
public void onDisable(ProxyShutdownEvent e) {
    this.platform.disable();
}
 
Example #27
Source Project: Velocity   Author: VelocityPowered   File: VelocityEventManager.java    License: MIT License 4 votes vote down vote up
@Override
public boolean shouldRegister(@NonNull Object listener, @NonNull Method method) {
  return method.isAnnotationPresent(Subscribe.class);
}
 
Example #28
Source Project: Velocity   Author: VelocityPowered   File: VelocityEventManager.java    License: MIT License 4 votes vote down vote up
@Override
public int postOrder(@NonNull Object listener, @NonNull Method method) {
  return method.getAnnotation(Subscribe.class).order().ordinal();
}
 
Example #29
Source Project: SkinsRestorerX   Author: SkinsRestorer   File: SkinsRestorer.java    License: GNU General Public License v3.0 4 votes vote down vote up
@Subscribe
public void onProxyInitialize(ProxyInitializeEvent e) {
    logger.logAlways("Enabling SkinsRestorer v" + getVersion());
    console = this.proxy.getConsoleCommandSource();

    // Check for updates
    if (Config.UPDATER_ENABLED) {
        this.updateChecker = new UpdateCheckerGitHub(2124, this.getVersion(), this.getLogger(), "SkinsRestorerUpdater/Velocity");
        this.checkUpdate(true);

        if (Config.UPDATER_PERIODIC)
            this.getProxy().getScheduler().buildTask(this, this::checkUpdate).repeat(10, TimeUnit.MINUTES).delay(10, TimeUnit.MINUTES).schedule();
    }

    this.skinStorage = new SkinStorage();

    // Init config files
    Config.load(configPath, getClass().getClassLoader().getResourceAsStream("config.yml"));
    Locale.load(configPath);

    this.mojangAPI = new MojangAPI(this.logger);
    this.mineSkinAPI = new MineSkinAPI(this.logger);

    this.skinStorage.setMojangAPI(mojangAPI);
    // Init storage
    if (!this.initStorage())
        return;

    this.mojangAPI.setSkinStorage(this.skinStorage);
    this.mineSkinAPI.setSkinStorage(this.skinStorage);

    // Init listener
    proxy.getEventManager().register(this, new GameProfileRequest(this));

    // Init commands
    this.initCommands();

    // Init SkinApplier
    this.skinApplier = new SkinApplier(this);

    // Init API
    this.skinsRestorerVelocityAPI = new SkinsRestorerVelocityAPI(this, this.mojangAPI, this.skinStorage);

    logger.logAlways("Enabled SkinsRestorer v" + getVersion());
}
 
Example #30
Source Project: SkinsRestorerX   Author: SkinsRestorer   File: SkinsRestorer.java    License: GNU General Public License v3.0 4 votes vote down vote up
@Subscribe
public void onShutDown(ProxyShutdownEvent ev) {
    this.logger.logAlways("Disabling SkinsRestorer v" + getVersion());
    this.logger.logAlways("Disabled SkinsRestorer v" + getVersion());
}