Search in sources :

Example 1 with ServerConnection

use of com.velocitypowered.api.proxy.ServerConnection in project LimboAuth-SocialAddon by Elytrium.

the class Addon method onProxyInitialization.

@Subscribe(order = PostOrder.FIRST)
public void onProxyInitialization(ProxyInitializeEvent event) {
    Settings.IMP.reload(new File(this.dataDirectory.toFile().getAbsoluteFile(), "config.yml"));
    this.metricsFactory.make(this, 14770);
    this.socialManager.init();
    this.keyboard = List.of(List.of(new AbstractSocial.ButtonItem(INFO_BTN, Settings.IMP.MAIN.STRINGS.INFO_BTN, AbstractSocial.ButtonItem.Color.PRIMARY)), List.of(new AbstractSocial.ButtonItem(BLOCK_BTN, Settings.IMP.MAIN.STRINGS.BLOCK_TOGGLE_BTN, AbstractSocial.ButtonItem.Color.SECONDARY), new AbstractSocial.ButtonItem(TOTP_BTN, Settings.IMP.MAIN.STRINGS.TOGGLE_2FA_BTN, AbstractSocial.ButtonItem.Color.SECONDARY)), List.of(new AbstractSocial.ButtonItem(NOTIFY_BTN, Settings.IMP.MAIN.STRINGS.TOGGLE_NOTIFICATION_BTN, AbstractSocial.ButtonItem.Color.SECONDARY)), List.of(new AbstractSocial.ButtonItem(KICK_BTN, Settings.IMP.MAIN.STRINGS.KICK_BTN, AbstractSocial.ButtonItem.Color.RED), new AbstractSocial.ButtonItem(RESTORE_BTN, Settings.IMP.MAIN.STRINGS.RESTORE_BTN, AbstractSocial.ButtonItem.Color.RED), new AbstractSocial.ButtonItem(UNLINK_BTN, Settings.IMP.MAIN.STRINGS.UNLINK_BTN, AbstractSocial.ButtonItem.Color.RED)));
    this.socialManager.addMessageEvent((dbField, id, message) -> {
        if (message.startsWith(Settings.IMP.MAIN.SOCIAL_LINK_CMD)) {
            int desiredLength = Settings.IMP.MAIN.SOCIAL_LINK_CMD.length() + 1;
            if (message.length() <= desiredLength) {
                return;
            }
            try {
                if (this.dao.queryForEq(dbField, id).size() != 0) {
                    this.socialManager.broadcastMessage(dbField, id, Settings.IMP.MAIN.STRINGS.LINK_ALREADY);
                    return;
                }
            } catch (SQLException e) {
                e.printStackTrace();
                return;
            }
            String account = message.substring(desiredLength).toLowerCase(Locale.ROOT);
            if (!this.nicknamePattern.matcher(account).matches()) {
                return;
            }
            if (this.requestedMap.containsKey(id)) {
                this.codeMap.remove(this.requestedMap.get(id));
            } else {
                this.requestedMap.put(id, account);
                this.requestedReverseMap.put(account, new TempAccount(dbField, id));
            }
            int code = ThreadLocalRandom.current().nextInt(Settings.IMP.MAIN.CODE_LOWER_BOUND, Settings.IMP.MAIN.CODE_UPPER_BOUND);
            this.codeMap.put(account, code);
            this.socialManager.broadcastMessage(dbField, id, Settings.IMP.MAIN.STRINGS.LINK_CODE.replace("{CODE}", String.valueOf(code)));
        } else if (message.startsWith(Settings.IMP.MAIN.FORCE_KEYBOARD_CMD)) {
            this.socialManager.broadcastMessage(dbField, id, Settings.IMP.MAIN.STRINGS.KEYBOARD_RESTORED, this.keyboard);
        }
    });
    this.socialManager.addButtonEvent(INFO_BTN, (dbField, id) -> {
        try {
            List<SocialPlayer> socialPlayerList = this.dao.queryForEq(dbField, id);
            if (socialPlayerList.size() == 0) {
                return;
            }
            SocialPlayer player = socialPlayerList.get(0);
            Optional<Player> proxyPlayer = this.server.getPlayer(player.getLowercaseNickname());
            String server;
            String ip;
            String location;
            if (proxyPlayer.isPresent()) {
                Player player1 = proxyPlayer.get();
                Optional<ServerConnection> connection = player1.getCurrentServer();
                if (connection.isPresent()) {
                    server = connection.get().getServerInfo().getName();
                } else {
                    server = Settings.IMP.MAIN.STRINGS.STATUS_OFFLINE;
                }
                ip = player1.getRemoteAddress().getAddress().getHostAddress();
                location = Optional.ofNullable(this.geoIp).map(nonNullGeo -> "(" + nonNullGeo.getLocation(ip) + ")").orElse("");
            } else {
                server = Settings.IMP.MAIN.STRINGS.STATUS_OFFLINE;
                ip = Settings.IMP.MAIN.STRINGS.STATUS_OFFLINE;
                location = "";
            }
            this.socialManager.broadcastMessage(dbField, id, Settings.IMP.MAIN.STRINGS.INFO_MSG.replace("{NICKNAME}", player.getLowercaseNickname()).replace("{SERVER}", server).replace("{IP}", ip).replace("{LOCATION}", location).replace("{NOTIFY_STATUS}", player.isNotifyEnabled() ? Settings.IMP.MAIN.STRINGS.NOTIFY_ENABLED : Settings.IMP.MAIN.STRINGS.NOTIFY_DISABLED).replace("{BLOCK_STATUS}", player.isBlocked() ? Settings.IMP.MAIN.STRINGS.BLOCK_ENABLED : Settings.IMP.MAIN.STRINGS.BLOCK_DISABLED).replace("{TOTP_STATUS}", player.isTotpEnabled() ? Settings.IMP.MAIN.STRINGS.TOTP_ENABLED : Settings.IMP.MAIN.STRINGS.TOTP_DISABLED), this.keyboard);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    });
    this.socialManager.addButtonEvent(BLOCK_BTN, (dbField, id) -> {
        try {
            List<SocialPlayer> socialPlayerList = this.dao.queryForEq(dbField, id);
            if (socialPlayerList.size() == 0) {
                return;
            }
            SocialPlayer player = socialPlayerList.get(0);
            if (player.isBlocked()) {
                player.setBlocked(false);
                this.socialManager.broadcastMessage(dbField, id, Settings.IMP.MAIN.STRINGS.UNBLOCK_SUCCESS.replace("{NICKNAME}", player.getLowercaseNickname()), this.keyboard);
            } else {
                player.setBlocked(true);
                this.plugin.removePlayerFromCache(player.getLowercaseNickname());
                this.server.getPlayer(player.getLowercaseNickname()).ifPresent(e -> e.disconnect(LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.KICK_GAME_MESSAGE)));
                this.socialManager.broadcastMessage(dbField, id, Settings.IMP.MAIN.STRINGS.BLOCK_SUCCESS.replace("{NICKNAME}", player.getLowercaseNickname()), this.keyboard);
            }
            this.dao.update(player);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    });
    this.socialManager.addButtonEvent(TOTP_BTN, (dbField, id) -> {
        try {
            List<SocialPlayer> socialPlayerList = this.dao.queryForEq(dbField, id);
            if (socialPlayerList.size() == 0) {
                return;
            }
            SocialPlayer player = socialPlayerList.get(0);
            if (player.isTotpEnabled()) {
                player.setTotpEnabled(false);
                this.socialManager.broadcastMessage(dbField, id, Settings.IMP.MAIN.STRINGS.TOTP_DISABLE_SUCCESS.replace("{NICKNAME}", player.getLowercaseNickname()), this.keyboard);
            } else {
                player.setTotpEnabled(true);
                this.socialManager.broadcastMessage(dbField, id, Settings.IMP.MAIN.STRINGS.TOTP_ENABLE_SUCCESS.replace("{NICKNAME}", player.getLowercaseNickname()), this.keyboard);
            }
            this.dao.update(player);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    });
    this.socialManager.addButtonEvent(NOTIFY_BTN, (dbField, id) -> {
        try {
            List<SocialPlayer> socialPlayerList = this.dao.queryForEq(dbField, id);
            if (socialPlayerList.size() == 0) {
                return;
            }
            SocialPlayer player = socialPlayerList.get(0);
            if (player.isNotifyEnabled()) {
                player.setNotifyEnabled(false);
                this.socialManager.broadcastMessage(dbField, id, Settings.IMP.MAIN.STRINGS.NOTIFY_DISABLE_SUCCESS.replace("{NICKNAME}", player.getLowercaseNickname()), this.keyboard);
            } else {
                player.setNotifyEnabled(true);
                this.socialManager.broadcastMessage(dbField, id, Settings.IMP.MAIN.STRINGS.NOTIFY_ENABLE_SUCCESS.replace("{NICKNAME}", player.getLowercaseNickname()), this.keyboard);
            }
            this.dao.update(player);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    });
    this.socialManager.addButtonEvent(KICK_BTN, (dbField, id) -> {
        try {
            List<SocialPlayer> socialPlayerList = this.dao.queryForEq(dbField, id);
            if (socialPlayerList.size() == 0) {
                return;
            }
            SocialPlayer player = socialPlayerList.get(0);
            Optional<Player> proxyPlayer = this.server.getPlayer(player.getLowercaseNickname());
            this.plugin.removePlayerFromCache(player.getLowercaseNickname());
            if (proxyPlayer.isPresent()) {
                proxyPlayer.get().disconnect(LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.KICK_GAME_MESSAGE));
                this.socialManager.broadcastMessage(dbField, id, Settings.IMP.MAIN.STRINGS.KICK_SUCCESS.replace("{NICKNAME}", player.getLowercaseNickname()), this.keyboard);
            } else {
                this.socialManager.broadcastMessage(dbField, id, Settings.IMP.MAIN.STRINGS.KICK_IS_OFFLINE.replace("{NICKNAME}", player.getLowercaseNickname()), this.keyboard);
            }
            this.dao.update(player);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    });
    this.socialManager.addButtonEvent(RESTORE_BTN, (dbField, id) -> {
        try {
            List<SocialPlayer> socialPlayerList = this.dao.queryForEq(dbField, id);
            if (socialPlayerList.size() == 0) {
                return;
            }
            SocialPlayer player = socialPlayerList.get(0);
            Dao<RegisteredPlayer, String> playerDao = this.plugin.getPlayerDao();
            String newPassword = Long.toHexString(Double.doubleToLongBits(Math.random()));
            UpdateBuilder<RegisteredPlayer, String> updateBuilder = playerDao.updateBuilder();
            updateBuilder.where().eq("LOWERCASENICKNAME", player.getLowercaseNickname());
            updateBuilder.updateColumnValue("HASH", AuthSessionHandler.genHash(newPassword));
            updateBuilder.update();
            this.socialManager.broadcastMessage(dbField, id, Settings.IMP.MAIN.STRINGS.RESTORE_MSG.replace("{NICKNAME}", player.getLowercaseNickname()).replace("{PASSWORD}", newPassword), this.keyboard);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    });
    this.socialManager.addButtonEvent(UNLINK_BTN, (dbField, id) -> {
        try {
            if (Settings.IMP.MAIN.DISABLE_UNLINK) {
                this.socialManager.broadcastMessage(dbField, id, Settings.IMP.MAIN.STRINGS.UNLINK_DISABLED, this.keyboard);
                return;
            }
            List<SocialPlayer> socialPlayerList = this.dao.queryForEq(dbField, id);
            if (socialPlayerList.size() == 0) {
                return;
            }
            SocialPlayer player = socialPlayerList.get(0);
            if (player.isBlocked()) {
                this.socialManager.broadcastMessage(dbField, id, Settings.IMP.MAIN.STRINGS.UNLINK_BLOCK_CONFLICT, this.keyboard);
                return;
            }
            if (Settings.IMP.MAIN.UNLINK_BTN_ALL) {
                this.dao.delete(player);
                this.socialManager.unregisterHook(player);
            } else {
                UpdateBuilder<SocialPlayer, String> updateBuilder = this.dao.updateBuilder();
                updateBuilder.where().eq(SocialPlayer.LOWERCASE_NICKNAME_FIELD, player.getLowercaseNickname());
                updateBuilder.updateColumnValue(dbField, null);
                updateBuilder.update();
                this.socialManager.unregisterHook(dbField, player);
            }
            this.socialManager.broadcastMessage(dbField, id, Settings.IMP.MAIN.STRINGS.UNLINK_SUCCESS);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    });
    UpdatesChecker.checkForUpdates(this.logger);
}
Also used : SocialPlayer(net.elytrium.limboauth.socialaddon.model.SocialPlayer) Player(com.velocitypowered.api.proxy.Player) RegisteredPlayer(net.elytrium.limboauth.model.RegisteredPlayer) SQLException(java.sql.SQLException) ServerConnection(com.velocitypowered.api.proxy.ServerConnection) RegisteredPlayer(net.elytrium.limboauth.model.RegisteredPlayer) AbstractSocial(net.elytrium.limboauth.socialaddon.social.AbstractSocial) File(java.io.File) SocialPlayer(net.elytrium.limboauth.socialaddon.model.SocialPlayer) Subscribe(com.velocitypowered.api.event.Subscribe)

Example 2 with ServerConnection

use of com.velocitypowered.api.proxy.ServerConnection in project SubServers-2 by ME1312.

the class SubCommand method suggest.

/**
 * Suggest command arguments
 *
 * @param invocation Command invocation
 * @return The validator's response and list of possible arguments
 */
@SuppressWarnings("unchecked")
public List<String> suggest(Invocation invocation) {
    CommandSource sender = invocation.source();
    String[] args = invocation.arguments();
    String Last = (args.length > 0) ? args[args.length - 1] : "";
    String last = Last.toLowerCase();
    ServerInfo pcs = (sender instanceof Player) ? ((Player) sender).getCurrentServer().map(ServerConnection::getServerInfo).orElse(null) : null;
    ServerData pcsd = plugin.getData(pcs);
    if (plugin.api.getSubDataNetwork()[0] == null) {
        if (sender instanceof ConsoleCommandSource)
            new IllegalStateException("SubData is not connected").printStackTrace();
        return Collections.emptyList();
    } else if (sender instanceof Player && (!permitted.containsKey(((Player) sender).getUniqueId()) || !permitted.get(((Player) sender).getUniqueId()).containsKey(pcs) || !permitted.get(((Player) sender).getUniqueId()).get(pcs).value())) {
        if (permitted.containsKey(((Player) sender).getUniqueId()) && permitted.get(((Player) sender).getUniqueId()).containsKey(pcs) && permitted.get(((Player) sender).getUniqueId()).get(pcs).key() == null) {
        // do nothing
        } else if (!permitted.containsKey(((Player) sender).getUniqueId()) || !permitted.get(((Player) sender).getUniqueId()).containsKey(pcs) || Calendar.getInstance().getTime().getTime() - permitted.get(((Player) sender).getUniqueId()).get(pcs).key() >= TimeUnit.MINUTES.toMillis(1)) {
            if (pcsd == null || pcsd.getSubData()[0] == null) {
                HashMap<ServerInfo, Pair<Long, Boolean>> map = (permitted.containsKey(((Player) sender).getUniqueId())) ? permitted.get(((Player) sender).getUniqueId()) : new HashMap<ServerInfo, Pair<Long, Boolean>>();
                map.put(pcs, new ContainedPair<>(Calendar.getInstance().getTime().getTime(), false));
                permitted.put(((Player) sender).getUniqueId(), map);
            } else {
                HashMap<ServerInfo, Pair<Long, Boolean>> map = (permitted.containsKey(((Player) sender).getUniqueId())) ? permitted.get(((Player) sender).getUniqueId()) : new HashMap<ServerInfo, Pair<Long, Boolean>>();
                map.put(pcs, new ContainedPair<>(null, false));
                permitted.put(((Player) sender).getUniqueId(), map);
                ((SubDataSender) pcsd.getSubData()[0]).sendPacket(new PacketCheckPermission(((Player) sender).getUniqueId(), "subservers.command", result -> {
                    map.put(pcs, new ContainedPair<>(Calendar.getInstance().getTime().getTime(), result));
                }));
            }
        }
        return Collections.emptyList();
    } else if (args.length <= 1) {
        List<String> cmds = new ArrayList<>();
        cmds.addAll(Arrays.asList("help", "list", "info", "status", "version", "start", "restart", "stop", "kill", "terminate", "cmd", "command", "create", "update", "upgrade", "restore"));
        if (!(sender instanceof Player))
            cmds.addAll(Arrays.asList("remove", "delete"));
        updateCache();
        List<String> list = new ArrayList<String>();
        for (String cmd : cmds) {
            if (cmd.startsWith(last))
                list.add(Last + cmd.substring(last.length()));
        }
        return list;
    } else {
        if (args[0].equals("info") || args[0].equals("status")) {
            Supplier<Collection<String>> getPlayers = () -> {
                LinkedList<String> names = new LinkedList<String>();
                for (Player player : ExProxy.getInstance().getAllPlayers()) names.add(player.getGameProfile().getName());
                for (CachedPlayer player : plugin.api.getRemotePlayers().values()) if (!names.contains(player.getName()))
                    names.add(player.getName());
                Collections.sort(names);
                return names;
            };
            updateCache();
            if (args.length == 2) {
                List<String> list = new ArrayList<String>();
                List<String> subcommands = new ArrayList<String>();
                subcommands.add("proxy");
                subcommands.add("host");
                subcommands.add("group");
                subcommands.add("server");
                subcommands.add("subserver");
                subcommands.add("player");
                for (String command : subcommands) {
                    if (!list.contains(command) && command.toLowerCase().startsWith(last))
                        list.add(Last + command.substring(last.length()));
                }
                Proxy master = proxyMasterCache;
                if (master != null && !list.contains(master.getName()) && master.getName().toLowerCase().startsWith(last))
                    list.add(Last + master.getName().substring(last.length()));
                for (Proxy proxy : proxyCache.values()) {
                    if (!list.contains(proxy.getName()) && proxy.getName().toLowerCase().startsWith(last))
                        list.add(Last + proxy.getName().substring(last.length()));
                }
                for (Host host : hostCache.values()) {
                    if (!list.contains(host.getName()) && host.getName().toLowerCase().startsWith(last))
                        list.add(Last + host.getName().substring(last.length()));
                }
                for (String group : groupCache.keySet()) {
                    if (!list.contains(group) && group.toLowerCase().startsWith(last))
                        list.add(Last + group.substring(last.length()));
                }
                for (ServerData server : plugin.servers.values()) {
                    if (!list.contains(server.getName()) && server.getName().toLowerCase().startsWith(last))
                        list.add(Last + server.getName().substring(last.length()));
                }
                for (String player : getPlayers.get()) {
                    if (!list.contains(player) && player.toLowerCase().startsWith(last))
                        list.add(Last + player.substring(last.length()));
                }
                return list;
            } else if (args.length == 3) {
                List<String> list = new ArrayList<String>();
                switch(args[1].toLowerCase()) {
                    case "p":
                    case "proxy":
                        Proxy master = proxyMasterCache;
                        if (master != null && master.getName().toLowerCase().startsWith(last))
                            list.add(Last + master.getName().substring(last.length()));
                        for (Proxy proxy : proxyCache.values()) {
                            if (!list.contains(proxy.getName()) && proxy.getName().toLowerCase().startsWith(last))
                                list.add(Last + proxy.getName().substring(last.length()));
                        }
                        break;
                    case "h":
                    case "host":
                        for (Host host : hostCache.values()) {
                            if (host.getName().toLowerCase().startsWith(last))
                                list.add(Last + host.getName().substring(last.length()));
                        }
                        break;
                    case "g":
                    case "group":
                        for (String group : groupCache.keySet()) {
                            if (group.toLowerCase().startsWith(last))
                                list.add(Last + group.substring(last.length()));
                        }
                        break;
                    case "s":
                    case "server":
                    case "subserver":
                        for (ServerData server : plugin.servers.values()) {
                            if ((!args[1].equalsIgnoreCase("subserver") || server instanceof SubServerData) && server.getName().toLowerCase().startsWith(last))
                                list.add(Last + server.getName().substring(last.length()));
                        }
                        break;
                    case "u":
                    case "user":
                    case "player":
                        for (String player : getPlayers.get()) {
                            if (player.toLowerCase().startsWith(last))
                                list.add(Last + player.substring(last.length()));
                        }
                        break;
                }
                return list;
            } else {
                return Collections.emptyList();
            }
        } else if (args[0].equals("start") || args[0].equals("restart") || args[0].equals("stop") || args[0].equals("kill") || args[0].equals("terminate") || args[0].equals("cmd") || args[0].equals("command") || args[0].equals("update") || args[0].equals("upgrade") || args[0].equals("remove") || args[0].equals("del") || args[0].equals("delete")) {
            List<String> list = new ArrayList<String>();
            boolean mode = !args[0].equals("cmd") && !args[0].equals("command");
            RawServerSelection select = selectRawServers(null, args, 1, mode);
            if (select.last != null) {
                if (last.startsWith("::")) {
                    Map<String, Host> hosts = hostCache;
                    if (hosts.size() > 0) {
                        if (Arrays.binarySearch(select.selection, "::*") < 0 && "::*".startsWith(last))
                            list.add("::*");
                        if (sender instanceof Player && Arrays.binarySearch(select.selection, "::.") < 0 && "::.".startsWith(last))
                            list.add("::.");
                        for (Host host : hosts.values()) {
                            String name = "::" + host.getName();
                            if (Arrays.binarySearch(select.selection, name.toLowerCase()) < 0 && name.toLowerCase().startsWith(last))
                                list.add(Last + name.substring(last.length()));
                        }
                    }
                    return list;
                } else if (last.startsWith(":")) {
                    Map<String, List<Server>> groups = groupCache;
                    if (groups.size() > 0) {
                        if (Arrays.binarySearch(select.selection, ":*") < 0 && ":*".startsWith(last))
                            list.add(":*");
                        if (sender instanceof Player && Arrays.binarySearch(select.selection, ":.") < 0 && ":.".startsWith(last))
                            list.add(":.");
                        for (String group : groups.keySet()) {
                            group = ":" + group;
                            if (Arrays.binarySearch(select.selection, group.toLowerCase()) < 0 && group.toLowerCase().startsWith(last))
                                list.add(Last + group.substring(last.length()));
                        }
                    }
                    return list;
                } else {
                    Map<ServerInfo, ServerData> subservers = plugin.servers;
                    if (subservers.size() > 0) {
                        if (Arrays.binarySearch(select.selection, "*") < 0 && "*".startsWith(last))
                            list.add("*");
                        if (sender instanceof Player && Arrays.binarySearch(select.selection, ".") < 0 && ".".startsWith(last))
                            list.add(".");
                        for (ServerData server : subservers.values()) {
                            if ((!mode || server instanceof SubServerData) && Arrays.binarySearch(select.selection, server.getName().toLowerCase()) < 0 && server.getName().toLowerCase().startsWith(last))
                                list.add(Last + server.getName().substring(last.length()));
                        }
                    }
                    return list;
                }
            } else if (args[0].equals("cmd") || args[0].equals("command")) {
                if (select.args.length == 3) {
                    return Collections.singletonList("<Command>");
                } else {
                    return Collections.singletonList("[Args...]");
                }
            } else if (args[0].equals("update") || args[0].equals("upgrade")) {
                if (select.args.length == 3) {
                    return Arrays.asList("[Template]", "[Version]");
                } else if (select.args.length == 4) {
                    return Collections.singletonList("<Version>");
                }
            }
            return Collections.emptyList();
        } else if (args[0].equals("create")) {
            updateCache();
            if (args.length == 2) {
                return Collections.singletonList("<Name>");
            } else if (args.length == 3) {
                List<String> list = new ArrayList<String>();
                for (Host host : hostCache.values()) {
                    if (host.getName().toLowerCase().startsWith(last))
                        list.add(Last + host.getName().substring(last.length()));
                }
                return list;
            } else if (args.length == 4) {
                List<String> list = new ArrayList<String>();
                Map<String, Host> hosts = hostCache;
                if (!hosts.containsKey(args[2].toLowerCase())) {
                    list.add("<Template>");
                } else {
                    for (SubCreator.ServerTemplate template : hosts.get(args[2].toLowerCase()).getCreator().getTemplates().values()) {
                        if (template.getName().toLowerCase().startsWith(last))
                            list.add(Last + template.getName().substring(last.length()));
                    }
                }
                return list;
            } else if (args.length == 5) {
                return Collections.singletonList("[Version]");
            } else if (args.length == 6) {
                if (last.length() > 0) {
                    if (!Try.all.run(() -> Integer.parseInt(last)) || Integer.parseInt(last) <= 0 || Integer.parseInt(last) > 65535) {
                        return Collections.emptyList();
                    }
                }
                return Collections.singletonList("[Port]");
            } else {
                return Collections.emptyList();
            }
        } else if (args[0].equals("restore")) {
            if (args.length == 2) {
                return Collections.singletonList("<Subserver>");
            } else {
                return Collections.emptyList();
            }
        } else if (sender instanceof Player && (args[0].equals("tp") || args[0].equals("teleport"))) {
            if (args.length == 2 || args.length == 3) {
                List<String> list = new ArrayList<String>();
                if (args.length == 2) {
                    list.add("@p");
                    list.add("@a");
                    list.add("@r");
                    list.add("@s");
                    List<UUID> used = new ArrayList<UUID>();
                    Optional<ServerConnection> server = ((Player) sender).getCurrentServer();
                    if (server.isPresent()) {
                        for (Player player : server.get().getServer().getPlayersConnected()) {
                            if (player.getGameProfile().getName().toLowerCase().startsWith(last))
                                list.add(Last + player.getGameProfile().getName().substring(last.length()));
                            used.add(player.getUniqueId());
                        }
                        for (CachedPlayer player : SubAPI.getInstance().getRemotePlayers(server.get().getServerInfo()).values()) {
                            if (!used.contains(player.getUniqueId())) {
                                if (player.getName().toLowerCase().startsWith(last))
                                    list.add(Last + player.getName().substring(last.length()));
                                used.add(player.getUniqueId());
                            }
                        }
                    }
                }
                for (ServerData server : plugin.servers.values()) {
                    if (server.getName().toLowerCase().startsWith(last))
                        list.add(Last + server.getName().substring(last.length()));
                }
                return list;
            } else {
                return Collections.emptyList();
            }
        } else {
            return Collections.emptyList();
        }
    }
}
Also used : Platform(net.ME1312.Galaxi.Library.Platform) SubDataSender(net.ME1312.SubData.Client.SubDataSender) ServerConnection(com.velocitypowered.api.proxy.ServerConnection) java.util(java.util) SimpleCommand(com.velocitypowered.api.command.SimpleCommand) SubServerData(net.ME1312.SubServers.Velocity.Server.SubServerData) ChatColor(net.ME1312.SubServers.Velocity.Library.Compatibility.ChatColor) URL(java.net.URL) ClickEvent(net.kyori.adventure.text.event.ClickEvent) Supplier(java.util.function.Supplier) SubDataClient(net.ME1312.SubData.Client.SubDataClient) ServerData(net.ME1312.SubServers.Velocity.Server.ServerData) API(net.ME1312.SubServers.Client.Common.Network.API) Charset(java.nio.charset.Charset) AsyncConsolidator(net.ME1312.Galaxi.Library.AsyncConsolidator) Util(net.ME1312.Galaxi.Library.Util) Version(net.ME1312.Galaxi.Library.Version.Version) Try(net.ME1312.Galaxi.Library.Try) Gson(com.google.gson.Gson) Component(net.kyori.adventure.text.Component) Player(com.velocitypowered.api.proxy.Player) PacketCreateServer(net.ME1312.SubServers.Client.Common.Network.Packet.PacketCreateServer) PacketInExRunEvent(net.ME1312.SubServers.Velocity.Network.Packet.PacketInExRunEvent) CachedPlayer(net.ME1312.SubServers.Velocity.Server.CachedPlayer) TextComponent(net.kyori.adventure.text.TextComponent) RawCommand(com.velocitypowered.api.command.RawCommand) ConsoleCommandSource(com.velocitypowered.api.proxy.ConsoleCommandSource) Value(net.ME1312.Galaxi.Library.Container.Value) PacketUpdateServer(net.ME1312.SubServers.Client.Common.Network.Packet.PacketUpdateServer) RegisteredServer(com.velocitypowered.api.proxy.server.RegisteredServer) InputStreamReader(java.io.InputStreamReader) NamedTextColor(net.kyori.adventure.text.format.NamedTextColor) InvocationTargetException(java.lang.reflect.InvocationTargetException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ServerInfo(com.velocitypowered.api.proxy.server.ServerInfo) Container(net.ME1312.Galaxi.Library.Container.Container) ObjectMap(net.ME1312.Galaxi.Library.Map.ObjectMap) ContainedPair(net.ME1312.Galaxi.Library.Container.ContainedPair) PacketCheckPermission(net.ME1312.SubServers.Velocity.Network.Packet.PacketCheckPermission) BufferedReader(java.io.BufferedReader) Pair(net.ME1312.Galaxi.Library.Container.Pair) CommandSource(com.velocitypowered.api.command.CommandSource) HoverEvent(net.kyori.adventure.text.event.HoverEvent) CachedPlayer(net.ME1312.SubServers.Velocity.Server.CachedPlayer) ServerInfo(com.velocitypowered.api.proxy.server.ServerInfo) SubServerData(net.ME1312.SubServers.Velocity.Server.SubServerData) ServerData(net.ME1312.SubServers.Velocity.Server.ServerData) ContainedPair(net.ME1312.Galaxi.Library.Container.ContainedPair) ConsoleCommandSource(com.velocitypowered.api.proxy.ConsoleCommandSource) ContainedPair(net.ME1312.Galaxi.Library.Container.ContainedPair) Pair(net.ME1312.Galaxi.Library.Container.Pair) SubServerData(net.ME1312.SubServers.Velocity.Server.SubServerData) Player(com.velocitypowered.api.proxy.Player) CachedPlayer(net.ME1312.SubServers.Velocity.Server.CachedPlayer) ServerConnection(com.velocitypowered.api.proxy.ServerConnection) ConsoleCommandSource(com.velocitypowered.api.proxy.ConsoleCommandSource) CommandSource(com.velocitypowered.api.command.CommandSource) SubDataSender(net.ME1312.SubData.Client.SubDataSender) PacketCheckPermission(net.ME1312.SubServers.Velocity.Network.Packet.PacketCheckPermission) ObjectMap(net.ME1312.Galaxi.Library.Map.ObjectMap)

Example 3 with ServerConnection

use of com.velocitypowered.api.proxy.ServerConnection in project SubServers-2 by ME1312.

the class ExProxy method post.

private void post() {
    if (!config.get().getMap("Settings").getStringList("Disabled-Overrides", Collections.emptyList()).contains("/server"))
        proxy.getCommandManager().register("server", new SubCommand.BungeeServer(this));
    if (!config.get().getMap("Settings").getStringList("Disabled-Overrides", Collections.emptyList()).contains("/glist"))
        proxy.getCommandManager().register("glist", new SubCommand.BungeeList(this));
    proxy.getCommandManager().register("subservers", new SubCommand(this), "subserver", "sub");
    if (config.get().getMap("Settings").getMap("Smart-Fallback", new ObjectMap<>()).getBoolean("Enabled", true))
        proxy.getEventManager().register(this, new SmartFallback(config.get().getMap("Settings").getMap("Smart-Fallback", new ObjectMap<>())));
    metrics.make(this, 11953).appendAppData();
    new Timer("SubServers.Sync::Routine_Update_Check").schedule(new TimerTask() {

        @SuppressWarnings("unchecked")
        @Override
        public void run() {
            try {
                ObjectMap<String> tags = new ObjectMap<String>(new Gson().fromJson("{\"tags\":" + Util.readAll(new BufferedReader(new InputStreamReader(new URL("https://api.github.com/repos/ME1312/SubServers-2/git/refs/tags").openStream(), Charset.forName("UTF-8")))) + '}', Map.class));
                List<Version> versions = new LinkedList<Version>();
                Version updversion = version;
                int updcount = 0;
                for (ObjectMap<String> tag : tags.getMapList("tags")) versions.add(Version.fromString(tag.getString("ref").substring(10)));
                Collections.sort(versions);
                for (Version version : versions) {
                    if (version.compareTo(updversion) > 0) {
                        updversion = version;
                        updcount++;
                    }
                }
                if (updcount > 0)
                    Logger.get("SubServers").info("SubServers.Sync v" + updversion + " is available. You are " + updcount + " version" + ((updcount == 1) ? "" : "s") + " behind.");
            } catch (Exception e) {
            }
        }
    }, 0, TimeUnit.DAYS.toMillis(2));
    int rpec_i = config.get().getMap("Settings").getInt("RPEC-Check-Interval", 300);
    int rpec_s = rpec_i - new Random().nextInt((rpec_i / 3) + 1);
    new Timer("SubServers.Sync::RemotePlayer_Error_Checking").schedule(new TimerTask() {

        @Override
        public void run() {
            if (api.getName() != null && api.getSubDataNetwork()[0] != null && !api.getSubDataNetwork()[0].isClosed()) {
                api.getProxy(api.getName(), proxy -> {
                    synchronized (rPlayers) {
                        ArrayList<CachedPlayer> add = new ArrayList<CachedPlayer>();
                        for (Player player : ExProxy.this.proxy.getAllPlayers()) {
                            if (!rPlayers.containsKey(player.getUniqueId())) {
                                // Add players that don't exist
                                CachedPlayer p = new CachedPlayer(player);
                                rPlayerLinkP.put(player.getUniqueId(), p.getProxyName().toLowerCase());
                                rPlayers.put(player.getUniqueId(), p);
                                ServerInfo server = player.getCurrentServer().map(ServerConnection::getServerInfo).orElse(null);
                                if (servers.containsKey(server))
                                    rPlayerLinkS.put(player.getUniqueId(), servers.get(server));
                                add.add(p);
                            }
                        }
                        ArrayList<CachedPlayer> remove = new ArrayList<CachedPlayer>();
                        for (Pair<String, UUID> player : proxy.getPlayers()) {
                            // Remove players that shouldn't exist
                            if (!ExProxy.this.proxy.getPlayer(player.value()).isPresent()) {
                                remove.add(rPlayers.get(player.value()));
                                rPlayerLinkS.remove(player.value());
                                rPlayerLinkP.remove(player.value());
                                rPlayers.remove(player.value());
                            }
                        }
                        for (UUID player : Util.getBackwards(rPlayerLinkP, api.getName().toLowerCase())) {
                            // Remove players that shouldn't exist (internally)
                            if (!ExProxy.this.proxy.getPlayer(player).isPresent()) {
                                rPlayerLinkS.remove(player);
                                rPlayerLinkP.remove(player);
                                rPlayers.remove(player);
                            }
                        }
                        // Compile change data for external proxies
                        LinkedList<PacketExSyncPlayer> packets = new LinkedList<PacketExSyncPlayer>();
                        if (add.size() > 0)
                            packets.add(new PacketExSyncPlayer(true, add.toArray(new CachedPlayer[0])));
                        if (remove.size() > 0)
                            packets.add(new PacketExSyncPlayer(false, remove.toArray(new CachedPlayer[0])));
                        if (packets.size() > 0) {
                            PacketExSyncPlayer[] packet = packets.toArray(new PacketExSyncPlayer[0]);
                            if (api.getSubDataNetwork()[0] != null) {
                                ((SubDataClient) api.getSubDataNetwork()[0]).sendPacket(packet);
                            }
                        }
                    }
                });
            }
        }
    }, TimeUnit.SECONDS.toMillis(rpec_s), TimeUnit.SECONDS.toMillis(rpec_i));
}
Also used : AES(net.ME1312.SubData.Client.Encryption.AES) DataClient(net.ME1312.SubData.Client.DataClient) ChatColor(net.ME1312.SubServers.Velocity.Library.Compatibility.ChatColor) URL(java.net.URL) Inject(com.google.inject.Inject) SubStoppedEvent(net.ME1312.SubServers.Velocity.Event.SubStoppedEvent) FallbackState(net.ME1312.SubServers.Velocity.Library.Fallback.FallbackState) SubRemoveServerEvent(net.ME1312.SubServers.Velocity.Event.SubRemoveServerEvent) InetAddress(java.net.InetAddress) DHE(net.ME1312.SubData.Client.Encryption.DHE) ServerPreConnectEvent(com.velocitypowered.api.event.player.ServerPreConnectEvent) Util(net.ME1312.Galaxi.Library.Util) Try(net.ME1312.Galaxi.Library.Try) Gson(com.google.gson.Gson) Player(com.velocitypowered.api.proxy.Player) PluginContainer(com.velocitypowered.api.plugin.PluginContainer) LoginEvent(com.velocitypowered.api.event.connection.LoginEvent) YAMLConfig(net.ME1312.Galaxi.Library.Config.YAMLConfig) ServerPostConnectEvent(com.velocitypowered.api.event.player.ServerPostConnectEvent) CachedPlayer(net.ME1312.SubServers.Velocity.Server.CachedPlayer) Plugin(com.velocitypowered.api.plugin.Plugin) Metrics(net.ME1312.SubServers.Velocity.Library.Metrics) PluginDescription(com.velocitypowered.api.plugin.PluginDescription) com.velocitypowered.api.event.proxy(com.velocitypowered.api.event.proxy) Logger(net.ME1312.SubServers.Velocity.Library.Compatibility.Logger) RegisteredServer(com.velocitypowered.api.proxy.server.RegisteredServer) NamedTextColor(net.kyori.adventure.text.format.NamedTextColor) ServerPing(com.velocitypowered.api.proxy.server.ServerPing) RSA(net.ME1312.SubData.Client.Encryption.RSA) ObjectMap(net.ME1312.Galaxi.Library.Map.ObjectMap) SmartFallback(net.ME1312.SubServers.Velocity.Library.Fallback.SmartFallback) TextReplacementConfig(net.kyori.adventure.text.TextReplacementConfig) Subscribe(com.velocitypowered.api.event.Subscribe) SubProtocol(net.ME1312.SubServers.Velocity.Network.SubProtocol) Pair(net.ME1312.Galaxi.Library.Container.Pair) SubStartEvent(net.ME1312.SubServers.Velocity.Event.SubStartEvent) DisconnectEvent(com.velocitypowered.api.event.connection.DisconnectEvent) ServerConnection(com.velocitypowered.api.proxy.ServerConnection) java.util(java.util) SubAddServerEvent(net.ME1312.SubServers.Velocity.Event.SubAddServerEvent) SubServerData(net.ME1312.SubServers.Velocity.Server.SubServerData) DisconnectReason(net.ME1312.SubData.Client.Library.DisconnectReason) UPnP(com.dosse.upnp.UPnP) ConfigUpdater(net.ME1312.SubServers.Velocity.Library.ConfigUpdater) SubDataClient(net.ME1312.SubData.Client.SubDataClient) ServerData(net.ME1312.SubServers.Velocity.Server.ServerData) Charset(java.nio.charset.Charset) Version(net.ME1312.Galaxi.Library.Version.Version) PostOrder(com.velocitypowered.api.event.PostOrder) PacketDisconnectPlayer(net.ME1312.SubServers.Client.Common.Network.Packet.PacketDisconnectPlayer) Component(net.kyori.adventure.text.Component) ProxyServer(com.velocitypowered.api.proxy.ProxyServer) LegacyComponentSerializer(net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer) PacketExSyncPlayer(net.ME1312.SubServers.Velocity.Network.Packet.PacketExSyncPlayer) KickedFromServerEvent(com.velocitypowered.api.event.player.KickedFromServerEvent) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) ServerInfo(com.velocitypowered.api.proxy.server.ServerInfo) BufferedReader(java.io.BufferedReader) CachedPlayer(net.ME1312.SubServers.Velocity.Server.CachedPlayer) ServerInfo(com.velocitypowered.api.proxy.server.ServerInfo) Gson(com.google.gson.Gson) URL(java.net.URL) ObjectMap(net.ME1312.Galaxi.Library.Map.ObjectMap) Version(net.ME1312.Galaxi.Library.Version.Version) SmartFallback(net.ME1312.SubServers.Velocity.Library.Fallback.SmartFallback) Pair(net.ME1312.Galaxi.Library.Container.Pair) Player(com.velocitypowered.api.proxy.Player) CachedPlayer(net.ME1312.SubServers.Velocity.Server.CachedPlayer) PacketDisconnectPlayer(net.ME1312.SubServers.Client.Common.Network.Packet.PacketDisconnectPlayer) PacketExSyncPlayer(net.ME1312.SubServers.Velocity.Network.Packet.PacketExSyncPlayer) InputStreamReader(java.io.InputStreamReader) ServerConnection(com.velocitypowered.api.proxy.ServerConnection) PacketExSyncPlayer(net.ME1312.SubServers.Velocity.Network.Packet.PacketExSyncPlayer) IOException(java.io.IOException) BufferedReader(java.io.BufferedReader)

Example 4 with ServerConnection

use of com.velocitypowered.api.proxy.ServerConnection in project ProxyQueues by JLyne.

the class QueueHandlerImpl method notifyQueueRemoval.

private void notifyQueueRemoval(Player player, String message, MessageType messageType) {
    if (!player.isActive()) {
        return;
    }
    RegisteredServer waitingServer = proxyQueues.getWaitingServer().orElse(null);
    Optional<ServerConnection> currentServer = player.getCurrentServer();
    if (currentServer.isPresent() && currentServer.get().getServer().equals(waitingServer)) {
        player.disconnect(Messages.getComponent(message));
    } else {
        proxyQueues.sendMessage(player, messageType, message);
    }
}
Also used : RegisteredServer(com.velocitypowered.api.proxy.server.RegisteredServer) ServerConnection(com.velocitypowered.api.proxy.ServerConnection)

Example 5 with ServerConnection

use of com.velocitypowered.api.proxy.ServerConnection in project ProxyQueues by JLyne.

the class QueueMoveTask method connectPlayer.

private void connectPlayer() {
    proxyQueues.getLogger().info("Attempting to connect player " + targetPlayer.toString());
    targetPlayer.getPlayer().createConnectionRequest(server).connect().thenAcceptAsync(result -> {
        targetPlayer.setConnecting(false);
        if (result.isSuccessful()) {
            return;
        }
        proxyQueues.getLogger().info("Player " + targetPlayer.getPlayer().getUsername() + " failed to join " + queue.getServer().getServerInfo().getName() + ". Reason: \"" + PlainTextComponentSerializer.plainText().serialize(result.getReasonComponent().orElse(Component.text("(None)"))) + "\"");
        Component reason = result.getReasonComponent().orElse(Component.empty());
        String reasonPlain = PlainTextComponentSerializer.plainText().serialize(reason);
        ServerConnection currentServer = targetPlayer.getPlayer().getCurrentServer().orElse(null);
        boolean fatal = fatalErrors.stream().anyMatch(reasonPlain::contains);
        if (fatal) {
            queue.removePlayer(targetPlayer, false);
            if (currentServer == null || currentServer.getServer().equals(waitingServer)) {
                targetPlayer.getPlayer().disconnect(result.getReasonComponent().orElse(Component.empty()));
            } else {
                proxyQueues.sendMessage(targetPlayer.getPlayer(), MessageType.ERROR, "errors.queue-cannot-join", Collections.singletonMap("reason", reasonPlain));
            }
        }
    });
    targetPlayer.setConnecting(true);
}
Also used : ServerConnection(com.velocitypowered.api.proxy.ServerConnection) Component(net.kyori.adventure.text.Component)

Aggregations

ServerConnection (com.velocitypowered.api.proxy.ServerConnection)21 Subscribe (com.velocitypowered.api.event.Subscribe)12 Player (com.velocitypowered.api.proxy.Player)12 RegisteredServer (com.velocitypowered.api.proxy.server.RegisteredServer)8 ByteArrayDataInput (com.google.common.io.ByteArrayDataInput)6 UUID (java.util.UUID)6 Component (net.kyori.adventure.text.Component)5 File (java.io.File)4 InputStreamReader (java.io.InputStreamReader)4 TimeUnit (java.util.concurrent.TimeUnit)4 Inject (com.google.inject.Inject)3 CommandSource (com.velocitypowered.api.command.CommandSource)3 PostOrder (com.velocitypowered.api.event.PostOrder)3 DisconnectEvent (com.velocitypowered.api.event.connection.DisconnectEvent)3 ServerPostConnectEvent (com.velocitypowered.api.event.player.ServerPostConnectEvent)3 ProxyServer (com.velocitypowered.api.proxy.ProxyServer)3 IOException (java.io.IOException)3 TextComponent (net.kyori.adventure.text.TextComponent)3 HoverEvent (net.kyori.adventure.text.event.HoverEvent)3 ByteArrayDataOutput (com.google.common.io.ByteArrayDataOutput)2