Search in sources :

Example 1 with Injector

use of com.denizenscript.denizen.utilities.command.manager.Injector in project Denizen-For-Bukkit by DenizenScript.

the class Denizen method onEnable.

/*
     * Sets up Denizen on start of the CraftBukkit server.
     */
@Override
public void onEnable() {
    instance = this;
    try {
        versionTag = this.getDescription().getVersion();
        CoreUtilities.noDebugContext = new BukkitTagContext(null, null, null, false, null);
        CoreUtilities.basicContext = new BukkitTagContext(null, null, null, true, null);
        CoreUtilities.errorButNoDebugContext = new BukkitTagContext(null, null, null, false, null);
        CoreUtilities.errorButNoDebugContext.showErrors = true;
        // Load Denizen's core
        DenizenCore.init(coreImplementation);
    } catch (Exception e) {
        e.printStackTrace();
        getServer().getPluginManager().disablePlugin(this);
        startedSuccessful = false;
        return;
    }
    PlayerFlagHandler.dataFolder = new File(getDataFolder(), "player_flags");
    if (!PlayerFlagHandler.dataFolder.exists()) {
        PlayerFlagHandler.dataFolder.mkdir();
    }
    String javaVersion = System.getProperty("java.version");
    getLogger().info("Running on java version: " + javaVersion);
    if (javaVersion.startsWith("8") || javaVersion.startsWith("1.8")) {
        getLogger().info("Running on fully supported Java 8. Updating to Java 17+ is recommended.");
    } else if (javaVersion.startsWith("9") || javaVersion.startsWith("1.9") || javaVersion.startsWith("10") || javaVersion.startsWith("1.10") || javaVersion.startsWith("11") || javaVersion.startsWith("12") || javaVersion.startsWith("13") || javaVersion.startsWith("14") || javaVersion.startsWith("15")) {
        getLogger().warning("Running unreliable Java version. Old Minecraft is built for Java 8, modern Minecraft is built for Java 17. Other Java versions are not guaranteed to function properly.");
    } else if (javaVersion.startsWith("16")) {
        getLogger().info("Running on fully supported Java 16.");
    } else if (javaVersion.startsWith("17")) {
        getLogger().info("Running on fully supported Java 17.");
    } else {
        getLogger().info("Running on unrecognized (future?) Java version. May or may not work.");
    }
    if (!NMSHandler.initialize(this)) {
        getLogger().warning("-------------------------------------");
        getLogger().warning("This build of Denizen is not compatible with this Spigot version! Deactivating Denizen!");
        getLogger().warning("-------------------------------------");
        getServer().getPluginManager().disablePlugin(this);
        startedSuccessful = false;
        return;
    }
    if (!NMSHandler.getInstance().isCorrectMappingsCode()) {
        getLogger().warning("-------------------------------------");
        getLogger().warning("This build of Denizen was built for a different Spigot revision! This may potentially cause issues." + " If you are experiencing trouble, update Denizen and Spigot both to latest builds!" + " If this message appears with both Denizen and Spigot fully up-to-date, contact the Denizen team (via GitHub, Spigot, or Discord) to request an update be built.");
        getLogger().warning("-------------------------------------");
    }
    BukkitCommandRegistry commandRegistry = new BukkitCommandRegistry();
    triggerRegistry = new TriggerRegistry();
    boolean citizensBork = false;
    try {
        // Activate dependencies
        Depends.initialize();
        if (Depends.citizens == null) {
            if (Bukkit.getPluginManager().getPlugin("Citizens") != null) {
                citizensBork = true;
                getLogger().warning("Citizens is present but doesn't seem to be activated! You may have an error earlier in your logs, or you may have a broken plugin load order.");
            } else {
                getLogger().warning("Citizens does not seem to be available! Denizen will have greatly reduced functionality!");
            }
        }
        startedSuccessful = true;
    } catch (Exception e) {
        Debug.echoError(e);
    }
    try {
        // Populate config.yml if it doesn't yet exist.
        saveDefaultConfig();
        reloadConfig();
        // Startup procedure
        Debug.log(ChatColor.LIGHT_PURPLE + "+-------------------------+");
        Debug.log(ChatColor.YELLOW + " _/_ _  ._  _ _  ");
        Debug.log(ChatColor.YELLOW + "(/(-/ )/ /_(-/ ) " + ChatColor.GRAY + " scriptable minecraft");
        Debug.log("");
        Debug.log(ChatColor.GRAY + "by: " + ChatColor.WHITE + "The DenizenScript team");
        Debug.log(ChatColor.GRAY + "Chat with us at: " + ChatColor.WHITE + " https://discord.gg/Q6pZGSR");
        Debug.log(ChatColor.GRAY + "Or learn more at: " + ChatColor.WHITE + " https://denizenscript.com");
        Debug.log(ChatColor.GRAY + "version: " + ChatColor.WHITE + versionTag);
        Debug.log(ChatColor.LIGHT_PURPLE + "+-------------------------+");
    } catch (Exception e) {
        Debug.echoError(e);
    }
    try {
        if (Class.forName("com.destroystokyo.paper.PaperConfig") != null) {
            supportsPaper = true;
        }
    } catch (ClassNotFoundException ex) {
    // Ignore.
    } catch (Throwable ex) {
        Debug.echoError(ex);
    }
    // bstats.org
    try {
        BStatsMetricsLite metrics = new BStatsMetricsLite(this);
    } catch (Throwable e) {
        Debug.echoError(e);
    }
    try {
        // If Citizens is enabled, Create the NPC Helper
        if (Depends.citizens != null) {
            npcHelper = new DenizenNPCHelper();
        }
        // Create our CommandManager to handle '/denizen' commands
        commandManager = new CommandManager();
        commandManager.setInjector(new Injector(this));
        commandManager.register(DenizenCommandHandler.class);
        // If Citizens is enabled, let it handle '/npc' commands
        if (Depends.citizens != null) {
            Depends.citizens.registerCommandClass(NPCCommandHandler.class);
        }
        DenizenEntityType.registerEntityType("ITEM_PROJECTILE", ItemProjectile.class);
        DenizenEntityType.registerEntityType("FAKE_ARROW", FakeArrow.class);
        DenizenEntityType.registerEntityType("FAKE_PLAYER", FakePlayer.class);
        // Track all player names for quick PlayerTag matching
        for (OfflinePlayer player : Bukkit.getOfflinePlayers()) {
            PlayerTag.notePlayer(player);
        }
    } catch (Exception e) {
        Debug.echoError(e);
    }
    try {
        DenizenCore.commandRegistry = commandRegistry;
        commandRegistry.registerCommands();
    } catch (Exception e) {
        Debug.echoError(e);
    }
    try {
        // Register script-container types
        ScriptRegistry._registerCoreTypes();
    } catch (Exception e) {
        Debug.echoError(e);
    }
    try {
        ContainerRegistry.registerMainContainers();
    } catch (Exception e) {
        Debug.echoError(e);
    }
    try {
        // Ensure the Scripts and Midi folder exist
        new File(getDataFolder() + "/scripts").mkdirs();
        new File(getDataFolder() + "/midi").mkdirs();
        new File(getDataFolder() + "/schematics").mkdirs();
        // Ensure the example Denizen.mid sound file is available
        if (!new File(getDataFolder() + "/midi/Denizen.mid").exists()) {
            String sourceFile = URLDecoder.decode(Denizen.class.getProtectionDomain().getCodeSource().getLocation().getFile());
            Debug.log("Denizen.mid not found, extracting from " + sourceFile);
            Utilities.extractFile(new File(sourceFile), "Denizen.mid", getDataFolder() + "/midi/");
        }
    } catch (Exception e) {
        Debug.echoError(e);
    }
    try {
        // Automatic config file update
        InputStream properConfig = Denizen.class.getResourceAsStream("/config.yml");
        String properConfigString = ScriptHelper.convertStreamToString(properConfig);
        properConfig.close();
        FileInputStream currentConfig = new FileInputStream(getDataFolder() + "/config.yml");
        String currentConfigString = ScriptHelper.convertStreamToString(currentConfig);
        currentConfig.close();
        String updated = ConfigUpdater.updateConfig(currentConfigString, properConfigString);
        if (updated != null) {
            Debug.log("Your config file is outdated. Automatically updating it...");
            FileOutputStream configOutput = new FileOutputStream(getDataFolder() + "/config.yml");
            OutputStreamWriter writer = new OutputStreamWriter(configOutput);
            writer.write(updated);
            writer.close();
            configOutput.close();
            reloadConfig();
        }
    } catch (Exception e) {
        Debug.echoError(e);
    }
    try {
        worldScriptHelper = new BukkitWorldScriptHelper();
        itemScriptHelper = new ItemScriptHelper();
        new InventoryScriptHelper();
        new EntityScriptHelper();
        new CommandScriptHelper();
    } catch (Exception e) {
        Debug.echoError(e);
    }
    try {
        if (Depends.citizens != null) {
            // Register traits
            TraitRegistry.registerMainTraits();
        }
    } catch (Exception e) {
        Debug.echoError(e);
    }
    // Register Core Members in the Denizen Registries
    try {
        if (Depends.citizens != null) {
            triggerRegistry.registerCoreMembers();
        }
    } catch (Exception e) {
        Debug.echoError(e);
    }
    try {
        AdjustCommand.specialAdjustables.put("server", ServerTagBase::adjustServer);
        eventManager = new OldEventManager();
        // Register all the modern script events
        ScriptEventRegistry.registerMainEvents();
        // Register Core ObjectTags with the ObjectFetcher
        ObjectFetcher.registerCoreObjects();
        CommonRegistries.registerMainObjects();
        TagManager.registerCoreTags();
        CommonRegistries.registerMainTagHandlers();
    } catch (Exception e) {
        Debug.echoError(e);
    }
    try {
        // Initialize all properties
        PropertyRegistry.registerMainProperties();
    } catch (Exception e) {
        Debug.echoError(e);
    }
    try {
        new CommandEvents();
        if (Settings.cache_packetInterceptAutoInit) {
            NetworkInterceptHelper.enable();
        }
    } catch (Exception e) {
        Debug.echoError(e);
    }
    try {
        if (supportsPaper) {
            final Class<?> clazz = Class.forName("com.denizenscript.denizen.paper.PaperModule");
            clazz.getMethod("init").invoke(null);
        }
    } catch (ClassNotFoundException ex) {
        supportsPaper = false;
    } catch (Throwable ex) {
        supportsPaper = false;
        Debug.echoError(ex);
    }
    Debug.log("Loaded <A>" + commandRegistry.instances.size() + "<W> core commands and <A>" + ObjectFetcher.objectsByPrefix.size() + "<W> core object types.");
    exCommand = new ExCommandHandler();
    exCommand.enableFor(getCommand("ex"));
    ExSustainedCommandHandler exsCommand = new ExSustainedCommandHandler();
    exsCommand.enableFor(getCommand("exs"));
    // Load script files without processing.
    DenizenCore.preloadScripts();
    // Load the saves.yml into memory
    reloadSaves();
    try {
        // Fire the 'on Server PreStart' world event
        ServerPrestartScriptEvent.instance.specialHackRunEvent();
    } catch (Throwable ex) {
        Debug.echoError(ex);
    }
    final boolean hadCitizensBork = citizensBork;
    // Run everything else on the first server tick
    Bukkit.getScheduler().scheduleSyncDelayedTask(this, () -> {
        try {
            if (hadCitizensBork) {
                Depends.setupCitizens();
                if (Depends.citizens != null) {
                    getLogger().warning("Citizens was activated late - this means a plugin load order error occurred. You may have plugins with invalid 'plugin.yml' files (eg that use the 'loadbefore' directive, or that have circular dependencies).");
                    npcHelper = new DenizenNPCHelper();
                    Depends.citizens.registerCommandClass(NPCCommandHandler.class);
                    TraitRegistry.registerMainTraits();
                    triggerRegistry.registerCoreMembers();
                    commandRegistry.registerCitizensCommands();
                    ScriptEventRegistry.registerCitizensEvents();
                    new NPCTagBase();
                    ObjectFetcher.registerWithObjectFetcher(NPCTag.class, NPCTag.tagProcessor);
                }
            }
        } catch (Throwable ex) {
            Debug.echoError(ex);
        }
        try {
            // Process script files (events, etc).
            NoteManager.reload();
            DenizenCore.postLoadScripts();
            Debug.log(ChatColor.LIGHT_PURPLE + "+-------------------------+");
            // Fire the 'on Server Start' world event
            ServerStartScriptEvent.instance.fire();
            worldScriptHelper.serverStartEvent();
            if (Settings.allowStupidx()) {
                Debug.echoError("Don't screw with bad config values.");
                Bukkit.shutdown();
            }
            Bukkit.getScheduler().scheduleSyncRepeatingTask(Denizen.this, () -> {
                Debug.onTick();
                // Sadly, minecraft has no delta timing, so a tick is always 50ms.
                DenizenCore.tick(50);
            }, 1, 1);
            InventoryTag.setupInventoryTracker();
            if (!MapTagBasedFlagTracker.skipAllCleanings) {
                BukkitWorldScriptHelper.cleanAllWorldChunkFlags();
            }
            Bukkit.getPluginManager().registerEvents(new PlayerFlagHandler(), this);
            Debug.log("Denizen fully loaded at: " + TimeTag.now().format());
        } catch (Throwable ex) {
            Debug.echoError(ex);
        }
    }, 1);
    new BukkitRunnable() {

        @Override
        public void run() {
            if (Settings.canRecordStats()) {
                new StatsRecord().start();
            }
        }
    }.runTaskTimer(this, 100, 20 * 60 * 60);
    new BukkitRunnable() {

        @Override
        public void run() {
            PlayerFlagHandler.cleanCache();
        }
    }.runTaskTimer(this, 100, 20 * 60);
    new BukkitRunnable() {

        @Override
        public void run() {
            if (!StrongWarning.recentWarnings.isEmpty()) {
                StringBuilder warnText = new StringBuilder();
                warnText.append(ChatColor.YELLOW).append("[Denizen] ").append(ChatColor.RED).append("Recent strong system warnings, scripters need to address ASAP (check earlier console logs for details):");
                for (StrongWarning warning : StrongWarning.recentWarnings) {
                    warnText.append("\n- ").append(warning.message);
                }
                StrongWarning.recentWarnings.clear();
                Bukkit.getConsoleSender().sendMessage(warnText.toString());
                for (Player player : Bukkit.getOnlinePlayers()) {
                    if (player.isOp()) {
                        player.sendMessage(warnText.toString());
                    }
                }
            }
        }
    }.runTaskTimer(this, 100, 20 * 60 * 5);
}
Also used : NPCTagBase(com.denizenscript.denizen.tags.core.NPCTagBase) StatsRecord(com.denizenscript.denizen.utilities.debugging.StatsRecord) DenizenNPCHelper(com.denizenscript.denizen.npc.DenizenNPCHelper) BukkitCommandRegistry(com.denizenscript.denizen.scripts.commands.BukkitCommandRegistry) ServerTagBase(com.denizenscript.denizen.tags.core.ServerTagBase) StrongWarning(com.denizenscript.denizencore.utilities.debugging.StrongWarning) BStatsMetricsLite(com.denizenscript.denizen.utilities.debugging.BStatsMetricsLite) PlayerFlagHandler(com.denizenscript.denizen.utilities.flags.PlayerFlagHandler) TriggerRegistry(com.denizenscript.denizen.scripts.triggers.TriggerRegistry) CommandManager(com.denizenscript.denizen.utilities.command.manager.CommandManager) Injector(com.denizenscript.denizen.utilities.command.manager.Injector) Player(org.bukkit.entity.Player) FakePlayer(com.denizenscript.denizen.nms.interfaces.FakePlayer) BukkitRunnable(org.bukkit.scheduler.BukkitRunnable) BukkitTagContext(com.denizenscript.denizen.tags.BukkitTagContext) OldEventManager(com.denizenscript.denizencore.events.OldEventManager)

Aggregations

FakePlayer (com.denizenscript.denizen.nms.interfaces.FakePlayer)1 DenizenNPCHelper (com.denizenscript.denizen.npc.DenizenNPCHelper)1 BukkitCommandRegistry (com.denizenscript.denizen.scripts.commands.BukkitCommandRegistry)1 TriggerRegistry (com.denizenscript.denizen.scripts.triggers.TriggerRegistry)1 BukkitTagContext (com.denizenscript.denizen.tags.BukkitTagContext)1 NPCTagBase (com.denizenscript.denizen.tags.core.NPCTagBase)1 ServerTagBase (com.denizenscript.denizen.tags.core.ServerTagBase)1 CommandManager (com.denizenscript.denizen.utilities.command.manager.CommandManager)1 Injector (com.denizenscript.denizen.utilities.command.manager.Injector)1 BStatsMetricsLite (com.denizenscript.denizen.utilities.debugging.BStatsMetricsLite)1 StatsRecord (com.denizenscript.denizen.utilities.debugging.StatsRecord)1 PlayerFlagHandler (com.denizenscript.denizen.utilities.flags.PlayerFlagHandler)1 OldEventManager (com.denizenscript.denizencore.events.OldEventManager)1 StrongWarning (com.denizenscript.denizencore.utilities.debugging.StrongWarning)1 Player (org.bukkit.entity.Player)1 BukkitRunnable (org.bukkit.scheduler.BukkitRunnable)1