Search in sources :

Example 1 with BukkitCommandCompletionContext

use of co.aikar.commands.BukkitCommandCompletionContext in project map-ads by cerus-mc.

the class MapAdsPlugin method onEnable.

@Override
public void onEnable() {
    if (enabled) {
        this.getLogger().severe("DO NOT RELOAD YOUR SERVER.");
        this.getLogger().severe("This plugin will probably not work correctly now. Disabling.");
        this.getPluginLoader().disablePlugin(this);
        return;
    }
    enabled = true;
    // Misc init
    Premium.init();
    this.closeables.add(TransitionRegistry::cleanup);
    // Init config
    this.saveDefaultConfig();
    this.configModel = new ConfigModel(this.getConfig());
    // Init color cache
    ColorCache colorCache = null;
    if (this.configModel.useColorCache && Premium.isPremium()) {
        final File file = new File(this.getDataFolder(), "colors.cache");
        if (!file.exists()) {
            this.getLogger().info("Color cache does not exist. Generating new cache... This will take a while");
            colorCache = ColorCache.generate();
            try (final OutputStream outputStream = new FileOutputStream(file)) {
                colorCache.write(outputStream);
                outputStream.flush();
            } catch (final IOException e) {
                e.printStackTrace();
                this.getLogger().severe("Failed to save color cache");
            }
        } else {
            try (final InputStream inputStream = new FileInputStream(file)) {
                colorCache = ColorCache.fromInputStream(inputStream);
            } catch (final IOException e) {
                e.printStackTrace();
                this.getLogger().severe("Failed to load color cache");
            }
        }
    }
    // Init L10n
    this.saveResource("lang.yml", false);
    final File l10nFile = new File(this.getDataFolder(), "lang.yml");
    final YamlConfiguration configuration = YamlConfiguration.loadConfiguration(l10nFile);
    this.update(configuration, l10nFile);
    for (final String key : configuration.getKeys(false)) {
        final Object o = configuration.get(key);
        if (o instanceof List) {
            L10n.put(key.replace(",", "."), ((List<String>) o).stream().map(s -> ChatColor.translateAlternateColorCodes('&', s)).collect(Collectors.toList()));
        } else if (o instanceof String) {
            L10n.put(key.replace(",", "."), ChatColor.translateAlternateColorCodes('&', (String) o));
        } else {
            this.getLogger().warning("Invalid lang mapping: " + key + "->" + o.getClass().getName());
        }
    }
    // Init help book
    this.saveResource("helpbook.yml", false);
    final HelpBookConfiguration helpBookConfiguration = new HelpBookConfiguration();
    helpBookConfiguration.load();
    HelpBook.init(helpBookConfiguration);
    // Init Vault
    final RegisteredServiceProvider<Economy> registration = this.getServer().getServicesManager().getRegistration(Economy.class);
    if (registration == null) {
        this.getLogger().severe("Please install an economy plugin!");
        this.getPluginLoader().disablePlugin(this);
        return;
    }
    final Economy economy = registration.getProvider();
    // Init image storage
    final ImageStorage imageStorage = this.loadImageStorage();
    if (imageStorage == null) {
        this.getLogger().severe("Invalid image storage configuration");
        this.getPluginLoader().disablePlugin(this);
        return;
    }
    this.closeables.add(imageStorage);
    // Init advert storage
    final AdvertStorage advertStorage = this.loadAdvertStorage(imageStorage);
    if (advertStorage == null) {
        this.getLogger().severe("Invalid advert storage configuration");
        this.getPluginLoader().disablePlugin(this);
        return;
    }
    this.closeables.add(advertStorage);
    // Init Discord bot
    boolean discordEnabled = false;
    if (this.getServer().getPluginManager().isPluginEnabled("map-ads-discord-bot")) {
        final DiscordHook discordHook = new DiscordHook(this, advertStorage, imageStorage, economy);
        final AutoCloseable closeable = discordHook.load();
        if (closeable != null) {
            this.closeables.add(closeable);
            this.getLogger().info("Discovered Discord extension");
            discordEnabled = true;
        }
    }
    final boolean finalDiscordEnabled = discordEnabled;
    // Init misc services
    final AdScreenStorage adScreenStorage = this.loadAdScreenStorage();
    this.closeables.add(adScreenStorage);
    final DefaultImageController defaultImageController = new DefaultImageController(this, imageStorage);
    final AdvertController advertController = new AdvertController(this, advertStorage, imageStorage, defaultImageController);
    final ImageRetriever imageRetriever = new ImageRetriever();
    final ImageConverter imageConverter = new ImageConverter(colorCache);
    // Register commands & dependencies, init completions
    final BukkitCommandManager commandManager = new BukkitCommandManager(this);
    final CommandCompletions<BukkitCommandCompletionContext> completions = commandManager.getCommandCompletions();
    completions.registerCompletion("mapads_names", context -> adScreenStorage.getScreens().stream().map(AdScreen::getId).collect(Collectors.toList()));
    completions.registerCompletion("mapads_transitions", context -> TransitionRegistry.names());
    completions.registerCompletion("mapads_adverts", context -> advertStorage.getPendingAdvertisements().stream().map(advertisement -> advertisement.getAdvertId().toString()).collect(Collectors.toSet()));
    completions.registerCompletion("maps_ids", context -> MapScreenRegistry.getScreenIds().stream().map(String::valueOf).collect(Collectors.toList()));
    completions.registerCompletion("mapads_commondim", context -> {
        final List<String> list = new ArrayList<>();
        for (int x = 1; x <= 20; x++) {
            for (int y = 1; y <= 20; y++) {
                list.add(x + "x" + y);
            }
        }
        return list;
    });
    commandManager.getCommandContexts().registerContext(UUID.class, ctx -> {
        final String s = ctx.popFirstArg();
        try {
            return UUID.fromString(s);
        } catch (final IllegalArgumentException ignored) {
            throw new InvalidCommandArgument("Not a UUID");
        }
    });
    commandManager.registerDependency(ImageStorage.class, imageStorage);
    commandManager.registerDependency(AdvertStorage.class, advertStorage);
    commandManager.registerDependency(AdScreenStorage.class, adScreenStorage);
    commandManager.registerDependency(ImageRetriever.class, imageRetriever);
    commandManager.registerDependency(ImageConverter.class, imageConverter);
    commandManager.registerDependency(DefaultImageController.class, defaultImageController);
    commandManager.registerDependency(AdvertController.class, advertController);
    commandManager.registerDependency(ConfigModel.class, this.configModel);
    commandManager.registerDependency(Economy.class, economy);
    commandManager.registerCommand(new MapAdsCommand());
    commandManager.registerCommand(new PremiumCommand());
    commandManager.registerCommand(new ScreenCommand());
    commandManager.registerCommand(new DefaultImageCommand());
    commandManager.registerCommand(new ReviewCommand());
    commandManager.registerCommand(new HelpCommand());
    commandManager.registerCommand(new PreviewCommand());
    commandManager.registerCommand(new AdvertCommand());
    // Register listeners
    final PluginManager pluginManager = this.getServer().getPluginManager();
    pluginManager.registerEvents(new PlayerJoinListener(this, adScreenStorage, advertStorage), this);
    // Start tasks
    final BukkitScheduler scheduler = this.getServer().getScheduler();
    scheduler.runTaskTimerAsynchronously(this, new FrameSendTask(adScreenStorage), 4 * 20, 2 * 20);
    scheduler.runTaskTimerAsynchronously(this, () -> adScreenStorage.getScreens().forEach(advertController::update), 4 * 20, 60 * 20);
    scheduler.runTaskLater(this, () -> this.screensLoaded = true, 4 * 20);
    // Register services
    final ServicesManager servicesManager = this.getServer().getServicesManager();
    servicesManager.register(AdvertStorage.class, advertStorage, this, ServicePriority.Normal);
    servicesManager.register(AdScreenStorage.class, adScreenStorage, this, ServicePriority.Normal);
    servicesManager.register(ImageStorage.class, imageStorage, this, ServicePriority.Normal);
    servicesManager.register(DefaultImageController.class, defaultImageController, this, ServicePriority.Normal);
    servicesManager.register(ImageConverter.class, imageConverter, this, ServicePriority.Normal);
    servicesManager.register(ImageRetriever.class, imageRetriever, this, ServicePriority.Normal);
    // Init metrics
    final Metrics metrics = new Metrics(this, 13063);
    metrics.addCustomChart(new SimplePie("premium", () -> Premium.isPremium() ? "Yes" : "No"));
    metrics.addCustomChart(new SimplePie("discord_integration_enabled", () -> finalDiscordEnabled ? "Yes" : "No"));
    metrics.addCustomChart(new AdvancedPie("transition_usage", () -> {
        final Map<String, Integer> map = new HashMap<>();
        for (final String name : TransitionRegistry.names()) {
            map.put(name, 0);
        }
        for (final AdScreen screen : adScreenStorage.getScreens()) {
            if (map.containsKey(screen.getTransition())) {
                map.put(screen.getTransition(), map.get(screen.getTransition()) + 1);
            }
        }
        return map;
    }));
}
Also used : ScreenCommand(dev.cerus.mapads.command.ScreenCommand) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) AdvertController(dev.cerus.mapads.advert.AdvertController) ArrayList(java.util.ArrayList) SimplePie(org.bstats.charts.SimplePie) FrameSendTask(dev.cerus.mapads.task.FrameSendTask) AdvertStorage(dev.cerus.mapads.advert.storage.AdvertStorage) PluginManager(org.bukkit.plugin.PluginManager) ReviewCommand(dev.cerus.mapads.command.ReviewCommand) Metrics(org.bstats.bukkit.Metrics) InvalidCommandArgument(co.aikar.commands.InvalidCommandArgument) List(java.util.List) ArrayList(java.util.ArrayList) DefaultImageCommand(dev.cerus.mapads.command.DefaultImageCommand) HelpCommand(dev.cerus.mapads.command.HelpCommand) PlayerJoinListener(dev.cerus.mapads.listener.PlayerJoinListener) FileInputStream(java.io.FileInputStream) BukkitCommandCompletionContext(co.aikar.commands.BukkitCommandCompletionContext) FileOutputStream(java.io.FileOutputStream) BukkitScheduler(org.bukkit.scheduler.BukkitScheduler) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) ImageConverter(dev.cerus.mapads.image.ImageConverter) YamlConfiguration(org.bukkit.configuration.file.YamlConfiguration) ImageRetriever(dev.cerus.mapads.image.ImageRetriever) PreviewCommand(dev.cerus.mapads.command.PreviewCommand) Economy(net.milkbowl.vault.economy.Economy) AdvancedPie(org.bstats.charts.AdvancedPie) PremiumCommand(dev.cerus.mapads.command.PremiumCommand) AdvertCommand(dev.cerus.mapads.command.AdvertCommand) ColorCache(dev.cerus.mapads.image.ColorCache) TransitionRegistry(dev.cerus.mapads.image.transition.TransitionRegistry) BukkitCommandManager(co.aikar.commands.BukkitCommandManager) ImageStorage(dev.cerus.mapads.image.storage.ImageStorage) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) AdScreen(dev.cerus.mapads.screen.AdScreen) HelpBookConfiguration(dev.cerus.mapads.helpbook.HelpBookConfiguration) IOException(java.io.IOException) AdScreenStorage(dev.cerus.mapads.screen.storage.AdScreenStorage) ServicesManager(org.bukkit.plugin.ServicesManager) DefaultImageController(dev.cerus.mapads.image.DefaultImageController) MapAdsCommand(dev.cerus.mapads.command.MapAdsCommand) DiscordHook(dev.cerus.mapads.hook.DiscordHook)

Example 2 with BukkitCommandCompletionContext

use of co.aikar.commands.BukkitCommandCompletionContext in project RoseStacker by Rosewood-Development.

the class CommandManager method reload.

@Override
public void reload() {
    LocaleManager localeManager = this.rosePlugin.getManager(LocaleManager.class);
    ConversionManager conversionManager = this.rosePlugin.getManager(ConversionManager.class);
    StackSettingManager stackSettingManager = this.rosePlugin.getManager(StackSettingManager.class);
    // Load custom message strings
    Map<String, String> acfCoreMessages = localeManager.getAcfCoreMessages();
    Map<String, String> acfMinecraftMessages = localeManager.getAcfMinecraftMessages();
    for (Entry<String, String> entry : acfCoreMessages.entrySet()) this.commandManager.getLocales().addMessage(Locale.ENGLISH, MessageKey.of("acf-core." + entry.getKey()), HexUtils.colorify(localeManager.getLocaleMessage("prefix") + entry.getValue()));
    for (Entry<String, String> entry : acfMinecraftMessages.entrySet()) this.commandManager.getLocales().addMessage(Locale.ENGLISH, MessageKey.of("acf-minecraft." + entry.getKey()), HexUtils.colorify(localeManager.getLocaleMessage("prefix") + entry.getValue()));
    CommandCompletions<BukkitCommandCompletionContext> completions = this.commandManager.getCommandCompletions();
    completions.registerStaticCompletion("stackableBlockMaterial", () -> stackSettingManager.getStackableBlockTypes().stream().map(Enum::name).map(String::toLowerCase).collect(Collectors.toSet()));
    completions.registerStaticCompletion("spawnableSpawnerEntityType", () -> stackSettingManager.getStackableSpawnerTypes().stream().map(Enum::name).map(String::toLowerCase).collect(Collectors.toSet()));
    completions.registerStaticCompletion("spawnableEggEntityType", () -> stackSettingManager.getStackableEntityTypes().stream().filter(x -> {
        EntityStackSettings stackSettings = stackSettingManager.getEntityStackSettings(x);
        return stackSettings.getEntityTypeData().getSpawnEggMaterial() != null;
    }).map(Enum::name).map(String::toLowerCase).collect(Collectors.toSet()));
    completions.registerAsyncCompletion("blockStackAmounts", ctx -> {
        Material blockType = ctx.getContextValue(Material.class);
        if (blockType == null)
            return Collections.emptyList();
        BlockStackSettings blockStackSettings = stackSettingManager.getBlockStackSettings(blockType);
        int maxStackAmount = blockStackSettings.getMaxStackSize();
        return Arrays.asList(String.valueOf(maxStackAmount), String.valueOf(maxStackAmount / 2), String.valueOf(maxStackAmount / 4), "<amount>");
    });
    completions.registerAsyncCompletion("spawnerStackAmounts", ctx -> {
        EntityType entityType = ctx.getContextValue(EntityType.class);
        if (entityType == null)
            return Collections.emptySet();
        SpawnerStackSettings spawnerStackSettings = stackSettingManager.getSpawnerStackSettings(entityType);
        int maxStackAmount = spawnerStackSettings.getMaxStackSize();
        return Arrays.asList(String.valueOf(maxStackAmount), String.valueOf(maxStackAmount / 2), String.valueOf(maxStackAmount / 4), "<amount>");
    });
    completions.registerAsyncCompletion("entityStackAmounts", ctx -> {
        EntityType entityType = ctx.getContextValue(EntityType.class);
        if (entityType == null)
            return Collections.emptySet();
        EntityStackSettings entityStackSettings = stackSettingManager.getEntityStackSettings(entityType);
        int maxStackAmount = entityStackSettings.getMaxStackSize();
        return Arrays.asList(String.valueOf(maxStackAmount), String.valueOf(maxStackAmount / 2), String.valueOf(maxStackAmount / 4), "<amount>");
    });
    completions.registerStaticCompletion("giveAmounts", () -> IntStream.rangeClosed(1, 5).mapToObj(String::valueOf).collect(Collectors.toList()));
    completions.registerStaticCompletion("clearallType", () -> Stream.of(ClearallType.values()).map(Enum::name).map(String::toLowerCase).collect(Collectors.toSet()));
    completions.registerStaticCompletion("stackType", () -> Stream.of(StackType.values()).map(Enum::name).map(String::toLowerCase).collect(Collectors.toSet()));
    completions.registerAsyncCompletion("conversionType", ctx -> conversionManager.getEnabledConverters().stream().map(Enum::name).collect(Collectors.toSet()));
    completions.registerAsyncCompletion("conversionEnabledType", ctx -> conversionManager.getEnabledHandlers().stream().map(ConversionHandler::getRequiredDataStackType).map(Enum::name).map(String::toLowerCase).collect(Collectors.toSet()));
    completions.registerAsyncCompletion("translationLocales", ctx -> localeManager.getPossibleTranslationLocales());
    this.commandManager.getCommandConditions().addCondition(int.class, "limits", (c, exec, value) -> {
        if (value == null)
            return;
        if (c.hasConfig("min") && c.getConfigValue("min", 0) > value)
            throw new ConditionFailedException(MessageKeys.PLEASE_SPECIFY_AT_LEAST, "{min}", String.valueOf(c.getConfigValue("min", 0)));
        if (c.hasConfig("max") && c.getConfigValue("max", Integer.MAX_VALUE) < value)
            throw new ConditionFailedException(MessageKeys.PLEASE_SPECIFY_AT_MOST, "{max}", String.valueOf(c.getConfigValue("max", Integer.MAX_VALUE)));
    });
}
Also used : EntityStackSettings(dev.rosewood.rosestacker.stack.settings.EntityStackSettings) SpawnerStackSettings(dev.rosewood.rosestacker.stack.settings.SpawnerStackSettings) ConversionHandler(dev.rosewood.rosestacker.conversion.handler.ConversionHandler) Material(org.bukkit.Material) BlockStackSettings(dev.rosewood.rosestacker.stack.settings.BlockStackSettings) EntityType(org.bukkit.entity.EntityType) ConditionFailedException(co.aikar.commands.ConditionFailedException) BukkitCommandCompletionContext(co.aikar.commands.BukkitCommandCompletionContext)

Example 3 with BukkitCommandCompletionContext

use of co.aikar.commands.BukkitCommandCompletionContext in project Easterlyn by Easterlyn.

the class CoreCompletions method register.

public static void register(EasterlynCore plugin) {
    CommandCompletions<BukkitCommandCompletionContext> completions = plugin.getCommandManager().getCommandCompletions();
    completions.registerAsyncCompletion("integer", context -> {
        String input = context.getInput();
        if (!input.matches("-?\\d+?")) {
            return Collections.emptyList();
        }
        ArrayList<String> values = new ArrayList<>();
        if (!input.isEmpty()) {
            values.add(input);
        }
        for (int i = input.isEmpty() ? 1 : 0; i < 10; ++i) {
            values.add(input + i);
        }
        return values;
    });
    completions.setDefaultCompletion("integer", int.class, Integer.class, long.class, Long.class);
    completions.registerAsyncCompletion("decimal", context -> {
        String input = context.getInput();
        if (!input.matches("-?\\d+?\\.?\\d+?")) {
            return Collections.emptyList();
        }
        ArrayList<String> values = new ArrayList<>();
        if (!input.isEmpty()) {
            values.add(input);
        }
        for (int i = input.isEmpty() ? 1 : 0; i < 10; ++i) {
            values.add(input + i);
        }
        if (input.indexOf('.') == -1) {
            values.add(input + '.');
        }
        return values;
    });
    completions.setDefaultCompletion("decimal", double.class, Double.class, float.class, Float.class);
    completions.registerAsyncCompletion("permission", context -> {
        if (context.hasConfig("value") && !context.getIssuer().hasPermission(context.getConfig("value"))) {
            return Collections.emptyList();
        }
        if (!context.hasConfig("complete")) {
            return Collections.emptyList();
        }
        return Arrays.stream(context.getConfig("complete").split("/")).distinct().filter(completion -> StringUtil.startsWithIgnoreCase(completion, context.getInput())).collect(Collectors.toList());
    });
    completions.registerCompletion("player", context -> {
        Player issuer = context.getPlayer();
        ArrayList<String> values = new ArrayList<>();
        for (Player player : Bukkit.getOnlinePlayers()) {
            if (issuer == null || issuer.canSee(player)) {
                values.add(player.getName());
            }
        }
        return values;
    });
    completions.setDefaultCompletion("player", Player.class);
    // TODO
    // commands, date
    // location, worldLocation, material, world, chatcolor, chatformat
    completions.registerStaticCompletion("password", Arrays.asList("Hunter2", "animebuttsdrivemenuts1"));
}
Also used : Arrays(java.util.Arrays) BukkitCommandCompletionContext(co.aikar.commands.BukkitCommandCompletionContext) StringUtil(com.easterlyn.util.StringUtil) EasterlynCore(com.easterlyn.EasterlynCore) Player(org.bukkit.entity.Player) Collections(java.util.Collections) Collectors(java.util.stream.Collectors) CommandCompletions(co.aikar.commands.CommandCompletions) ArrayList(java.util.ArrayList) Bukkit(org.bukkit.Bukkit) Player(org.bukkit.entity.Player) BukkitCommandCompletionContext(co.aikar.commands.BukkitCommandCompletionContext) ArrayList(java.util.ArrayList)

Aggregations

BukkitCommandCompletionContext (co.aikar.commands.BukkitCommandCompletionContext)3 ArrayList (java.util.ArrayList)2 BukkitCommandManager (co.aikar.commands.BukkitCommandManager)1 CommandCompletions (co.aikar.commands.CommandCompletions)1 ConditionFailedException (co.aikar.commands.ConditionFailedException)1 InvalidCommandArgument (co.aikar.commands.InvalidCommandArgument)1 EasterlynCore (com.easterlyn.EasterlynCore)1 StringUtil (com.easterlyn.util.StringUtil)1 AdvertController (dev.cerus.mapads.advert.AdvertController)1 AdvertStorage (dev.cerus.mapads.advert.storage.AdvertStorage)1 AdvertCommand (dev.cerus.mapads.command.AdvertCommand)1 DefaultImageCommand (dev.cerus.mapads.command.DefaultImageCommand)1 HelpCommand (dev.cerus.mapads.command.HelpCommand)1 MapAdsCommand (dev.cerus.mapads.command.MapAdsCommand)1 PremiumCommand (dev.cerus.mapads.command.PremiumCommand)1 PreviewCommand (dev.cerus.mapads.command.PreviewCommand)1 ReviewCommand (dev.cerus.mapads.command.ReviewCommand)1 ScreenCommand (dev.cerus.mapads.command.ScreenCommand)1 HelpBookConfiguration (dev.cerus.mapads.helpbook.HelpBookConfiguration)1 DiscordHook (dev.cerus.mapads.hook.DiscordHook)1