Search in sources :

Example 1 with Slimefun

use of io.github.thebusybiscuit.slimefun4.implementation.Slimefun in project Slimefun4 by Slimefun.

the class Slimefun method onDisable.

/**
 * This method gets called when the {@link Plugin} gets disabled.
 * Most often it is called when the {@link Server} is shutting down or reloading.
 */
@Override
public void onDisable() {
    // Slimefun never loaded successfully, so we don't even bother doing stuff here
    if (instance() == null || minecraftVersion == MinecraftVersion.UNIT_TEST) {
        return;
    }
    // Cancel all tasks from this plugin immediately
    Bukkit.getScheduler().cancelTasks(this);
    // Finishes all started movements/removals of block data
    try {
        ticker.halt();
        ticker.run();
    } catch (Exception x) {
        getLogger().log(Level.SEVERE, x, () -> "Something went wrong while disabling the ticker task for Slimefun v" + getDescription().getVersion());
    }
    // Kill our Profiler Threads
    profiler.kill();
    // Save all Player Profiles that are still in memory
    PlayerProfile.iterator().forEachRemaining(profile -> {
        if (profile.isDirty()) {
            profile.save();
        }
    });
    // Save all registered Worlds
    for (Map.Entry<String, BlockStorage> entry : getRegistry().getWorlds().entrySet()) {
        try {
            entry.getValue().saveAndRemove();
        } catch (Exception x) {
            getLogger().log(Level.SEVERE, x, () -> "An Error occurred while saving Slimefun-Blocks in World '" + entry.getKey() + "' for Slimefun " + getVersion());
        }
    }
    // Save all "universal" inventories (ender chests for example)
    for (UniversalBlockMenu menu : registry.getUniversalInventories().values()) {
        menu.save();
    }
    // Create a new backup zip
    if (config.getBoolean("options.backup-data")) {
        backupService.run();
    }
    // Close and unload any resources from our Metrics Service
    metricsService.cleanUp();
    // Terminate our Plugin instance
    setInstance(null);
    /**
     * Close all inventories on the server to prevent item dupes
     * (Incase some idiot uses /reload)
     */
    for (Player p : Bukkit.getOnlinePlayers()) {
        p.closeInventory();
    }
}
Also used : Player(org.bukkit.entity.Player) BlockStorage(me.mrCookieSlime.Slimefun.api.BlockStorage) Map(java.util.Map) TagMisconfigurationException(io.github.thebusybiscuit.slimefun4.api.exceptions.TagMisconfigurationException) UniversalBlockMenu(me.mrCookieSlime.Slimefun.api.inventory.UniversalBlockMenu)

Example 2 with Slimefun

use of io.github.thebusybiscuit.slimefun4.implementation.Slimefun in project Slimefun4 by Slimefun.

the class Slimefun method onPluginStart.

/**
 * This is our start method for a correct Slimefun installation.
 */
private void onPluginStart() {
    long timestamp = System.nanoTime();
    Logger logger = getLogger();
    // Check if Paper (<3) is installed
    if (PaperLib.isPaper()) {
        logger.log(Level.INFO, "Paper was detected! Performance optimizations have been applied.");
    } else {
        PaperLib.suggestPaper(this);
    }
    // Check if CS-CoreLib is installed (it is no longer needed)
    if (getServer().getPluginManager().getPlugin("CS-CoreLib") != null) {
        StartupWarnings.discourageCSCoreLib(logger);
    }
    // Encourage newer Java version
    if (NumberUtils.getJavaVersion() < RECOMMENDED_JAVA_VERSION) {
        StartupWarnings.oldJavaVersion(logger, RECOMMENDED_JAVA_VERSION);
    }
    // If the server has no "data-storage" folder, it's _probably_ a new install. So mark it for metrics.
    isNewlyInstalled = !new File("data-storage/Slimefun").exists();
    // Creating all necessary Folders
    logger.log(Level.INFO, "Creating directories...");
    createDirectories();
    // Load various config settings into our cache
    registry.load(this, config);
    // Set up localization
    logger.log(Level.INFO, "Loading language files...");
    String chatPrefix = config.getString("options.chat-prefix");
    String serverDefaultLanguage = config.getString("options.language");
    local = new LocalizationService(this, chatPrefix, serverDefaultLanguage);
    int networkSize = config.getInt("networks.max-size");
    // Make sure that the network size is a valid input
    if (networkSize < 1) {
        logger.log(Level.WARNING, "Your 'networks.max-size' setting is misconfigured! It must be at least 1, it was set to: {0}", networkSize);
        networkSize = 1;
    }
    networkManager = new NetworkManager(networkSize, config.getBoolean("networks.enable-visualizer"), config.getBoolean("networks.delete-excess-items"));
    // Setting up bStats
    new Thread(metricsService::start, "Slimefun Metrics").start();
    // Starting the Auto-Updater
    if (config.getBoolean("options.auto-update")) {
        logger.log(Level.INFO, "Starting Auto-Updater...");
        updaterService.start();
    } else {
        updaterService.disable();
    }
    // Registering all GEO Resources
    logger.log(Level.INFO, "Loading GEO-Resources...");
    GEOResourcesSetup.setup();
    logger.log(Level.INFO, "Loading Tags...");
    loadTags();
    logger.log(Level.INFO, "Loading items...");
    loadItems();
    logger.log(Level.INFO, "Loading researches...");
    loadResearches();
    registry.setResearchingEnabled(getResearchCfg().getBoolean("enable-researching"));
    PostSetup.setupWiki();
    logger.log(Level.INFO, "Registering listeners...");
    registerListeners();
    // Initiating various Stuff and all items with a slight delay (0ms after the Server finished loading)
    runSync(new SlimefunStartupTask(this, () -> {
        textureService.register(registry.getAllSlimefunItems(), true);
        permissionsService.register(registry.getAllSlimefunItems(), true);
        // This try/catch should prevent buggy Spigot builds from blocking item loading
        try {
            recipeService.refresh();
        } catch (Exception | LinkageError x) {
            logger.log(Level.SEVERE, x, () -> "An Exception occurred while iterating through the Recipe list on Minecraft Version " + minecraftVersion.getName() + " (Slimefun v" + getVersion() + ")");
        }
    }), 0);
    // Setting up our commands
    try {
        command.register();
    } catch (Exception | LinkageError x) {
        logger.log(Level.SEVERE, "An Exception occurred while registering the /slimefun command", x);
    }
    // Armor Update Task
    if (config.getBoolean("options.enable-armor-effects")) {
        boolean radioactiveFire = config.getBoolean("options.burn-players-when-radioactive");
        getServer().getScheduler().runTaskTimerAsynchronously(this, new ArmorTask(radioactiveFire), 0L, config.getInt("options.armor-update-interval") * 20L);
    }
    // Starting our tasks
    autoSavingService.start(this, config.getInt("options.auto-save-delay-in-minutes"));
    hologramsService.start();
    ticker.start(this);
    // Loading integrations
    logger.log(Level.INFO, "Loading Third-Party plugin integrations...");
    integrations.start();
    gitHubService.start(this);
    // Hooray!
    logger.log(Level.INFO, "Slimefun has finished loading in {0}", getStartupTime(timestamp));
}
Also used : ArmorTask(io.github.thebusybiscuit.slimefun4.implementation.tasks.ArmorTask) LocalizationService(io.github.thebusybiscuit.slimefun4.core.services.LocalizationService) SlimefunStartupTask(io.github.thebusybiscuit.slimefun4.implementation.tasks.SlimefunStartupTask) Logger(java.util.logging.Logger) TagMisconfigurationException(io.github.thebusybiscuit.slimefun4.api.exceptions.TagMisconfigurationException) NetworkManager(io.github.thebusybiscuit.slimefun4.core.networks.NetworkManager) File(java.io.File) PluginDescriptionFile(org.bukkit.plugin.PluginDescriptionFile)

Example 3 with Slimefun

use of io.github.thebusybiscuit.slimefun4.implementation.Slimefun in project Slimefun4 by Slimefun.

the class GuideModeOption method getDisplayItem.

@Nonnull
@Override
public Optional<ItemStack> getDisplayItem(Player p, ItemStack guide) {
    if (!p.hasPermission("slimefun.cheat.items")) {
        // Only Players with the appropriate permission can access the cheat sheet
        return Optional.empty();
    }
    Optional<SlimefunGuideMode> current = getSelectedOption(p, guide);
    if (current.isPresent()) {
        SlimefunGuideMode selectedMode = current.get();
        ItemStack item = new ItemStack(Material.AIR);
        if (selectedMode == SlimefunGuideMode.SURVIVAL_MODE) {
            item.setType(Material.CHEST);
        } else {
            item.setType(Material.COMMAND_BLOCK);
        }
        ItemMeta meta = item.getItemMeta();
        meta.setDisplayName(ChatColor.GRAY + "Slimefun Guide Type: " + ChatColor.YELLOW + ChatUtils.humanize(selectedMode.name()));
        List<String> lore = new ArrayList<>();
        lore.add("");
        lore.add((selectedMode == SlimefunGuideMode.SURVIVAL_MODE ? ChatColor.GREEN : ChatColor.GRAY) + "Survival Mode");
        lore.add((selectedMode == SlimefunGuideMode.CHEAT_MODE ? ChatColor.GREEN : ChatColor.GRAY) + "Cheat Sheet");
        lore.add("");
        lore.add(ChatColor.GRAY + "\u21E8 " + ChatColor.YELLOW + "Click to change the type");
        meta.setLore(lore);
        item.setItemMeta(meta);
        return Optional.of(item);
    }
    return Optional.empty();
}
Also used : ArrayList(java.util.ArrayList) SlimefunGuideMode(io.github.thebusybiscuit.slimefun4.core.guide.SlimefunGuideMode) ItemStack(org.bukkit.inventory.ItemStack) ItemMeta(org.bukkit.inventory.meta.ItemMeta) Nonnull(javax.annotation.Nonnull)

Example 4 with Slimefun

use of io.github.thebusybiscuit.slimefun4.implementation.Slimefun in project Slimefun4 by Slimefun.

the class PlayerLanguageOption method openLanguageSelection.

private void openLanguageSelection(Player p, ItemStack guide) {
    ChestMenu menu = new ChestMenu(Slimefun.getLocalization().getMessage(p, "guide.title.languages"));
    menu.setEmptySlotsClickable(false);
    menu.addMenuOpeningHandler(pl -> pl.playSound(pl.getLocation(), Sound.BLOCK_NOTE_BLOCK_HARP, 0.7F, 0.7F));
    for (int i = 0; i < 9; i++) {
        if (i == 1) {
            menu.addItem(1, ChestMenuUtils.getBackButton(p, "", "&7" + Slimefun.getLocalization().getMessage(p, "guide.back.settings")), (pl, slot, item, action) -> {
                SlimefunGuideSettings.openSettings(pl, guide);
                return false;
            });
        } else if (i == 7) {
            menu.addItem(7, new CustomItemStack(SlimefunUtils.getCustomHead(HeadTexture.ADD_NEW_LANGUAGE.getTexture()), Slimefun.getLocalization().getMessage(p, "guide.languages.translations.name"), "", "&7\u21E8 &e" + Slimefun.getLocalization().getMessage(p, "guide.languages.translations.lore")), (pl, slot, item, action) -> {
                ChatUtils.sendURL(pl, "https://github.com/Slimefun/Slimefun4/wiki/Translating-Slimefun");
                pl.closeInventory();
                return false;
            });
        } else {
            menu.addItem(i, ChestMenuUtils.getBackground(), ChestMenuUtils.getEmptyClickHandler());
        }
    }
    Language defaultLanguage = Slimefun.getLocalization().getDefaultLanguage();
    String defaultLanguageString = Slimefun.getLocalization().getMessage(p, "languages.default");
    menu.addItem(9, new CustomItemStack(defaultLanguage.getItem(), ChatColor.GRAY + defaultLanguageString + ChatColor.DARK_GRAY + " (" + defaultLanguage.getName(p) + ")", "", "&7\u21E8 &e" + Slimefun.getLocalization().getMessage(p, "guide.languages.select-default")), (pl, i, item, action) -> {
        Slimefun.instance().getServer().getPluginManager().callEvent(new PlayerLanguageChangeEvent(pl, Slimefun.getLocalization().getLanguage(pl), defaultLanguage));
        setSelectedOption(pl, guide, null);
        Slimefun.getLocalization().sendMessage(pl, "guide.languages.updated", msg -> msg.replace("%lang%", defaultLanguageString));
        SlimefunGuideSettings.openSettings(pl, guide);
        return false;
    });
    int slot = 10;
    for (Language language : Slimefun.getLocalization().getLanguages()) {
        menu.addItem(slot, new CustomItemStack(language.getItem(), ChatColor.GREEN + language.getName(p), "&b" + language.getTranslationProgress() + '%', "", "&7\u21E8 &e" + Slimefun.getLocalization().getMessage(p, "guide.languages.select")), (pl, i, item, action) -> {
            Slimefun.instance().getServer().getPluginManager().callEvent(new PlayerLanguageChangeEvent(pl, Slimefun.getLocalization().getLanguage(pl), language));
            setSelectedOption(pl, guide, language.getId());
            String name = language.getName(pl);
            Slimefun.getLocalization().sendMessage(pl, "guide.languages.updated", msg -> msg.replace("%lang%", name));
            SlimefunGuideSettings.openSettings(pl, guide);
            return false;
        });
        slot++;
    }
    menu.open(p);
}
Also used : SlimefunUtils(io.github.thebusybiscuit.slimefun4.utils.SlimefunUtils) NamespacedKey(org.bukkit.NamespacedKey) ChestMenuUtils(io.github.thebusybiscuit.slimefun4.utils.ChestMenuUtils) PersistentDataAPI(io.github.bakedlibs.dough.data.persistent.PersistentDataAPI) Sound(org.bukkit.Sound) Player(org.bukkit.entity.Player) SlimefunAddon(io.github.thebusybiscuit.slimefun4.api.SlimefunAddon) ChatUtils(io.github.thebusybiscuit.slimefun4.utils.ChatUtils) ArrayList(java.util.ArrayList) ItemStack(org.bukkit.inventory.ItemStack) PlayerLanguageChangeEvent(io.github.thebusybiscuit.slimefun4.api.events.PlayerLanguageChangeEvent) List(java.util.List) Language(io.github.thebusybiscuit.slimefun4.core.services.localization.Language) Slimefun(io.github.thebusybiscuit.slimefun4.implementation.Slimefun) Optional(java.util.Optional) ChestMenu(me.mrCookieSlime.CSCoreLibPlugin.general.Inventory.ChestMenu) ChatColor(org.bukkit.ChatColor) HeadTexture(io.github.thebusybiscuit.slimefun4.utils.HeadTexture) CustomItemStack(io.github.bakedlibs.dough.items.CustomItemStack) PlayerLanguageChangeEvent(io.github.thebusybiscuit.slimefun4.api.events.PlayerLanguageChangeEvent) Language(io.github.thebusybiscuit.slimefun4.core.services.localization.Language) CustomItemStack(io.github.bakedlibs.dough.items.CustomItemStack) ChestMenu(me.mrCookieSlime.CSCoreLibPlugin.general.Inventory.ChestMenu)

Example 5 with Slimefun

use of io.github.thebusybiscuit.slimefun4.implementation.Slimefun in project Slimefun4 by Slimefun.

the class ErrorReport method getNewFile.

@Nonnull
private static File getNewFile() {
    String path = "plugins/Slimefun/error-reports/" + dateFormat.format(LocalDateTime.now());
    File newFile = new File(path + ".err");
    if (newFile.exists()) {
        IntStream stream = IntStream.iterate(1, i -> i + 1).filter(i -> !new File(path + " (" + i + ").err").exists());
        int id = stream.findFirst().getAsInt();
        newFile = new File(path + " (" + id + ").err");
    }
    return newFile;
}
Also used : PrintStream(java.io.PrintStream) IntStream(java.util.stream.IntStream) Plugin(org.bukkit.plugin.Plugin) SlimefunItem(io.github.thebusybiscuit.slimefun4.api.items.SlimefunItem) LocalDateTime(java.time.LocalDateTime) BlockStorage(me.mrCookieSlime.Slimefun.api.BlockStorage) Function(java.util.function.Function) PaperLib(io.papermc.lib.PaperLib) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) ParametersAreNonnullByDefault(javax.annotation.ParametersAreNonnullByDefault) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) Consumer(java.util.function.Consumer) List(java.util.List) EnergyNetProvider(io.github.thebusybiscuit.slimefun4.core.attributes.EnergyNetProvider) Location(org.bukkit.Location) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Locale(java.util.Locale) Slimefun(io.github.thebusybiscuit.slimefun4.implementation.Slimefun) DateTimeFormatter(java.time.format.DateTimeFormatter) Nonnull(javax.annotation.Nonnull) Bukkit(org.bukkit.Bukkit) BlockTicker(me.mrCookieSlime.Slimefun.Objects.handlers.BlockTicker) File(java.io.File) IntStream(java.util.stream.IntStream) Nonnull(javax.annotation.Nonnull)

Aggregations

SlimefunItemStack (io.github.thebusybiscuit.slimefun4.api.items.SlimefunItemStack)17 SlimefunItem (io.github.thebusybiscuit.slimefun4.api.items.SlimefunItem)16 ItemStack (org.bukkit.inventory.ItemStack)14 DisplayName (org.junit.jupiter.api.DisplayName)14 Test (org.junit.jupiter.api.Test)14 Player (org.bukkit.entity.Player)12 CustomItemStack (io.github.bakedlibs.dough.items.CustomItemStack)10 Slimefun (io.github.thebusybiscuit.slimefun4.implementation.Slimefun)8 ParametersAreNonnullByDefault (javax.annotation.ParametersAreNonnullByDefault)7 NamespacedKey (org.bukkit.NamespacedKey)7 PlayerProfile (io.github.thebusybiscuit.slimefun4.api.player.PlayerProfile)6 ArrayList (java.util.ArrayList)6 Nonnull (javax.annotation.Nonnull)6 BeforeAll (org.junit.jupiter.api.BeforeAll)4 TagMisconfigurationException (io.github.thebusybiscuit.slimefun4.api.exceptions.TagMisconfigurationException)3 ItemGroup (io.github.thebusybiscuit.slimefun4.api.items.ItemGroup)3 Block (org.bukkit.block.Block)3 ItemMeta (org.bukkit.inventory.meta.ItemMeta)3 PotionEffect (org.bukkit.potion.PotionEffect)3 AndroidMineEvent (io.github.thebusybiscuit.slimefun4.api.events.AndroidMineEvent)2