com.velocitypowered.api.proxy.Player Java Examples

The following examples show how to use com.velocitypowered.api.proxy.Player. 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: 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 #2
Source File: OnlineForwardPluginMessagingForwardingSource.java    From NuVotifier with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void forward(Vote v) {
    Optional<Player> p = plugin.getServer().getPlayer(v.getUsername());
    Optional<ServerConnection> sc = p.flatMap(Player::getCurrentServer);
    if (sc.isPresent() &&
            serverFilter.isAllowed(sc.get().getServerInfo().getName())
    ) {
        if (forwardSpecific(new VelocityBackendServer(plugin.getServer(), sc.get().getServer()), v)) {
            if (plugin.isDebug()) {
                plugin.getPluginLogger().info("Successfully forwarded vote " + v + " to server " + sc.get().getServerInfo().getName());
            }
            return;
        }
    }

    Optional<RegisteredServer> fs = plugin.getServer().getServer(fallbackServer);
    // nowhere to fall back to, yet still not online. lets save this vote yet!
    if (!fs.isPresent())
        attemptToAddToPlayerCache(v, v.getUsername());
    else if (!forwardSpecific(new VelocityBackendServer(plugin.getServer(), fs.get()), v))
        attemptToAddToCache(v, fallbackServer);
}
 
Example #3
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 #4
Source File: SkinCommand.java    From SkinsRestorerX with GNU General Public License v3.0 6 votes vote down vote up
@Subcommand("update") @CommandPermission("%skinUpdateOther")
@CommandCompletion("@players")
@Description("%helpSkinUpdateOther")
public void onSkinUpdateOther(CommandSource source, OnlinePlayer target) {
    plugin.getService().execute(() -> {
        Player p = target.getPlayer();
        String skin = plugin.getSkinStorage().getPlayerSkin(p.getUsername());

        // User has no custom skin set, get the default skin name / his skin
        if (skin == null)
            skin = plugin.getSkinStorage().getDefaultSkinNameIfEnabled(p.getUsername(), true);

        if (!plugin.getSkinStorage().forceUpdateSkinData(skin)) {
            source.sendMessage(plugin.deserialize(Locale.ERROR_UPDATING_SKIN));
            return;
        }

        if (this.setSkin(source, p, skin, false)) {
            if (!getSenderName(source).equals(target.getPlayer().getUsername()))
                source.sendMessage(plugin.deserialize(Locale.SUCCESS_UPDATING_SKIN_OTHER.replace("%player", target.getPlayer().getUsername())));
            else
                source.sendMessage(plugin.deserialize(Locale.SUCCESS_UPDATING_SKIN));
        }
    });
}
 
Example #5
Source File: SkinCommand.java    From SkinsRestorerX with GNU General Public License v3.0 6 votes vote down vote up
@Subcommand("clear") @CommandPermission("%skinClearOther")
@CommandCompletion("@players")
@Description("%helpSkinClearOther")
public void onSkinClearOther(CommandSource source, OnlinePlayer target) {
    plugin.getService().execute(() -> {
        Player p = target.getPlayer();
        String skin = plugin.getSkinStorage().getDefaultSkinNameIfEnabled(p.getUsername(), true);

        // remove users custom skin and set default skin / his skin
        plugin.getSkinStorage().removePlayerSkin(p.getUsername());
        if (this.setSkin(source, p, skin, false)) {
            if (!getSenderName(source).equals(target.getPlayer().getUsername()))
                source.sendMessage(plugin.deserialize(Locale.SKIN_CLEAR_ISSUER.replace("%player", target.getPlayer().getUsername())));
            else
                source.sendMessage(plugin.deserialize(Locale.SKIN_CLEAR_SUCCESS));
        }
    });
}
 
Example #6
Source File: GlistCommand.java    From Velocity with MIT License 6 votes vote down vote up
private void sendServerPlayers(CommandSource target, RegisteredServer server, boolean fromAll) {
  List<Player> onServer = ImmutableList.copyOf(server.getPlayersConnected());
  if (onServer.isEmpty() && fromAll) {
    return;
  }

  TextComponent.Builder builder = TextComponent.builder()
      .append(TextComponent.of("[" + server.getServerInfo().getName() + "] ",
          TextColor.DARK_AQUA))
      .append("(" + onServer.size() + ")", TextColor.GRAY)
      .append(": ")
      .resetStyle();

  for (int i = 0; i < onServer.size(); i++) {
    Player player = onServer.get(i);
    builder.append(player.getUsername());

    if (i + 1 < onServer.size()) {
      builder.append(", ");
    }
  }

  target.sendMessage(builder.build());
}
 
Example #7
Source File: LPVelocityBootstrap.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
public Collection<String> getPlayerList() {
    Collection<Player> players = this.proxy.getAllPlayers();
    List<String> list = new ArrayList<>(players.size());
    for (Player player : players) {
        list.add(player.getUsername());
    }
    return list;
}
 
Example #8
Source File: TabPlayer.java    From TAB with Apache License 2.0 5 votes vote down vote up
public TabPlayer(Player p, String server) {
	player = p;
	world = server;
	channel = ((ConnectedPlayer)player).getConnection().getChannel();
	tablistId = UUID.nameUUIDFromBytes(("OfflinePlayer:" + p.getUsername()).getBytes(Charsets.UTF_8));
	uniqueId = p.getUniqueId();
	name = p.getUsername();
	version = ProtocolVersion.fromNumber(player.getProtocolVersion().getProtocol());
	init();
}
 
Example #9
Source File: VelocityCommandSender.java    From spark with GNU General Public License v3.0 5 votes vote down vote up
@Override
public UUID getUniqueId() {
    if (super.delegate instanceof Player) {
        return ((Player) super.delegate).getUniqueId();
    }
    return null;
}
 
Example #10
Source File: PlayerEvents.java    From AntiVPN with MIT License 5 votes vote down vote up
private void tryRunCommands(List<String> commands, Player player, String ip) {
    for (String command : commands) {
        command = command.replace("%player%", player.getUsername()).replace("%uuid%", player.getUniqueId().toString()).replace("%ip%", ip);
        if (command.charAt(0) == '/') {
            command = command.substring(1);
        }

        proxy.getCommandManager().execute(proxy.getConsoleCommandSource(), command);
    }
}
 
Example #11
Source File: PlayerAnalyticsHook.java    From AntiVPN with MIT License 5 votes vote down vote up
private String getIp(Player player) {
    InetSocketAddress address = player.getRemoteAddress();
    if (address == null) {
        return null;
    }
    InetAddress host = address.getAddress();
    if (host == null) {
        return null;
    }
    return host.getHostAddress();
}
 
Example #12
Source File: PlayerAnalyticsHook.java    From AntiVPN with MIT License 5 votes vote down vote up
@NumberProvider(
        text = "MCLeaks Users",
        description = "Number of online MCLeaks users.",
        priority = 1,
        iconName = "users",
        iconFamily = Family.SOLID,
        iconColor = Color.NONE,
        format = FormatType.NONE
)
public long getMCLeaks() {
    Optional<CachedConfigValues> cachedConfig = ConfigUtil.getCachedConfig();
    if (!cachedConfig.isPresent()) {
        logger.error("Cached config could not be fetched.");
        return 0L;
    }

    long retVal = 0L;
    for (Player p : proxy.getAllPlayers()) {
        try {
            if (api.isMCLeaks(p.getUniqueId())) {
                retVal++;
            }
        } catch (APIException ex) {
            if (cachedConfig.get().getDebug()) {
                logger.error("[Hard: " + ex.isHard() + "] " + ex.getMessage(), ex);
            } else {
                logger.error("[Hard: " + ex.isHard() + "] " + ex.getMessage());
            }
        }
    }
    return retVal;
}
 
Example #13
Source File: VelocityPlayerInfo.java    From AntiVPN with MIT License 5 votes vote down vote up
private static String nameExpensive(UUID uuid, ProxyServer proxy) throws IOException {
    // Currently-online lookup
    Optional<Player> player = proxy.getPlayer(uuid);
    if (player.isPresent()) {
        nameCache.put(player.get().getUsername(), uuid);
        return player.get().getUsername();
    }

    // Network lookup
    HttpURLConnection conn = JSONWebUtil.getConnection(new URL("https://api.mojang.com/user/profiles/" + uuid.toString().replace("-", "") + "/names"), "GET", 5000, "egg82/PlayerInfo", headers);;
    int status = conn.getResponseCode();

    if (status == 204) {
        // No data exists
        return null;
    } else if (status == 200) {
        try {
            JSONArray json = getJSONArray(conn, status);
            JSONObject last = (JSONObject) json.get(json.size() - 1);
            String name = (String) last.get("name");
            nameCache.put(name, uuid);
            return name;
        } catch (ParseException | ClassCastException ex) {
            throw new IOException(ex.getMessage(), ex);
        }
    }

    throw new IOException("Could not load player data from Mojang (rate-limited?)");
}
 
Example #14
Source File: KickedFromServerEvent.java    From Velocity with MIT License 5 votes vote down vote up
/**
 * Creates a {@code KickedFromServerEvent} instance.
 * @param player the player affected
 * @param server the server the player disconnected from
 * @param originalReason the reason for being kicked, optional
 * @param duringServerConnect whether or not the player was kicked during the connection process
 * @param fancyReason a fancy reason for being disconnected, used for the initial result
 */
public KickedFromServerEvent(Player player, RegisteredServer server,
    @Nullable Component originalReason, boolean duringServerConnect, Component fancyReason) {
  this.player = Preconditions.checkNotNull(player, "player");
  this.server = Preconditions.checkNotNull(server, "server");
  this.originalReason = originalReason;
  this.duringServerConnect = duringServerConnect;
  this.result = new Notify(fancyReason);
}
 
Example #15
Source File: VelocityCommandSender.java    From spark with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String getName() {
    if (super.delegate instanceof Player) {
        return ((Player) super.delegate).getUsername();
    } else if (super.delegate instanceof ConsoleCommandSource) {
        return "Console";
    } else {
        return "unknown:" + super.delegate.getClass().getSimpleName();
    }
}
 
Example #16
Source File: VelocityContextManager.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
public QueryOptionsSupplier getCacheFor(Player subject) {
    if (subject == null) {
        throw new NullPointerException("subject");
    }

    return this.subjectCaches.get(subject);
}
 
Example #17
Source File: KickedFromServerEvent.java    From Velocity with MIT License 5 votes vote down vote up
/**
 * Creates a {@code KickedFromServerEvent} instance.
 * @param player the player affected
 * @param server the server the player disconnected from
 * @param originalReason the reason for being kicked, optional
 * @param duringServerConnect whether or not the player was kicked during the connection process
 * @param result the initial result
 */
public KickedFromServerEvent(Player player,
    RegisteredServer server,
    @Nullable Component originalReason, boolean duringServerConnect,
    ServerKickResult result) {
  this.player = Preconditions.checkNotNull(player, "player");
  this.server = Preconditions.checkNotNull(server, "server");
  this.originalReason = originalReason;
  this.duringServerConnect = duringServerConnect;
  this.result = Preconditions.checkNotNull(result, "result");
}
 
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: VelocitySenderFactory.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
protected String getName(CommandSource source) {
    if (source instanceof Player) {
        return ((Player) source).getUsername();
    }
    return Sender.CONSOLE_NAME;
}
 
Example #20
Source File: VelocityPlugin.java    From ServerListPlus with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Iterator<String> getRandomPlayers(String location) {
    Optional<RegisteredServer> server = proxy.getServer(location);
    if (!server.isPresent()) {
        return null;
    }

    ArrayList<String> result = new ArrayList<>();
    for (Player player : server.get().getPlayersConnected()) {
        result.add(player.getUsername());
    }

    return Randoms.shuffle(result).iterator();
}
 
Example #21
Source File: VelocityBossBar.java    From Velocity with MIT License 5 votes vote down vote up
@Override
public void addPlayers(Iterable<Player> players) {
  checkNotNull(players, "players");
  for (Player player : players) {
    addPlayer(player);
  }
}
 
Example #22
Source File: VelocityBossBar.java    From Velocity with MIT License 5 votes vote down vote up
@Override
public void removePlayers(Iterable<Player> players) {
  checkNotNull(players, "players");
  for (Player player : players) {
    removePlayer(player);
  }
}
 
Example #23
Source File: LPVelocityBootstrap.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
public Collection<UUID> getOnlinePlayers() {
    Collection<Player> players = this.proxy.getAllPlayers();
    List<UUID> list = new ArrayList<>(players.size());
    for (Player player : players) {
        list.add(player.getUniqueId());
    }
    return list;
}
 
Example #24
Source File: VelocityBossBar.java    From Velocity with MIT License 5 votes vote down vote up
private void sendToAffected(MinecraftPacket packet) {
  for (Player player : players) {
    if (player.isActive() && player.getProtocolVersion().getProtocol()
        >= ProtocolVersion.MINECRAFT_1_9.getProtocol()) {
      sendPacket(player, packet);
    }
  }
}
 
Example #25
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 #26
Source File: PlayerOnlineListener.java    From Plan with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void actOnLogin(PostLoginEvent event) {
    Player player = event.getPlayer();
    UUID playerUUID = player.getUniqueId();
    String playerName = player.getUsername();
    InetAddress address = player.getRemoteAddress().getAddress();
    long time = System.currentTimeMillis();

    Session session = new Session(playerUUID, serverInfo.getServerUUID(), time, null, null);
    session.putRawData(SessionKeys.NAME, playerName);
    session.putRawData(SessionKeys.SERVER_NAME, "Proxy Server");
    sessionCache.cacheSession(playerUUID, session);

    Database database = dbSystem.getDatabase();

    boolean gatheringGeolocations = config.isTrue(DataGatheringSettings.GEOLOCATIONS);
    if (gatheringGeolocations) {
        database.executeTransaction(
                new GeoInfoStoreTransaction(playerUUID, address, time, geolocationCache::getCountry)
        );
    }

    database.executeTransaction(new PlayerRegisterTransaction(playerUUID, () -> time, playerName));
    processing.submitNonCritical(() -> extensionService.updatePlayerValues(playerUUID, playerName, CallEvents.PLAYER_JOIN));
    if (config.isTrue(ExportSettings.EXPORT_ON_ONLINE_STATUS_CHANGE)) {
        processing.submitNonCritical(() -> exporter.exportPlayerPage(playerUUID, playerName));
    }

    UUID serverUUID = serverInfo.getServerUUID();
    JSONCache.invalidateMatching(DataID.SERVER_OVERVIEW);
    JSONCache.invalidate(DataID.GRAPH_ONLINE, serverUUID);
    JSONCache.invalidate(DataID.SERVERS);
    JSONCache.invalidate(DataID.SESSIONS);
}
 
Example #27
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 #28
Source File: VelocityCommandSender.java    From ServerListPlus with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String getName() {
    if (source instanceof Player) {
        return ((Player) source).getUsername();
    } else if (source == this.proxy.getConsoleCommandSource()) {
        return "Console";
    } else {
        return "Unknown";
    }
}
 
Example #29
Source File: VelocityPingCounter.java    From Plan with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void run() {
    long time = System.currentTimeMillis();
    Iterator<Map.Entry<UUID, List<DateObj<Integer>>>> iterator = playerHistory.entrySet().iterator();

    while (iterator.hasNext()) {
        Map.Entry<UUID, List<DateObj<Integer>>> entry = iterator.next();
        UUID uuid = entry.getKey();
        List<DateObj<Integer>> history = entry.getValue();
        Player player = plugin.getProxy().getPlayer(uuid).orElse(null);
        if (player != null) {
            int ping = getPing(player);
            if (ping < -1 || ping > TimeUnit.SECONDS.toMillis(8L)) {
                // Don't accept bad values
                continue;
            }
            history.add(new DateObj<>(time, ping));
            if (history.size() >= 30) {
                dbSystem.getDatabase().executeTransaction(
                        new PingStoreTransaction(uuid, serverInfo.getServerUUID(), new ArrayList<>(history))
                );
                history.clear();
            }
        } else {
            iterator.remove();
        }
    }
}
 
Example #30
Source File: VelocityPingCounterTest.java    From Plan with GNU Lesser General Public License v3.0 5 votes vote down vote up
@BeforeEach
void setUp() {
    PlanVelocityMocker mocker = PlanVelocityMocker.setUp()
            .withProxy();
    plugin = mocker.getPlanMock();

    player = Mockito.mock(Player.class);
    when(player.getPing()).thenReturn(5L);
    when(player.getUniqueId()).thenReturn(TestConstants.PLAYER_ONE_UUID);

    ProxyServer proxy = plugin.getProxy();
    when(proxy.getPlayer(TestConstants.PLAYER_ONE_UUID)).thenReturn(Optional.empty());
}