Search in sources :

Example 1 with ShopManager

use of de.Keyle.MyPet.util.shop.ShopManager in project MyPet by xXKeyleXx.

the class MyPetPlugin method onEnable.

public void onEnable() {
    this.isReady = false;
    Updater updater = new Updater("MyPet");
    updater.update();
    if (compatUtil.getInternalVersion() == null || !MyPetVersion.isValidBukkitPacket(compatUtil.getInternalVersion())) {
        getLogger().warning("This version of MyPet is not compatible with \"" + compatUtil.getInternalVersion() + "\". Is MyPet up to date?");
        updater.waitForDownload();
        setEnabled(false);
        return;
    }
    serviceManager.activate(Load.State.OnEnable);
    entityRegistry.registerEntityTypes();
    if (getLogger() instanceof MyPetLogger) {
        ((MyPetLogger) getLogger()).updateDebugLoggerLogLevel();
    }
    compatManager.enable();
    getLogger().info("Compat mode for " + compatUtil.getInternalVersion() + " loaded.");
    ConfigurationLoader.loadCompatConfiguration();
    // register leash flags
    registerLeashFlags();
    // register skilltree requirementSettings
    registerSkilltreeRequirements();
    // register exp calculators
    if (!new File(getDataFolder(), "exp.js").exists()) {
        platformHelper.copyResource(this, "exp.js", new File(getDataFolder(), "exp.js"));
    }
    serviceManager.getService(ExperienceCalculatorManager.class).ifPresent(calculatorManager -> {
        calculatorManager.registerCalculator("JS", JavaScriptExperienceCalculator.class);
        calculatorManager.registerCalculator("JavaScript", JavaScriptExperienceCalculator.class);
        calculatorManager.switchCalculator(Configuration.LevelSystem.CALCULATION_MODE.toLowerCase());
    });
    // register event listener
    PlayerListener playerListener = new PlayerListener();
    getServer().getPluginManager().registerEvents(playerListener, this);
    VehicleListener vehicleListener = new VehicleListener();
    getServer().getPluginManager().registerEvents(vehicleListener, this);
    EntityListener entityListener = new EntityListener();
    getServer().getPluginManager().registerEvents(entityListener, this);
    MyPetEntityListener myPetEntityListener = new MyPetEntityListener();
    getServer().getPluginManager().registerEvents(myPetEntityListener, this);
    LevelListener levelupListener = new LevelListener();
    getServer().getPluginManager().registerEvents(levelupListener, this);
    WorldListener worldListener = new WorldListener();
    getServer().getPluginManager().registerEvents(worldListener, this);
    // register commands
    getCommand("petname").setExecutor(new CommandName());
    getCommand("petcall").setExecutor(new CommandCall());
    getCommand("petsendaway").setExecutor(new CommandSendAway());
    getCommand("petstop").setExecutor(new CommandStop());
    getCommand("petrelease").setExecutor(new CommandRelease());
    getCommand("mypet").setExecutor(new CommandHelp());
    getCommand("petinventory").setExecutor(new CommandInventory());
    getCommand("petpickup").setExecutor(new CommandPickup());
    getCommand("petbehavior").setExecutor(new CommandBehavior());
    getCommand("petinfo").setExecutor(new CommandInfo());
    getCommand("mypetadmin").setExecutor(new CommandAdmin());
    getCommand("petskill").setExecutor(new CommandSkill());
    getCommand("petchooseskilltree").setExecutor(new CommandChooseSkilltree());
    getCommand("petbeacon").setExecutor(new CommandBeacon());
    getCommand("petrespawn").setExecutor(new CommandRespawn());
    getCommand("petsettings").setExecutor(new CommandSettings());
    getCommand("petswitch").setExecutor(new CommandSwitch());
    getCommand("petstore").setExecutor(new CommandStore());
    getCommand("petlist").setExecutor(new CommandList());
    getCommand("petcapturehelper").setExecutor(new CommandCaptureHelper());
    getCommand("pettrade").setExecutor(new CommandTrade());
    getCommand("petshop").setExecutor(new CommandShop());
    // load worldgroups
    WorldGroup.loadGroups(new File(getDataFolder().getPath(), "worldgroups.yml"));
    // register skills
    registerSkills();
    // create folders
    File skilltreeFolder = new File(getDataFolder().getPath(), "skilltrees");
    getDataFolder().mkdirs();
    boolean createDefaultSkilltree = skilltreeFolder.mkdirs();
    boolean createLocaleReadme = new File(getDataFolder(), "locale").mkdirs();
    new File(getDataFolder(), "logs").mkdirs();
    if (!createDefaultSkilltree) {
        File legacyDefaultSkilltree = new File(skilltreeFolder, "default.st");
        if (legacyDefaultSkilltree.exists()) {
            if (Util.getSha256FromFile(legacyDefaultSkilltree) == -4323392001800132707L) {
                createDefaultSkilltree = true;
                legacyDefaultSkilltree.delete();
            }
        }
    }
    if (createDefaultSkilltree) {
        File skilltreeFile = new File(skilltreeFolder, "Combat.st.json");
        if (!skilltreeFile.exists()) {
            platformHelper.copyResource(this, "skilltrees/Combat.st.json", new File(skilltreeFolder, "Combat.st.json"));
        }
        skilltreeFile = new File(skilltreeFolder, "Farm.st.json");
        if (!skilltreeFile.exists()) {
            platformHelper.copyResource(this, "skilltrees/Farm.st.json", new File(skilltreeFolder, "Farm.st.json"));
        }
        skilltreeFile = new File(skilltreeFolder, "PvP.st.json");
        if (!skilltreeFile.exists()) {
            platformHelper.copyResource(this, "skilltrees/PvP.st.json", new File(skilltreeFolder, "PvP.st.json"));
        }
        skilltreeFile = new File(skilltreeFolder, "Ride.st.json");
        if (!skilltreeFile.exists()) {
            platformHelper.copyResource(this, "skilltrees/Ride.st.json", new File(skilltreeFolder, "Ride.st.json"));
        }
        skilltreeFile = new File(skilltreeFolder, "Utility.st.json");
        if (!skilltreeFile.exists()) {
            platformHelper.copyResource(this, "skilltrees/Utility.st.json", new File(skilltreeFolder, "Utility.st.json"));
        }
        MyPetApi.getLogger().info("Default skilltree files created.");
    }
    // load skilltrees
    MyPetApi.getSkilltreeManager().clearSkilltrees();
    SkillTreeLoaderJSON.loadSkilltrees(new File(getDataFolder(), "skilltrees"));
    for (int i = 0; i <= Configuration.Misc.MAX_STORED_PET_COUNT; i++) {
        try {
            Bukkit.getPluginManager().addPermission(new Permission("MyPet.petstorage.limit." + i));
        } catch (Exception ignored) {
        }
    }
    if (createLocaleReadme) {
        platformHelper.copyResource(this, "locale-readme.txt", new File(getDataFolder(), "locale" + File.separator + "readme.txt"));
    }
    Translation.init();
    for (Team team : Bukkit.getScoreboardManager().getMainScoreboard().getTeams()) {
        if (team.getName().startsWith("MyPet-")) {
            team.unregister();
        }
    }
    // init repository
    if (Configuration.Repository.REPOSITORY_TYPE.equalsIgnoreCase("NBT")) {
        Configuration.Repository.REPOSITORY_TYPE = "SQLite";
        Configuration.Repository.CONVERT_FROM = "NBT";
        repo = new SqLiteRepository();
        try {
            repo.init();
        } catch (RepositoryInitException e) {
            e.printStackTrace();
            repo = null;
        }
    } else if (Configuration.Repository.REPOSITORY_TYPE.equalsIgnoreCase("MySQL")) {
        MyPetApi.getLogger().info("Connect to MySQL database...");
        repo = new MySqlRepository();
        try {
            repo.init();
            MyPetApi.getLogger().info("MySQL connection successful.");
        } catch (RepositoryInitException e) {
            MyPetApi.getLogger().warning("MySQL connection failed!");
            e.printStackTrace();
            repo = null;
        }
    } else if (Configuration.Repository.REPOSITORY_TYPE.equalsIgnoreCase("MongoDB")) {
        MyPetApi.getLogger().info("Connect to MongoDB database...");
        repo = new MongoDbRepository();
        try {
            repo.init();
            MyPetApi.getLogger().info("MongoDB connection successful.");
        } catch (RepositoryInitException e) {
            MyPetApi.getLogger().warning("MongoDB connection failed!");
            e.printStackTrace();
            repo = null;
        }
    }
    if (repo == null) {
        MyPetApi.getLogger().info("Connect to SQLite database...");
        repo = new SqLiteRepository();
        try {
            repo.init();
            MyPetApi.getLogger().info("SQLite connection successful.");
        } catch (RepositoryInitException ignored) {
            MyPetApi.getLogger().warning("SQLite connection failed!");
            setEnabled(false);
            return;
        }
    }
    Converter.convert();
    if (repo instanceof Scheduler) {
        Timer.addTask((Scheduler) repo);
    }
    File shopConfig = new File(getDataFolder(), "pet-shops.yml");
    if (!shopConfig.exists()) {
        platformHelper.copyResource(this, "pet-shops.yml", shopConfig);
    }
    new ShopManager();
    Timer.startTimer();
    updater.waitForDownload();
    pluginHookManager.enableHooks();
    serviceManager.activate(Load.State.AfterHooks);
    // init Metrics
    try {
        Metrics metrics = new Metrics(this, 778);
        if (metrics.isEnabled()) {
            metrics.addCustomChart(new Metrics.SingleLineChart("active_pets", () -> myPetManager.countActiveMyPets()));
            metrics.addCustomChart(new Metrics.SimplePie("build", MyPetVersion::getBuild));
            metrics.addCustomChart(new Metrics.SimplePie("update_mode", () -> {
                String mode = "Disabled";
                if (Configuration.Update.CHECK) {
                    mode = "Check";
                    if (Configuration.Update.DOWNLOAD) {
                        mode += " & Download";
                    }
                }
                return mode;
            }));
            metrics.addCustomChart(new Metrics.AdvancedPie("hooks", () -> {
                Map<String, Integer> activatedHooks = new HashMap<>();
                for (PluginHook hook : MyPetApi.getPluginHookManager().getHooks()) {
                    activatedHooks.put(hook.getPluginName(), 1);
                }
                return activatedHooks;
            }));
        }
    } catch (Throwable e) {
        errorReporter.sendError(e, "Init Metrics failed");
    }
    getLogger().info("Version " + MyPetVersion.getVersion() + "-b" + MyPetVersion.getBuild() + ChatColor.GREEN + " ENABLED");
    this.isReady = true;
    serviceManager.activate(Load.State.OnReady);
    // load pets for online players
    new BukkitRunnable() {

        @Override
        public void run() {
            for (final Player player : getServer().getOnlinePlayers()) {
                repo.getMyPetPlayer(player, new RepositoryCallback<MyPetPlayer>() {

                    @Override
                    public void callback(final MyPetPlayer p) {
                        if (p != null) {
                            final MyPetPlayerImpl onlinePlayer = (MyPetPlayerImpl) p;
                            onlinePlayer.setLastKnownName(player.getName());
                            if (!player.getUniqueId().equals(onlinePlayer.getOfflineUUID())) {
                                if (onlinePlayer.getMojangUUID() == null) {
                                    onlinePlayer.setMojangUUID(player.getUniqueId());
                                }
                                onlinePlayer.setOnlineMode(true);
                            }
                            playerManager.setOnline(onlinePlayer);
                            final WorldGroup joinGroup = WorldGroup.getGroupByWorld(player.getWorld().getName());
                            if (joinGroup.isDisabled()) {
                                return;
                            }
                            if (onlinePlayer.hasMyPet()) {
                                MyPet myPet = onlinePlayer.getMyPet();
                                if (!myPet.getWorldGroup().equals(joinGroup.getName())) {
                                    myPetManager.deactivateMyPet(onlinePlayer, true);
                                }
                            }
                            if (!onlinePlayer.hasMyPet() && onlinePlayer.hasMyPetInWorldGroup(joinGroup.getName())) {
                                final UUID petUUID = onlinePlayer.getMyPetForWorldGroup(joinGroup.getName());
                                MyPetApi.getRepository().getMyPet(petUUID, new RepositoryCallback<StoredMyPet>() {

                                    @Override
                                    public void callback(StoredMyPet storedMyPet) {
                                        myPetManager.activateMyPet(storedMyPet);
                                        if (onlinePlayer.hasMyPet()) {
                                            final MyPet myPet = onlinePlayer.getMyPet();
                                            final MyPetPlayer myPetPlayer = myPet.getOwner();
                                            if (myPet.wantsToRespawn()) {
                                                if (myPetPlayer.hasMyPet()) {
                                                    MyPet runMyPet = myPetPlayer.getMyPet();
                                                    switch(runMyPet.createEntity()) {
                                                        case Canceled:
                                                            runMyPet.getOwner().sendMessage(Util.formatText(Translation.getString("Message.Spawn.Prevent", myPet.getOwner()), runMyPet.getPetName()));
                                                            break;
                                                        case NoSpace:
                                                            runMyPet.getOwner().sendMessage(Util.formatText(Translation.getString("Message.Spawn.NoSpace", myPet.getOwner()), runMyPet.getPetName()));
                                                            break;
                                                        case NotAllowed:
                                                            runMyPet.getOwner().sendMessage(Util.formatText(Translation.getString("Message.No.AllowedHere", myPet.getOwner()), myPet.getPetName()));
                                                            break;
                                                        case Dead:
                                                            if (Configuration.Respawn.DISABLE_AUTO_RESPAWN) {
                                                                runMyPet.getOwner().sendMessage(Util.formatText(Translation.getString("Message.Call.Dead", myPet.getOwner()), myPet.getPetName()));
                                                            } else {
                                                                runMyPet.getOwner().sendMessage(Util.formatText(Translation.getString("Message.Spawn.Respawn.In", myPet.getOwner()), myPet.getPetName(), myPet.getRespawnTime()));
                                                            }
                                                            break;
                                                        case Flying:
                                                            runMyPet.getOwner().sendMessage(Util.formatText(Translation.getString("Message.Spawn.Flying", myPet.getOwner()), myPet.getPetName()));
                                                            break;
                                                        case Success:
                                                            runMyPet.getOwner().sendMessage(Util.formatText(Translation.getString("Message.Command.Call.Success", myPet.getOwner()), runMyPet.getPetName()));
                                                            break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                });
                            }
                            onlinePlayer.checkForDonation();
                        }
                    }
                });
            }
        }
    }.runTaskLater(this, 0);
}
Also used : MySqlRepository(de.Keyle.MyPet.repository.types.MySqlRepository) MyPetPlayerImpl(de.Keyle.MyPet.util.player.MyPetPlayerImpl) Metrics(org.bstats.bukkit.Metrics) Updater(de.Keyle.MyPet.util.Updater) Permission(org.bukkit.permissions.Permission) ShopManager(de.Keyle.MyPet.util.shop.ShopManager) UUID(java.util.UUID) StoredMyPet(de.Keyle.MyPet.api.entity.StoredMyPet) Player(org.bukkit.entity.Player) MyPetPlayer(de.Keyle.MyPet.api.player.MyPetPlayer) MongoDbRepository(de.Keyle.MyPet.repository.types.MongoDbRepository) MyPetLogger(de.Keyle.MyPet.api.util.logger.MyPetLogger) PluginHook(de.Keyle.MyPet.api.util.hooks.PluginHook) SqLiteRepository(de.Keyle.MyPet.repository.types.SqLiteRepository) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) MyPetPlayer(de.Keyle.MyPet.api.player.MyPetPlayer) MyPet(de.Keyle.MyPet.api.entity.MyPet) StoredMyPet(de.Keyle.MyPet.api.entity.StoredMyPet) Team(org.bukkit.scoreboard.Team) ExperienceCalculatorManager(de.Keyle.MyPet.api.skill.experience.ExperienceCalculatorManager) BukkitRunnable(org.bukkit.scheduler.BukkitRunnable)

Example 2 with ShopManager

use of de.Keyle.MyPet.util.shop.ShopManager in project MyPet by xXKeyleXx.

the class CommandShop method onCommand.

public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (!MyPetApi.getHookHelper().isEconomyEnabled()) {
        sender.sendMessage(Translation.getString("Message.No.Economy", sender));
        return true;
    }
    Player player = null;
    if (sender instanceof ConsoleCommandSender && args.length < 2) {
        sender.sendMessage("You can't use this command from server console!");
        return true;
    }
    if (sender instanceof Player) {
        if (WorldGroup.getGroupByWorld(((Player) sender).getWorld()).isDisabled()) {
            sender.sendMessage(Translation.getString("Message.No.AllowedHere", sender));
            return true;
        }
    }
    if (args.length > 1) {
        if (!(sender instanceof Player) || Permissions.has((Player) sender, "MyPet.admin")) {
            player = Bukkit.getPlayer(args[1]);
            if (player == null || !player.isOnline()) {
                sender.sendMessage("[" + ChatColor.AQUA + "MyPet" + ChatColor.RESET + "] " + Translation.getString("Message.No.PlayerOnline", sender));
                return true;
            }
        }
    }
    if (player == null) {
        if (!(sender instanceof Player)) {
            sender.sendMessage("You can't use this command from server console!");
            return true;
        }
        player = (Player) sender;
    }
    final Optional<ShopManager> shopManager = MyPetApi.getServiceManager().getService(ShopManager.class);
    if (shopManager.isPresent()) {
        if (args.length > 0) {
            String shop = args[0];
            if (Permissions.has(player, "MyPet.shop.access." + shop) || Permissions.has(player, "MyPet.admin")) {
                shopManager.get().open(shop, player);
            } else {
                player.sendMessage(Translation.getString("Message.No.Allowed", player));
            }
        } else {
            String shop = shopManager.get().getDefaultShopName();
            if (shop != null) {
                if (Permissions.has(player, "MyPet.shop.access." + shop) || Permissions.has(player, "MyPet.admin")) {
                    shopManager.get().open(player);
                    return true;
                }
            } else {
                final List<String> availableShops = getAvailablePetShops(player);
                if (availableShops != null && availableShops.size() > 0) {
                    final Player finalPlayer = player;
                    Map<Integer, String> shops = new HashMap<>();
                    IconMenu menu = new IconMenu(Translation.getString("Message.Shop.Available", player), event -> {
                        String shopname = shops.get(event.getPosition());
                        if (shopname != null) {
                            final String finalShopname = shopname;
                            new BukkitRunnable() {

                                @Override
                                public void run() {
                                    shopManager.get().open(finalShopname, finalPlayer);
                                }
                            }.runTaskLater(MyPetApi.getPlugin(), 5L);
                            event.setWillClose(true);
                            event.setWillDestroy(true);
                        }
                    }, MyPetApi.getPlugin());
                    ItemDatabase itemDatabase = MyPetApi.getServiceManager().getService(ItemDatabase.class).get();
                    for (String shopname : availableShops) {
                        PetShop s = shopManager.get().getShop(shopname);
                        IconMenuItem icon = new IconMenuItem();
                        icon.setTitle(RESET + Colorizer.setColors(s.getDisplayName()));
                        SkilltreeIcon si = s.getIcon();
                        MaterialHolder material = itemDatabase.getByID(si.getMaterial());
                        if (material == null) {
                            material = itemDatabase.getByID("chest");
                        }
                        icon.setMaterial(material.getMaterial()).setGlowing(si.isGlowing());
                        if (material.isLegacy()) {
                            icon.setData(material.getLegacyId().getData());
                        }
                        if (Util.isBetween(0, 53, s.getPosition())) {
                            menu.setOption(s.getPosition(), icon);
                            shops.put(s.getPosition(), s.getName());
                        } else {
                            shops.put(menu.addOption(icon), s.getName());
                        }
                    }
                    menu.open(player);
                    return true;
                }
            }
            player.sendMessage(Translation.getString("Message.No.Allowed", player));
        }
    }
    return true;
}
Also used : PetShop(de.Keyle.MyPet.util.shop.PetShop) Player(org.bukkit.entity.Player) IconMenu(de.Keyle.MyPet.api.gui.IconMenu) ItemDatabase(de.Keyle.MyPet.api.util.inventory.material.ItemDatabase) BukkitRunnable(org.bukkit.scheduler.BukkitRunnable) MaterialHolder(de.Keyle.MyPet.api.util.inventory.material.MaterialHolder) ConsoleCommandSender(org.bukkit.command.ConsoleCommandSender) SkilltreeIcon(de.Keyle.MyPet.api.skill.skilltree.SkilltreeIcon) ShopManager(de.Keyle.MyPet.util.shop.ShopManager) IconMenuItem(de.Keyle.MyPet.api.gui.IconMenuItem)

Aggregations

ShopManager (de.Keyle.MyPet.util.shop.ShopManager)2 Player (org.bukkit.entity.Player)2 BukkitRunnable (org.bukkit.scheduler.BukkitRunnable)2 MyPet (de.Keyle.MyPet.api.entity.MyPet)1 StoredMyPet (de.Keyle.MyPet.api.entity.StoredMyPet)1 IconMenu (de.Keyle.MyPet.api.gui.IconMenu)1 IconMenuItem (de.Keyle.MyPet.api.gui.IconMenuItem)1 MyPetPlayer (de.Keyle.MyPet.api.player.MyPetPlayer)1 ExperienceCalculatorManager (de.Keyle.MyPet.api.skill.experience.ExperienceCalculatorManager)1 SkilltreeIcon (de.Keyle.MyPet.api.skill.skilltree.SkilltreeIcon)1 PluginHook (de.Keyle.MyPet.api.util.hooks.PluginHook)1 ItemDatabase (de.Keyle.MyPet.api.util.inventory.material.ItemDatabase)1 MaterialHolder (de.Keyle.MyPet.api.util.inventory.material.MaterialHolder)1 MyPetLogger (de.Keyle.MyPet.api.util.logger.MyPetLogger)1 MongoDbRepository (de.Keyle.MyPet.repository.types.MongoDbRepository)1 MySqlRepository (de.Keyle.MyPet.repository.types.MySqlRepository)1 SqLiteRepository (de.Keyle.MyPet.repository.types.SqLiteRepository)1 Updater (de.Keyle.MyPet.util.Updater)1 MyPetPlayerImpl (de.Keyle.MyPet.util.player.MyPetPlayerImpl)1 PetShop (de.Keyle.MyPet.util.shop.PetShop)1