예제 #1
0
 public synchronized void lock(World world) {
   long time = world.getFullTime();
   unlock(world);
   int id =
       CommandBook.server()
           .getScheduler()
           .scheduleSyncRepeatingTask(
               CommandBook.inst(), new TimeLocker(world, time), 20, config.timeLockDelay);
   tasks.put(world.getName(), id);
 }
예제 #2
0
    @Command(
        aliases = {"banip", "ipban"},
        usage = "<target> [reason...]",
        desc = "Ban an IP address",
        flags = "st:",
        min = 1,
        max = -1)
    @CommandPermissions({"commandbook.bans.ban.ip"})
    public void banIP(CommandContext args, CommandSender sender) throws CommandException {

      String message = args.argsLength() >= 2 ? args.getJoinedStrings(1) : "Banned!";
      long endDate = args.hasFlag('t') ? CommandBookUtil.matchFutureDate(args.getFlag('t')) : 0L;

      String addr =
          args.getString(0).replace("\r", "").replace("\n", "").replace("\0", "").replace("\b", "");

      // Need to kick + log
      for (Player player : CommandBook.server().getOnlinePlayers()) {
        if (player.getAddress().getAddress().getHostAddress().equals(addr)) {
          player.kickPlayer(message);
          getBanDatabase().logKick(player, sender, message);
        }
      }

      getBanDatabase().ban(null, addr, sender, message, endDate);

      sender.sendMessage(ChatColor.YELLOW + addr + " banned.");

      if (!getBanDatabase().save()) {
        sender.sendMessage(ChatColor.RED + "Bans database failed to save. See console.");
      }
    }
예제 #3
0
  @Override
  public void enable() {
    config = configure(new LocalConfiguration());

    // Setup the ban database
    bans = new CSVBanDatabase(CommandBook.inst().getDataFolder());
    bans.load();
    if (FlatFileBanDatabase.toImport(CommandBook.inst().getDataFolder())) {
      BanDatabase banDb = new FlatFileBanDatabase(CommandBook.inst().getDataFolder(), this);
      banDb.load();
      bans.importFrom(banDb);
      final File oldBansFile = new File(CommandBook.inst().getDataFolder(), "banned_names.txt");
      oldBansFile.renameTo(new File(oldBansFile.getAbsolutePath() + ".old"));
    }
    CommandBook.registerEvents(this);
    registerCommands(Commands.class);
  }
예제 #4
0
  @Override
  public void enable() {
    CommandBook.inst().createDefaultConfiguration("kits.txt");

    // Setup kits
    kits = new FlatFileKitsManager(new File(CommandBook.inst().getDataFolder(), "kits.txt"));
    kits.load();

    CommandBook.server()
        .getScheduler()
        .scheduleAsyncRepeatingTask(
            CommandBook.inst(),
            new GarbageCollector(this),
            GarbageCollector.CHECK_FREQUENCY,
            GarbageCollector.CHECK_FREQUENCY);
    registerCommands(Commands.class);
  }
예제 #5
0
    @Command(
        aliases = {"kick"},
        usage = "<target> [reason...]",
        desc = "Kick a user",
        flags = "os",
        min = 1,
        max = -1)
    @CommandPermissions({"commandbook.kick"})
    public void kick(CommandContext args, CommandSender sender) throws CommandException {
      Iterable<Player> targets = PlayerUtil.matchPlayers(sender, args.getString(0));
      String message = args.argsLength() >= 2 ? args.getJoinedStrings(1) : "Kicked!";

      String broadcastPlayers = "";
      for (Player player : targets) {
        if (CommandBook.inst().hasPermission(player, "commandbook.kick.exempt")
            && !(args.hasFlag('o')
                && CommandBook.inst().hasPermission(sender, "commandbook.kick.exempt.override"))) {
          sender.sendMessage(
              ChatColor.RED
                  + "Player "
                  + player.getName()
                  + ChatColor.RED
                  + " is exempt from being kicked!");
          continue;
        }
        player.kickPlayer(message);
        broadcastPlayers += PlayerUtil.toColoredName(player, ChatColor.YELLOW) + " ";
        getBanDatabase().logKick(player, sender, message);
      }

      if (broadcastPlayers.length() > 0) {
        sender.sendMessage(ChatColor.YELLOW + "Player(s) kicked.");
        // Broadcast the Message
        if (config.broadcastKicks && !args.hasFlag('s')) {
          BasePlugin.server()
              .broadcastMessage(
                  ChatColor.YELLOW
                      + PlayerUtil.toColoredName(sender, ChatColor.YELLOW)
                      + " has kicked "
                      + broadcastPlayers
                      + " - "
                      + message);
        }
      }
    }
 /**
  * Check to see if god mode is enabled for a player.
  *
  * @param player The player to check
  * @return Whether the player has godmode through WorldGuard or CommandBook
  */
 public boolean hasGodMode(Player player) {
   if (hasCommandBookGodMode) {
     GodComponent god = CommandBook.inst().getComponentManager().getComponent(GodComponent.class);
     if (god != null) {
       return god.hasGodMode(player);
     }
   }
   return hasGodMode.contains(player.getName());
 }
예제 #7
0
 @EventHandler
 public void playerWhois(InfoComponent.PlayerWhoisEvent event) {
   if (CommandBook.inst().hasPermission(event.getSource(), "commandbook.bans.isbanned")) {
     event.addWhoisInformation(
         null,
         "Player "
             + (getBanDatabase().isBannedName(event.getPlayer().getName()) ? "is" : "is not")
             + " banned.");
   }
 }
 public void updateWorlds() {
   for (Iterator<Map.Entry<String, List<NamedLocation>>> i = unloadedLocs.entrySet().iterator();
       i.hasNext(); ) {
     Map.Entry<String, List<NamedLocation>> entry = i.next();
     World world = CommandBook.server().getWorld(entry.getKey());
     if (world == null) continue;
     i.remove();
     for (NamedLocation warp : entry.getValue()) {
       warp.getLocation().setWorld(world);
       locs.put(warp.getName().toLowerCase(), warp);
     }
   }
   for (Iterator<NamedLocation> i = locs.values().iterator(); i.hasNext(); ) {
     NamedLocation loc = i.next();
     if (CommandBook.server().getWorld(loc.getWorldName()) == null) {
       i.remove();
       getNestedList(unloadedLocs, loc.getWorldName()).add(loc);
     }
   }
 }
 @Override
 public boolean handle(AbstractComponent component, Field field, InjectComponent annotation) {
   try {
     Object target = CommandBook.inst().getComponentManager().getComponent(field.getType());
     if (target != null) {
       field.set(component, target);
       return true;
     }
   } catch (IllegalAccessException ignore) {
   }
   return false;
 }
예제 #10
0
  private void configureWorldLocks() {
    config = configure(new LocalConfiguration());

    if (config.timeLocks != null) {
      for (Map.Entry<String, Object> entry : config.timeLocks.entrySet()) {
        int time = 0;

        try {
          time = matchTime(String.valueOf(entry.getValue()));
        } catch (CommandException e) {
          CommandBook.logger()
              .warning("Time lock: Failed to parse time '" + entry.getValue() + "'");
          continue;
        }

        lockedTimes.put(entry.getKey(), time);

        World world = CommandBook.server().getWorld(entry.getKey());

        if (world == null) {
          CommandBook.logger().info("Could not time-lock unknown world '" + entry.getKey() + "'");
          continue;
        }

        world.setTime(time);
        lock(world);
        CommandBook.logger()
            .info(
                "Time locked to '"
                    + CommandBookUtil.getTimeString(time)
                    + "' for world '"
                    + world.getName()
                    + "'");
      }
    }
  }
예제 #11
0
  /**
   * Called on player login.
   *
   * @param event Relevant event details
   */
  @EventHandler(priority = EventPriority.NORMAL)
  public void playerLogin(PlayerLoginEvent event) {
    final Player player = event.getPlayer();

    if (!CommandBook.inst().hasPermission(player, "commandbook.bans.exempt")) {
      if (getBanDatabase().isBannedName(player.getName())) {
        event.disallow(
            PlayerLoginEvent.Result.KICK_BANNED,
            getBanDatabase().getBannedNameMessage(player.getName()));
      } else if (getBanDatabase().isBannedAddress(event.getAddress())) {
        event.disallow(
            PlayerLoginEvent.Result.KICK_BANNED,
            getBanDatabase().getBannedAddressMessage(event.getAddress().getHostAddress()));
      }
    }
  }
예제 #12
0
  /** Called when a World is loaded. */
  @EventHandler
  public void onWorldLoad(WorldLoadEvent event) {
    World world = event.getWorld();
    Integer lockedTime = getLockedTimes().get(world.getName());

    if (lockedTime != null) {
      world.setTime(lockedTime);
      lock(world);
      CommandBook.logger()
          .info(
              "Time locked to '"
                  + CommandBookUtil.getTimeString(lockedTime)
                  + "' for world '"
                  + world.getName()
                  + "'");
    }
  }
예제 #13
0
 @Override
 public void enable() {
   configureWorldLocks();
   registerCommands(Commands.class);
   CommandBook.registerEvents(this);
 }
예제 #14
0
    @Command(
        aliases = {"playertime"},
        usage = "[filter] <time|\"current\">",
        desc = "Get/change a player's time",
        flags = "rsw",
        min = 0,
        max = 2)
    public void playertime(CommandContext args, CommandSender sender) throws CommandException {
      Iterable<Player> players = null;
      String timeStr = "current";
      boolean included = false;
      boolean reset = args.hasFlag('r');

      if (args.argsLength() < 2) {
        if (args.argsLength() == 1) {
          timeStr = args.getString(0);
          if (reset) {
            players = PlayerUtil.matchPlayers(sender, timeStr);
          }
        }

        if (players == null) {
          players = PlayerUtil.matchPlayers(PlayerUtil.checkPlayer(sender));
        }
      } else {
        players = PlayerUtil.matchPlayers(sender, args.getString(0));
        timeStr = args.getString(1);
      }

      for (Player player : players) {
        if (player != sender) {
          CommandBook.inst().checkPermission(sender, "commandbook.time.player.other");
          break;
        } else {
          CommandBook.inst().checkPermission(sender, "commandbook.time.player");
        }
      }

      if (args.hasFlag('r')) {
        for (Player player : players) {
          player.resetPlayerTime();
          if (!args.hasFlag('s')) {
            player.sendMessage(ChatColor.YELLOW + "Your time was reset to world time");
          }
          if (sender instanceof Player && sender.equals(player)) {
            included = true;
          }
        }
        if (!included) {
          sender.sendMessage(ChatColor.YELLOW + "Player times reset");
        }
        return;
      }

      if (timeStr.equalsIgnoreCase("current")
          || timeStr.equalsIgnoreCase("cur")
          || timeStr.equalsIgnoreCase("now")) {
        CommandBook.inst().checkPermission(sender, "commandbook.time.player.check");
        sender.sendMessage(
            ChatColor.YELLOW
                + "Player Time: "
                + CommandBookUtil.getTimeString(
                    PlayerUtil.matchSinglePlayer(
                            sender, args.getString(0, PlayerUtil.checkPlayer(sender).getName()))
                        .getPlayerTime()));
        return;
      }

      for (Player player : players) {
        if (!player.equals(sender)) {
          player.sendMessage(
              ChatColor.YELLOW
                  + "Your time set to "
                  + CommandBookUtil.getTimeString(player.getPlayerTime()));
        } else {
          player.sendMessage(
              ChatColor.YELLOW
                  + "Your time set to "
                  + CommandBookUtil.getTimeString(player.getPlayerTime()));
          included = true;
        }
        player.setPlayerTime(
            args.hasFlag('w') ? Integer.parseInt(timeStr) : matchTime(timeStr), args.hasFlag('w'));
      }
      if (!included) {
        sender.sendMessage(
            ChatColor.YELLOW
                + "Player times set to "
                + CommandBookUtil.getTimeString(matchTime(timeStr)));
      }
    }
예제 #15
0
    @Command(
        aliases = {"time"},
        usage = "[world] <time|\"current\">",
        desc = "Get/change the world time",
        flags = "l",
        min = 0,
        max = 2)
    public void time(CommandContext args, CommandSender sender) throws CommandException {

      World world;
      String timeStr;
      boolean onlyLock = false;

      // Easy way to get the time
      if (args.argsLength() == 0) {
        world = PlayerUtil.checkPlayer(sender).getWorld();
        timeStr = "current";
        // If no world was specified, get the world from the sender, but
        // fail if the sender isn't player
      } else if (args.argsLength() == 1) {
        world = PlayerUtil.checkPlayer(sender).getWorld();
        timeStr = args.getString(0);
      } else { // A world was specified!
        world = LocationUtil.matchWorld(sender, args.getString(0));
        timeStr = args.getString(1);
      }

      // Let the player get the time
      if (timeStr.equalsIgnoreCase("current")
          || timeStr.equalsIgnoreCase("cur")
          || timeStr.equalsIgnoreCase("now")) {

        // We want to lock to the current time
        if (!args.hasFlag('l')) {
          CommandBook.inst().checkPermission(sender, "commandbook.time.check");
          sender.sendMessage(
              ChatColor.YELLOW + "Time: " + CommandBookUtil.getTimeString(world.getTime()));
          return;
        }

        onlyLock = true;
      }

      CommandBook.inst().checkPermission(sender, "commandbook.time");

      if (!onlyLock) {
        unlock(world);
        world.setTime(matchTime(timeStr));
      }

      String verb = "set";

      // Locking
      if (args.hasFlag('l')) {
        CommandBook.inst().checkPermission(sender, "commandbook.time.lock");
        lock(world);
        verb = "locked";
      }

      if (CommandBook.inst().broadcastChanges) {
        CommandBook.server()
            .broadcastMessage(
                ChatColor.YELLOW
                    + PlayerUtil.toName(sender)
                    + " "
                    + verb
                    + " the time of '"
                    + world.getName()
                    + "' to "
                    + CommandBookUtil.getTimeString(world.getTime())
                    + ".");
      } else {
        sender.sendMessage(
            ChatColor.YELLOW
                + "Time "
                + verb
                + " to "
                + CommandBookUtil.getTimeString(world.getTime())
                + ".");
      }
    }
예제 #16
0
    @Command(
        aliases = {"ban"},
        usage = "[-t end ] <target> [reason...]",
        desc = "Ban a user or IP address (with the -i flag)",
        flags = "set:o",
        min = 1,
        max = -1)
    @CommandPermissions({"commandbook.bans.ban"})
    public void ban(CommandContext args, CommandSender sender) throws CommandException {
      String banName;
      String banAddress = null;
      long endDate = args.hasFlag('t') ? CommandBookUtil.matchFutureDate(args.getFlag('t')) : 0L;
      String message = args.argsLength() >= 2 ? args.getJoinedStrings(1) : "Banned!";

      final boolean hasExemptOverride =
          args.hasFlag('o')
              && CommandBook.inst().hasPermission(sender, "commandbook.bans.exempt.override");
      // Check if it's a player in the server right now
      try {
        Player player;

        // Exact mode matches names exactly
        if (args.hasFlag('e')) {
          player = PlayerUtil.matchPlayerExactly(sender, args.getString(0));
        } else {
          player = PlayerUtil.matchSinglePlayer(sender, args.getString(0));
        }

        if (CommandBook.inst().hasPermission(player, "commandbook.bans.exempt")
            && !hasExemptOverride) {
          throw new CommandException(
              "This player is exempt from being banned! "
                  + "(use -o flag to override if you have commandbook.bans.exempt.override)");
        }

        // Need to kick + log
        player.kickPlayer(message);
        getBanDatabase().logKick(player, sender, message);

        banName = player.getName();

        sender.sendMessage(
            ChatColor.YELLOW
                + player.getName()
                + " ("
                + player.getDisplayName()
                + ChatColor.YELLOW
                + ") banned and kicked.");
      } catch (CommandException e) {
        banName =
            args.getString(0)
                .replace("\r", "")
                .replace("\n", "")
                .replace("\0", "")
                .replace("\b", "");

        sender.sendMessage(ChatColor.YELLOW + banName + " banned.");
      }

      // Broadcast the Message
      if (config.broadcastBans && !args.hasFlag('s')) {
        CommandBook.server()
            .broadcastMessage(
                ChatColor.YELLOW
                    + PlayerUtil.toColoredName(sender, ChatColor.YELLOW)
                    + " has banned "
                    + banName
                    + " - "
                    + message);
      }

      getBanDatabase().ban(banName, banAddress, sender, message, endDate);

      if (!getBanDatabase().save()) {
        sender.sendMessage(ChatColor.RED + "Bans database failed to save. See console.");
      }
    }
예제 #17
0
 public synchronized void unlock(World world) {
   Integer id = tasks.get(world.getName());
   if (id != null) {
     CommandBook.server().getScheduler().cancelTask(id);
   }
 }
  public void load() throws IOException {
    FileInputStream input = null;
    Map<String, NamedLocation> locs = new HashMap<String, NamedLocation>();

    file.getParentFile().mkdirs();
    if (!file.exists()) {
      file.createNewFile();
    }

    try {
      input = new FileInputStream(file);
      InputStreamReader streamReader = new InputStreamReader(input, "utf-8");
      BufferedReader reader = new BufferedReader(streamReader);

      CSVReader csv = new CSVReader(reader);
      String[] line;
      while ((line = csv.readNext()) != null) {
        if (line.length < 7) {
          logger.warning("CommandBook: " + type + " data file has an invalid line with < 7 fields");
        } else {
          try {
            String name = line[0].trim().replace(" ", "");
            String worldName = line[1]; // Set to null if the world exists
            String creator = line[2];
            double x = Double.parseDouble(line[3]);
            double y = Double.parseDouble(line[4]);
            double z = Double.parseDouble(line[5]);
            float pitch = Float.parseFloat(line[6]);
            float yaw = Float.parseFloat(line[7]);

            World world = CommandBook.server().getWorld(worldName);

            if (world != null) {
              // We shouldn't have this warp
              if (castWorld != null && !castWorld.equals(world)) {
                continue;
              }
            }

            Location loc = new Location(world, x, y, z, yaw, pitch);
            NamedLocation warp = new NamedLocation(name, loc);
            warp.setWorldName(worldName);
            warp.setCreatorName(creator);
            if (world == null) {
              getNestedList(unloadedLocs, worldName).add(warp);
            } else {
              locs.put(name.toLowerCase(), warp);
            }
          } catch (NumberFormatException e) {
            logger.warning(
                "CommandBook: "
                    + type
                    + " data file has an invalid line with non-numeric numeric fields");
          }
        }
      }

      this.locs = locs;

      if (castWorld != null) {
        logger.info(
            "CommandBook: " + locs.size() + " " + type + "(s) loaded for " + castWorld.getName());
      } else {
        logger.info("CommandBook: " + locs.size() + " " + type + "(s) loaded");
      }
    } finally {
      if (input != null) {
        try {
          input.close();
        } catch (IOException e) {
        }
      }
    }
  }
예제 #19
0
    @Command(
        aliases = {"kit"},
        usage = "<id> [target]",
        desc = "Get a kit",
        flags = "",
        min = 0,
        max = 2)
    public void kit(CommandContext args, CommandSender sender) throws CommandException {
      // List kits
      if (args.argsLength() == 0) {
        CommandBook.inst().checkPermission(sender, "commandbook.kit.list");

        Map<String, Kit> kits = getKitManager().getKits();

        if (kits.size() == 0) {
          throw new CommandException("No kits are configured.");
        }

        StringBuilder str = new StringBuilder();
        int count = 0;

        for (String id : kits.keySet()) {
          if (!CommandBook.inst()
              .hasPermission(sender, "commandbook.kit.kits." + id.replace(".", ""))) {
            continue;
          }

          if (str.length() != 0) {
            str.append(", ");
          }

          str.append(id);
          count++;
        }

        if (count == 0) {
          throw new CommandException("You have access to no kits.");
        }

        sender.sendMessage(
            ChatColor.YELLOW + "Kits (" + count + "): " + ChatColor.WHITE + str.toString());
        sender.sendMessage(ChatColor.YELLOW + "Use /kit kitname to get a kit.");

        // Give a kit
      } else {
        Iterable<Player> targets;
        String id = args.getString(0).toLowerCase();
        boolean included = false;

        if (args.argsLength() == 2) {
          targets = PlayerUtil.matchPlayers(sender, args.getString(1));
        } else {
          targets = PlayerUtil.matchPlayers(PlayerUtil.checkPlayer(sender));
        }

        for (Player player : targets) {
          if (player != sender) {
            // Check permissions!
            CommandBook.inst().checkPermission(sender, "commandbook.kit.other");
          }
        }

        Kit kit = getKitManager().getKit(id);

        if (kit == null) {
          throw new CommandException("No kit by that name exists.");
        }

        CommandBook.inst().checkPermission(sender, "commandbook.kit.kits." + id.replace(".", ""));

        for (Player player : targets) {
          boolean success = kit.distribute(player);

          // Tell the user
          if (player.equals(sender)) {
            if (success) {
              player.sendMessage(ChatColor.YELLOW + "Kit '" + id + "' given!");
            } else {
              player.sendMessage(
                  ChatColor.RED + "You have to wait before you can get this kit again.");
            }

            included = true;
          } else {
            if (success) {
              player.sendMessage(
                  ChatColor.YELLOW
                      + "You've been given "
                      + "the '"
                      + id
                      + "' kit by "
                      + PlayerUtil.toColoredName(sender, ChatColor.YELLOW)
                      + ".");
            } else {
              player.sendMessage(
                  ChatColor.RED + "A kit could not be given to you because it has been too soon.");
            }
          }
        }

        // The player didn't receive any items, then we need to send the
        // user a message so s/he know that something is indeed working
        if (!included) {
          sender.sendMessage(ChatColor.YELLOW + "Kits given.");
        }
      }
    }