public final String getNameFromUuid(@NonNull UUID player, boolean expensiveLookups) { // If the player is online, give them their UUID. // Remember, local data > remote data. if (ProxyServer.getInstance().getPlayer(player) != null) return ProxyServer.getInstance().getPlayer(player).getName(); // Check if it exists in the map CachedUUIDEntry cachedUUIDEntry = uuidToNameMap.get(player); if (cachedUUIDEntry != null) { if (!cachedUUIDEntry.expired()) return cachedUUIDEntry.getName(); else uuidToNameMap.remove(player); } // Okay, it wasn't locally cached. Let's try Redis. try (Jedis jedis = plugin.getPool().getResource()) { String stored = jedis.hget("uuid-cache", player.toString()); if (stored != null) { // Found an entry value. Deserialize it. CachedUUIDEntry entry = RedisBungee.getGson().fromJson(stored, CachedUUIDEntry.class); // Check for expiry: if (entry.expired()) { jedis.hdel("uuid-cache", player.toString()); // Doesn't hurt to also remove the named entry as well. // TODO: Since UUIDs are fixed, we could look up the name and see if the UUID matches. jedis.hdel("uuid-cache", entry.getName()); } else { nameToUuidMap.put(entry.getName().toLowerCase(), entry); uuidToNameMap.put(player, entry); return entry.getName(); } } if (!expensiveLookups || !ProxyServer.getInstance().getConfig().isOnlineMode()) return null; // That didn't work. Let's ask Mojang. This call may fail, because Mojang is insane. String name; try { List<String> nameHist = NameFetcher.nameHistoryFromUuid(player); name = Iterables.getLast(nameHist, null); } catch (Exception e) { plugin.getLogger().log(Level.SEVERE, "Unable to fetch name from Mojang for " + player, e); return null; } if (name != null) { persistInfo(name, player, jedis); return name; } return null; } catch (JedisException e) { plugin.getLogger().log(Level.SEVERE, "Unable to fetch name for " + player, e); return null; } }
@EventHandler public void pingEvent(ProxyPingEvent e) { online = 0; slots = 0; servers[0] = new Minequery("91.121.7.118", 25571); servers[1] = new Minequery("91.121.7.118", 25572); for (Minequery query : servers) { String result = query.connetti(); String[] array_query = result.split("/"); try { int s_online = Integer.valueOf(array_query[0]).intValue(); int s_slots = Integer.valueOf(array_query[1]).intValue(); online += s_online; slots += s_slots; } catch (Exception ex) { } } e.setResponse( new ServerPing( ps.getProtocolVersion(), ps.getGameVersion(), e.getConnection().getListener().getMotd(), online, slots)); }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (ctx.channel().isActive()) { if (cause instanceof ReadTimeoutException) { ProxyServer.getInstance().getLogger().log(Level.WARNING, "{0} - read timed out", handler); } else if (cause instanceof BadPacketException) { ProxyServer.getInstance() .getLogger() .log(Level.WARNING, "{0} - bad packet ID, are mods in use!?", handler); } else if (cause instanceof IOException) { ProxyServer.getInstance() .getLogger() .log( Level.WARNING, "{0} - IOException: {1}", new Object[] {handler, cause.getMessage()}); } else { ProxyServer.getInstance() .getLogger() .log(Level.SEVERE, handler + " - encountered exception", cause); } if (handler != null) { try { handler.exception(cause); } catch (Exception ex) { ProxyServer.getInstance() .getLogger() .log(Level.SEVERE, handler + " - exception processing exception", ex); } } ctx.close(); } }
public void init() { this.entityRewrite = EntityMap.getEntityMap(getPendingConnection().getVersion()); this.displayName = name; // Blame Mojang for this one /*switch ( getPendingConnection().getListener().getTabListType() ) { case "GLOBAL": tabListHandler = new Global( this ); break; case "SERVER": tabListHandler = new ServerUnique( this ); break; default: tabListHandler = new GlobalPing( this ); break; }*/ tabListHandler = new ServerUnique(this); Collection<String> g = bungee.getConfigurationAdapter().getGroups(name); g.addAll(bungee.getConfigurationAdapter().getGroups(getUniqueId().toString())); for (String s : g) { addGroups(s); } forgeClientHandler = new ForgeClientHandler(this); // Set whether the connection has a 1.8 FML marker in the handshake. forgeClientHandler.setFmlTokenInHandshake( this.getPendingConnection() .getExtraDataInHandshake() .contains(ForgeConstants.FML_HANDSHAKE_TOKEN)); }
public Iterable<String> onTabComplete(CommandSender sender, String[] args) { if ((args.length > 2) || (args.length == 0)) { return ImmutableSet.of(); } Set<String> matches = new HashSet<>(); String search; if (args.length == 1) { search = args[0].toLowerCase(); for (ProxiedPlayer player : ProxyServer.getInstance().getPlayers()) { if (player.getName().toLowerCase().startsWith(search)) { matches.add(player.getName()); } } if ("all".startsWith(search)) { matches.add("all"); } if ("current".startsWith(search)) { matches.add("current"); } } else { search = args[1].toLowerCase(); for (String server : ProxyServer.getInstance().getServers().keySet()) { if (server.toLowerCase().startsWith(search)) { matches.add(server); } } } return matches; }
public void onEnable() { ProxyServer.getInstance().getPluginManager().registerListener(this, this); ps = ProxyServer.getInstance(); // minequery ip, //minequery port }
@Override public void execute(CommandSender sender, String[] args) { if (sender instanceof ProxiedPlayer) { if (args == null || args.length < 1) { sender.sendMessage(Dictionary.format(Dictionary.ERROR_INVALID_ARGUMENTS)); return; } ProxiedPlayer player = (ProxiedPlayer) sender; ProxiedPlayer join = ProxyServer.getInstance().getPlayer(args[0]); if (join == null || Messenger.isHidden(join)) { sender.sendMessage(Dictionary.format(Dictionary.ERROR_PLAYER_OFFLINE)); return; } if (player.getUniqueId() == join.getUniqueId()) { sender.sendMessage(ChatColor.RED + "You cannot join yourself!"); return; } ServerInfo info = join.getServer().getInfo(); if (info.canAccess(player)) { sender.sendMessage( ChatColor.LIGHT_PURPLE + "Attempting to join " + join.getName() + "'s server.."); player.connect(info); } else { sender.sendMessage(ProxyServer.getInstance().getTranslation("no_server_permission")); } } else { sender.sendMessage(ChatColor.RED + "Console cannot join servers"); } }
@Override public void handle(Chat chat) throws Exception { ChatEvent chatEvent = new ChatEvent(con, con.getServer(), chat.getMessage()); if (!bungee.getPluginManager().callEvent(chatEvent).isCancelled()) { chat.setMessage(chatEvent.getMessage()); if (!chatEvent.isCommand() || !bungee.getPluginManager().dispatchCommand(con, chat.getMessage().substring(1))) { con.getServer().unsafe().sendPacket(chat); } } throw new CancelSendSignal(); }
@Override public void disconnected(ChannelWrapper channel) throws Exception { // We lost connection to the client PlayerDisconnectEvent event = new PlayerDisconnectEvent(con); bungee.getPluginManager().callEvent(event); bungee.getTabListHandler().onDisconnect(con); BungeeCord.getInstance().removeConnection(con); if (con.getServer() != null) { con.getServer().disconnect("Quitting"); } }
void checkServers() { servers .values() .stream() .filter(server -> !server.isOnline()) .forEach( server -> { ProxyServer.getInstance() .getLogger() .severe( "[Servers] Server " + server.getName() + " detected as offline, removing."); remove(server.getName()); BungeeBridge.getInstance() .getExecutor() .addTask( () -> { Jedis jedis = BungeeBridge.getInstance().getConnector().getBungeeResource(); jedis.hdel("servers", server.getName()); jedis.sadd("offlineservers", server.getName()); jedis.del("connectedonserv:" + server.getName()); jedis.publish("servers", "stop " + server.getName()); jedis.close(); }); }); }
public ServersManager(BungeeBridge plugin) { this.plugin = plugin; // Recover servers // Jedis jedis = plugin.getConnector().getBungeeResource(); Map<String, String> servers = jedis.hgetAll("servers"); jedis.close(); for (String server : servers.keySet()) { String[] ip = servers.get(server).split(":"); if (ip.length == 2) createServer(server, ip[0], ip[1]); } // Init task ProxyServer.getInstance() .getScheduler() .schedule(plugin, this::checkServers, 30, 30, TimeUnit.SECONDS); thread = new SubscribingThread( SubscribingThread.Type.SUBSCRIBE, plugin.getConnector(), new Subscriber(this), "servers"); new Thread(thread).start(); }
public void checkJenkins() { ProxyServer.getInstance() .getScheduler() .runAsync( plugin, new Runnable() { @Override public void run() { try { URL url = new URL(jenkinsData); Gson gson = new Gson(); URLConnection conn = url.openConnection(); JsonReader reader = new JsonReader(new InputStreamReader(conn.getInputStream())); JenkinsVerInfo jenkinsInfo = gson.fromJson(reader, JenkinsVerInfo.class); String latestGit = jenkinsInfo.lastBuiltRevision.SHA1; String currentGit = currentVer.substring(currentVer.indexOf("-git") + 5); // logger.info(String.format("L: %s | C: %s", latestGit, currentGit)); if (currentGit.equals(latestGit)) { outResult(false, true, latestGit, jenkinsDL); } else { outResult(true, true, latestGit, jenkinsDL); } } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } }); }
@Override public boolean hasPermission(String permission) { return bungee .getPluginManager() .callEvent(new PermissionCheckEvent(this, permission, permissions.contains(permission))) .hasPermission(); }
public void checkGH() { ProxyServer.getInstance() .getScheduler() .runAsync( plugin, new Runnable() { @Override public void run() { try { String branch = "stable"; URL url = new URL(gitHubData); Gson gson = new Gson(); URLConnection conn = url.openConnection(); JsonReader reader = new JsonReader(new InputStreamReader(conn.getInputStream())); VerInfo verinfo = gson.fromJson(reader, VerInfo.class); String latestVer = verinfo.result.get(branch).version; String latestDL = verinfo.result.get(branch).download; if (currentVer.equals(latestVer)) { outResult(false, false, latestVer, latestDL); } else { outResult(true, false, latestVer, latestDL); } } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } }); }
public static void sendMessageToTarget(String target, String message) { sendMessageToTarget( getPlayer(target) != null ? getPlayer(target).getProxiedPlayer() : ProxyServer.getInstance().getConsole(), message); }
private static CommandSender getSender(String sender) { if (sender != null) { GSPlayer p = PlayerManager.getPlayer(sender); return (p == null ? ProxyServer.getInstance().getConsole() : p.getProxiedPlayer()); } return null; }
@Override public void onCommand(CommandSender sender, String[] args, boolean confirmedCmd) throws IllegalArgumentException { final ProxiedPlayer target = ProxyServer.getInstance().getPlayer(args[0]); final String reason = Utils.getFinalArg(args, 1); if(target == null){ if(!confirmedCmd && Core.getPlayerIP(args[0]).equals("0.0.0.0")){ mustConfirmCommand(sender, getName() + " " + Joiner.on(' ').join(args), _("operationUnknownPlayer", new String[] {args[0]})); return; } } if(sender instanceof ProxiedPlayer){ checkArgument(PermissionManager.canExecuteAction(Action.WARN , sender, ((ProxiedPlayer)sender).getServer().getInfo().getName()), _("noPerm")); } checkArgument(comment.hasLastcommentCooledDown(args[0]), _("cooldownUnfinished")); comment.insertComment(args[0], reason, Type.WARNING, sender.getName()); if(target != null){ target.sendMessage(__("wasWarnedNotif", new String[] {reason})); } BAT.broadcast(_("warnBroadcast", new String[]{args[0], sender.getName(), reason}), Action.WARN_BROADCAST.getPermission()); return; }
@Override public void handle(Packet0KeepAlive alive) throws Exception { if (alive.getRandomId() == con.getSentPingId()) { int newPing = (int) (System.currentTimeMillis() - con.getSentPingTime()); bungee.getTabListHandler().onPingChange(con, newPing); con.setPing(newPing); } }
private void save() { try { try (FileWriter wr = new FileWriter(file)) { yaml.dump(config, wr); } } catch (IOException ex) { ProxyServer.getInstance().getLogger().log(Level.WARNING, "Could not save config", ex); } }
@Override public void addGroups(String... groups) { for (String group : groups) { this.groups.add(group); for (String permission : bungee.getConfigurationAdapter().getPermissions(group)) { setPermission(permission, true); } } }
@Override public void removeGroups(String... groups) { for (String group : groups) { this.groups.remove(group); for (String permission : bungee.getConfigurationAdapter().getPermissions(group)) { setPermission(permission, false); } } }
@Override public void save() { try (FileWriter wr = new FileWriter(file)) { yaml.dump(data, wr); } catch (IOException ex) { ProxyServer.getInstance() .getLogger() .log(Level.WARNING, "Could not save reconnect locations", ex); } }
@Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { if (handler != null) { handler.disconnected(channel); if (!(handler instanceof InitialHandler || handler instanceof PingHandler)) { ProxyServer.getInstance().getLogger().log(Level.INFO, "{0} has disconnected", handler); } } }
@Override protected ServerInfo getStoredServer(ProxiedPlayer player) { ServerInfo server = null; lock.readLock().lock(); try { server = ProxyServer.getInstance().getServerInfo(data.get(key(player))); } finally { lock.readLock().unlock(); } return server; }
private static void createNewPlayer(final ProxiedPlayer player) { String ip = player.getAddress().getAddress().toString(); final GSPlayer gsPlayer = new GSPlayer( player.getName(), (FeatureDetector.canUseUUID()) ? player.getUUID() : null, true); DatabaseManager.players.insertPlayer(gsPlayer, ip.substring(1, ip.length())); if (ConfigManager.main.NewPlayerBroadcast) { String welcomeMsg = null; sendBroadcast( welcomeMsg = ConfigManager.messages.NEW_PLAYER_BROADCAST.replace("{player}", player.getName())); // Firing custom event ProxyServer.getInstance() .getPluginManager() .callEvent(new NewPlayerJoinEvent(player.getName(), welcomeMsg)); } onlinePlayers.put(player.getName(), gsPlayer); LoggingManager.log(ConfigManager.messages.PLAYER_LOAD.replace("{player}", gsPlayer.getName())); if (ConfigManager.spawn.SpawnNewPlayerAtNewspawn && SpawnManager.NewPlayerSpawn != null) { SpawnManager.newPlayers.add(player); ProxyServer.getInstance() .getScheduler() .schedule( geSuit.instance, new Runnable() { @Override public void run() { SpawnManager.sendPlayerToNewPlayerSpawn(gsPlayer); SpawnManager.newPlayers.remove(player); } }, 300, TimeUnit.MILLISECONDS); } }
@Override public void onConnect() { for (ProxiedPlayer p : ProxyServer.getInstance().getPlayers()) { getPlayer() .unsafe() .sendPacket(new PacketC9PlayerListItem(p.getDisplayName(), true, (short) p.getPing())); } BungeeCord.getInstance() .broadcast( new PacketC9PlayerListItem( getPlayer().getDisplayName(), true, (short) getPlayer().getPing())); }
@EventHandler public void onJoin(final PostLoginEvent e) { final ProxiedPlayer p = e.getPlayer(); ProxyServer.getInstance() .getScheduler() .runAsync( plugin, () -> { TextComponent welcome = new TextComponent("Bienvenue, " + p.getName() + " !"); welcome.setColor(ChatColor.GOLD); String key = "rejoinlist:" + e.getPlayer().getUniqueId().toString(); Jedis cache = plugin.getConnector().getBungeeResource(); String srv = cache.get(key); cache.close(); if (srv != null) { final ServerInfo server = ProxyServer.getInstance().getServerInfo(srv); if (server != null) ProxyServer.getInstance() .getScheduler() .schedule( plugin, () -> e.getPlayer() .connect( server, (aBoolean, throwable) -> { if (aBoolean) { p.sendMessage( new ComponentBuilder("") .color(ChatColor.GREEN) .append("Vous avez été remis en jeu.") .create()); } }), 200L, TimeUnit.MILLISECONDS); } }); }
public void loadDB(final Callback<Boolean> dbState) { if (config.isMysql_enabled()) { getLogger().config("Starting connection to the mysql database ..."); final String username = config.getMysql_user(); final String password = config.getMysql_password(); final String database = config.getMysql_database(); final String port = config.getMysql_port(); final String host = config.getMysql_host(); // BoneCP can accept no database and we want to avoid that Preconditions.checkArgument(!"".equals(database), "You must set the database."); ProxyServer.getInstance() .getScheduler() .runAsync( this, new Runnable() { @Override public void run() { try { dsHandler = new DataSourceHandler(host, port, database, username, password); final Connection c = dsHandler.getConnection(); if (c != null) { c.close(); dbState.done(true, null); return; } } catch (final SQLException handledByDatasourceHandler) { } getLogger() .severe( "The connection pool (database connection)" + " wasn't able to be launched !"); dbState.done(false, null); } }); } // If MySQL is disabled, we are gonna use SQLite // Before initialize the connection, we must download the sqlite driver // (if it isn't already in the lib folder) and load it else { getLogger().config("Starting connection to the sqlite database ..."); getLogger() .warning( "It is strongly DISRECOMMENDED to use SQLite with BAT," + " as the SQLite implementation is less stable and much slower than the MySQL implementation."); if (loadSQLiteDriver()) { dsHandler = new DataSourceHandler(); dbState.done(true, null); } else { dbState.done(false, null); } } }
@Override public void handle(TabCompleteRequest tabComplete) throws Exception { if (tabComplete.getCursor().startsWith("/")) { List<String> results = new ArrayList<>(); bungee.getPluginManager().dispatchCommand(con, tabComplete.getCursor().substring(1), results); if (!results.isEmpty()) { con.unsafe() .sendPacket(new TabCompleteResponse(results.toArray(new String[results.size()]))); throw new CancelSendSignal(); } } }
@SuppressWarnings("unchecked") public YamlReconnectHandler() { try { file.createNewFile(); try (FileReader rd = new FileReader(file)) { data = yaml.loadAs(rd, Map.class); } } catch (YAMLException ex) { file.renameTo(new File("locations.yml.old")); ProxyServer.getInstance() .getLogger() .log(Level.WARNING, "Could not load reconnect locations, resetting them"); } catch (IOException ex) { ProxyServer.getInstance() .getLogger() .log(Level.WARNING, "Could not load reconnect locations", ex); } if (data == null) { data = new HashMap<>(); } }