Search in sources :

Example 1 with PluginHook

use of de.Keyle.MyPet.api.util.hooks.PluginHook 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 PluginHook

use of de.Keyle.MyPet.api.util.hooks.PluginHook in project MyPet by xXKeyleXx.

the class CommandOptionReload method reloadConfig.

protected void reloadConfig(CommandSender sender) {
    int oldMaxPetCount = Configuration.Misc.MAX_STORED_PET_COUNT;
    ConfigurationLoader.loadConfiguration();
    ConfigurationLoader.loadCompatConfiguration();
    if (MyPetApi.getLogger() instanceof MyPetLogger) {
        ((MyPetLogger) MyPetApi.getLogger()).updateDebugLoggerLogLevel();
    }
    Translation.init();
    if (Configuration.Misc.MAX_STORED_PET_COUNT > oldMaxPetCount) {
        for (int i = oldMaxPetCount + 1; i <= Configuration.Misc.MAX_STORED_PET_COUNT; i++) {
            try {
                Bukkit.getPluginManager().addPermission(new Permission("MyPet.petstorage.limit." + i));
            } catch (Exception ignored) {
            }
        }
    } else if (oldMaxPetCount > Configuration.Misc.MAX_STORED_PET_COUNT) {
        for (int i = oldMaxPetCount; i > Configuration.Misc.MAX_STORED_PET_COUNT; i--) {
            try {
                Bukkit.getPluginManager().removePermission("MyPet.petstorage.limit." + i);
            } catch (Exception ignored) {
            }
        }
    }
    ExperienceCalculatorManager calculatorManager = MyPetApi.getServiceManager().getService(ExperienceCalculatorManager.class).get();
    calculatorManager.switchCalculator(Configuration.LevelSystem.CALCULATION_MODE);
    MyPetApi.getPluginHookManager().getConfig().loadConfig();
    for (PluginHook hook : MyPetApi.getPluginHookManager().getHooks()) {
        ConfigurationSection pluginSection = MyPetApi.getPluginHookManager().getConfig().getConfig().getConfigurationSection(hook.getPluginName());
        if (pluginSection != null) {
            hook.loadConfig(pluginSection);
        }
    }
    if (!(sender instanceof ConsoleCommandSender)) {
        sender.sendMessage("[" + ChatColor.DARK_GREEN + "MyPet" + ChatColor.RESET + "] config reloaded!");
    }
    MyPetApi.getLogger().info("Config reloaded!");
}
Also used : ExperienceCalculatorManager(de.Keyle.MyPet.api.skill.experience.ExperienceCalculatorManager) Permission(org.bukkit.permissions.Permission) MyPetLogger(de.Keyle.MyPet.api.util.logger.MyPetLogger) PluginHook(de.Keyle.MyPet.api.util.hooks.PluginHook) ConsoleCommandSender(org.bukkit.command.ConsoleCommandSender) ConfigurationSection(org.bukkit.configuration.ConfigurationSection)

Aggregations

ExperienceCalculatorManager (de.Keyle.MyPet.api.skill.experience.ExperienceCalculatorManager)2 PluginHook (de.Keyle.MyPet.api.util.hooks.PluginHook)2 MyPetLogger (de.Keyle.MyPet.api.util.logger.MyPetLogger)2 Permission (org.bukkit.permissions.Permission)2 MyPet (de.Keyle.MyPet.api.entity.MyPet)1 StoredMyPet (de.Keyle.MyPet.api.entity.StoredMyPet)1 MyPetPlayer (de.Keyle.MyPet.api.player.MyPetPlayer)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 ShopManager (de.Keyle.MyPet.util.shop.ShopManager)1 File (java.io.File)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 UUID (java.util.UUID)1 Metrics (org.bstats.bukkit.Metrics)1 ConsoleCommandSender (org.bukkit.command.ConsoleCommandSender)1 ConfigurationSection (org.bukkit.configuration.ConfigurationSection)1