Example #1
1
  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;
    }
  }
Example #2
0
  public void onEnable() {
    ProxyServer.getInstance().getPluginManager().registerListener(this, this);
    ps = ProxyServer.getInstance();

    // minequery ip, //minequery port

  }
Example #3
0
 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;
 }
Example #4
0
  @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();
    }
  }
Example #5
0
  @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");
    }
  }
Example #6
0
 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();
                     });
           });
 }
Example #7
0
 public static void sendMessageToTarget(String target, String message) {
   sendMessageToTarget(
       getPlayer(target) != null
           ? getPlayer(target).getProxiedPlayer()
           : ProxyServer.getInstance().getConsole(),
       message);
 }
Example #8
0
  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 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 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 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;
		}
 private static CommandSender getSender(String sender) {
   if (sender != null) {
     GSPlayer p = PlayerManager.getPlayer(sender);
     return (p == null ? ProxyServer.getInstance().getConsole() : p.getProxiedPlayer());
   }
   return null;
 }
Example #13
0
 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 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);
   }
 }
Example #15
0
  @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;
 }
Example #17
0
  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);
    }
  }
Example #18
0
 @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);
              }
            });
  }
Example #20
0
 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);
     }
   }
 }
  @Command(
      aliases = {"addserver"},
      desc = "Add a BungeeCord server",
      usage = "<name> <address> [port]",
      flags = "r",
      min = 2,
      max = 4)
  @CommandPermissions("bungeeutils.addserver")
  public static void addserver(final CommandContext args, CommandSender sender)
      throws CommandException {
    String name = args.getString(0);
    String address = args.getString(1);
    int port = args.argsLength() > 2 ? args.getInteger(2) : 25565;
    boolean restricted = args.hasFlag('r');

    ServerInfo serverInfo =
        ProxyServer.getInstance()
            .constructServerInfo(name, new InetSocketAddress(address, port), "", restricted);
    ProxyServer.getInstance().getServers().put(name, serverInfo);

    sender.sendMessage(ChatColor.GREEN + "Added server " + ChatColor.GOLD + name);
  }
  @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<>();
    }
  }
 @Command(
     aliases = {"hub", "lobby", "main"},
     desc = "Teleport to the lobby",
     min = 0,
     max = 0)
 public static void hub(final CommandContext args, CommandSender sender) throws CommandException {
   if (sender instanceof ProxiedPlayer) {
     ((ProxiedPlayer) sender).connect(ProxyServer.getInstance().getServers().get("default"));
     sender.sendMessage(ChatColor.GREEN + "Teleporting you to the lobby...");
   } else {
     sender.sendMessage(ChatColor.RED + "Only players may use this command");
   }
 }
Example #24
0
  @EventHandler
  public void onChat(ChatEvent event) {
    if (event.isCommand()) {
      CommandEvent commandEvent =
          new CommandEvent(
              BungeeUtilisals.getInstance().getUser((ProxiedPlayer) event.getSender()),
              event.getMessage());
      ProxyServer.getInstance().getPluginManager().callEvent(commandEvent);

      if (commandEvent.isCancelled()) {
        event.setCancelled(true);
      }
    }
  }
Example #25
0
 public static void logBungeeInfo(String msg) {
   TextComponent txp =
       new TextComponent(
           net.md_5.bungee.api.ChatColor.BLUE
               + "["
               + net.md_5.bungee.api.ChatColor.AQUA
               + LargeSkBungee.getPlugin().getDescription().getName()
               + " "
               + LargeSkBungee.getPlugin().getDescription().getVersion()
               + net.md_5.bungee.api.ChatColor.BLUE
               + "] "
               + net.md_5.bungee.api.ChatColor.RESET
               + msg);
   ProxyServer.getInstance().getConsole().sendMessage(txp);
 }
Example #26
0
  public void createServer(String server, String ip, String port) {
    InetSocketAddress address = new InetSocketAddress(ip, Integer.parseInt(port));

    ServerInfo info =
        ProxyServer.getInstance()
            .constructServerInfo(server, address, "Automatically added server", false);
    ProxyServer.getInstance().getServers().put(server, info);

    RemoteServer remoteServer = new RemoteServer(new Date(), server, info);
    this.servers.put(server, remoteServer);

    ProxyServer.getInstance()
        .getLogger()
        .info("[Servers] Created server " + server + ", " + ip + ":" + port);

    BungeeBridge.getInstance()
        .getExecutor()
        .addTask(
            () -> {
              Jedis jedis = BungeeBridge.getInstance().getConnector().getBungeeResource();
              jedis.srem("offlineservers", server);
              jedis.close();
            });
  }
 @SuppressWarnings("deprecation")
 public void run() {
   Collection<ProxiedPlayer> players = ProxyServer.getInstance().getPlayers();
   if (players.isEmpty()) {
     return;
   }
   for (ProxiedPlayer player : players) {
     for (String line : list.get(count).split("\n")) {
       player.sendMessage(line.replace("%p%", player.getName()));
     }
   }
   count++;
   if ((count + 1) > list.size()) {
     count = 0;
   }
 }
 /**
  * Sends the message to all online players on the server, as well as the console.
  *
  * @param args An optional array of arguments. If this is used they will be passed together with
  *     the message itself to the String.format() function, before the message gets send to the
  *     client. This can be used to add variable data into the message.
  */
 @SuppressWarnings("deprecation")
 @Override
 public void broadcast(@Nullable Object... args) {
   if (getSendMethod() == SendMethod.DISABLED) return;
   ProxyServer.getInstance()
       .getConsole()
       .sendMessage(
           (args != null && args.length > 0)
               ? String.format(fallback, args)
               : fallback); // Send the message to the console
   method
       .getSender()
       .doBroadcast(
           (args != null && args.length > 0) ? String.format(json, quoteArgs(args)) : json,
           optionalParameters);
 }
  @Command(
      aliases = {"delserver"},
      desc = "Remove a BungeeCord server",
      usage = "<name>",
      min = 1,
      max = 1)
  @CommandPermissions("bungeeutils.delserver")
  public static void delserver(final CommandContext args, CommandSender sender)
      throws CommandException {
    String name = args.getString(0);

    if (ProxyServer.getInstance().getServers().remove(name) == null) {
      sender.sendMessage(ChatColor.RED + "Could not find server " + ChatColor.GOLD + name);
    } else {
      sender.sendMessage(ChatColor.GREEN + "Removed server " + ChatColor.GOLD + name);
    }
  }
  @Override
  public void save() {
    Map<String, String> copy = new HashMap<>();
    lock.readLock().lock();
    try {
      copy.putAll(data);
    } finally {
      lock.readLock().unlock();
    }

    try (FileWriter wr = new FileWriter(file)) {
      yaml.dump(copy, wr);
    } catch (IOException ex) {
      ProxyServer.getInstance()
          .getLogger()
          .log(Level.WARNING, "Could not save reconnect locations", ex);
    }
  }