    001/*
    002 * Copyright (c) 2016-2017 Daniel Ennis (Aikar) - MIT License
    003 *
    004 *  Permission is hereby granted, free of charge, to any person obtaining
    005 *  a copy of this software and associated documentation files (the
    006 *  "Software"), to deal in the Software without restriction, including
    007 *  without limitation the rights to use, copy, modify, merge, publish,
    008 *  distribute, sublicense, and/or sell copies of the Software, and to
    009 *  permit persons to whom the Software is furnished to do so, subject to
    010 *  the following conditions:
    011 *
    012 *  The above copyright notice and this permission notice shall be
    013 *  included in all copies or substantial portions of the Software.
    014 *
    015 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    016 *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    017 *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    018 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
    019 *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
    020 *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
    021 *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    022 */
    023
    024package co.aikar.commands;
    025
    026import co.aikar.commands.apachecommonslang.ApacheCommonsExceptionUtil;
    027import net.md_5.bungee.api.ChatColor;
    028import net.md_5.bungee.api.CommandSender;
    029import net.md_5.bungee.api.ProxyServer;
    030import net.md_5.bungee.api.connection.ProxiedPlayer;
    031import net.md_5.bungee.api.plugin.Plugin;
    032
    033import java.lang.reflect.Method;
    034import java.util.Collection;
    035import java.util.Collections;
    036import java.util.HashMap;
    037import java.util.List;
    038import java.util.Locale;
    039import java.util.Map;
    040import java.util.concurrent.TimeUnit;
    041import java.util.logging.Level;
    042import java.util.logging.Logger;
    043
    044public class BungeeCommandManager extends CommandManager<
    045        CommandSender,
    046        BungeeCommandIssuer,
    047        ChatColor,
    048        BungeeMessageFormatter,
    049        BungeeCommandExecutionContext,
    050        BungeeConditionContext
    051    > {
    052
    053    protected final Plugin plugin;
    054    protected Map<String, BungeeRootCommand> registeredCommands = new HashMap<>();
    055    protected BungeeCommandContexts contexts;
    056    protected BungeeCommandCompletions completions;
    057    protected BungeeLocales locales;
    058
    059    public BungeeCommandManager(Plugin plugin) {
    060        this.plugin = plugin;
    061        this.formatters.put(MessageType.ERROR, defaultFormatter = new BungeeMessageFormatter(ChatColor.RED, ChatColor.YELLOW, ChatColor.RED));
    062        this.formatters.put(MessageType.SYNTAX, new BungeeMessageFormatter(ChatColor.YELLOW, ChatColor.GREEN, ChatColor.WHITE));
    063        this.formatters.put(MessageType.INFO, new BungeeMessageFormatter(ChatColor.BLUE, ChatColor.DARK_GREEN, ChatColor.GREEN));
    064        this.formatters.put(MessageType.HELP, new BungeeMessageFormatter(ChatColor.AQUA, ChatColor.GREEN, ChatColor.YELLOW));
    065
    066        getLocales(); // auto load locales
    067
    068        plugin.getProxy().getPluginManager().registerListener(plugin, new ACFBungeeListener(this, plugin));
    069
    070        //BungeeCord has no event for listening for client setting changes
    071        plugin.getProxy().getScheduler().schedule(plugin, () -> {
    072            ProxyServer.getInstance().getPlayers().forEach(this::readLocale);
    073        }, 5, 5, TimeUnit.SECONDS);
    074
    075        // TODO more default dependencies for bungee
    076        registerDependency(plugin.getClass(), plugin);
    077        registerDependency(Plugin.class, plugin);
    078    }
    079
    080    public Plugin getPlugin() {
    081        return this.plugin;
    082    }
    083
    084    @Override
    085    public synchronized CommandContexts<BungeeCommandExecutionContext> getCommandContexts() {
    086        if (this.contexts == null) {
    087            this.contexts = new BungeeCommandContexts(this);
    088        }
    089        return contexts;
    090    }
    091
    092    @Override
    093    public synchronized CommandCompletions<BungeeCommandCompletionContext> getCommandCompletions() {
    094        if (this.completions == null) {
    095            this.completions = new BungeeCommandCompletions(this);
    096        }
    097        return completions;
    098    }
    099
    100    @Override
    101    public BungeeLocales getLocales() {
    102        if (this.locales == null) {
    103            this.locales = new BungeeLocales(this);
    104            this.locales.loadLanguages();
    105        }
    106        return locales;
    107    }
    108
    109    public void readLocale(ProxiedPlayer player) {
    110        if (!player.isConnected()) {
    111            return;
    112        }
    113
    114        //This can be null if we didn't received a settings packet
    115        Locale locale = player.getLocale();
    116        if (locale != null) {
    117            setIssuerLocale(player, player.getLocale());
    118        }
    119    }
    120
    121    @Override
    122    public void registerCommand(BaseCommand command) {
    123        command.onRegister(this);
    124        for (Map.Entry<String, RootCommand> entry : command.registeredCommands.entrySet()) {
    125            String commandName = entry.getKey().toLowerCase();
    126            BungeeRootCommand bungeeCommand = (BungeeRootCommand) entry.getValue();
    127            if (!bungeeCommand.isRegistered) {
    128                this.plugin.getProxy().getPluginManager().registerCommand(this.plugin, bungeeCommand);
    129            }
    130            bungeeCommand.isRegistered = true;
    131            registeredCommands.put(commandName, bungeeCommand);
    132        }
    133    }
    134
    135    public void unregisterCommand(BaseCommand command) {
    136        for (Map.Entry<String, RootCommand> entry : command.registeredCommands.entrySet()) {
    137            String commandName = entry.getKey().toLowerCase();
    138            BungeeRootCommand bungeeCommand = (BungeeRootCommand) entry.getValue();
    139            bungeeCommand.getSubCommands().values().removeAll(command.subCommands.values());
    140            if (bungeeCommand.getSubCommands().isEmpty() && bungeeCommand.isRegistered)  {
    141                unregisterCommand(bungeeCommand);
    142                bungeeCommand.isRegistered = false;
    143                registeredCommands.remove(commandName);
    144            }
    145        }
    146    }
    147
    148    public void unregisterCommand(BungeeRootCommand command) {
    149        this.plugin.getProxy().getPluginManager().unregisterCommand(command);
    150    }
    151
    152    public void unregisterCommands() {
    153        for (Map.Entry<String, BungeeRootCommand> entry : registeredCommands.entrySet()) {
    154            unregisterCommand(entry.getValue());
    155        }
    156    }
    157
    158    @Override
    159    public boolean hasRegisteredCommands() {
    160        return !registeredCommands.isEmpty();
    161    }
    162
    163    @Override
    164    public boolean isCommandIssuer(Class<?> aClass) {
    165        return CommandSender.class.isAssignableFrom(aClass);
    166    }
    167
    168    @Override
    169    public BungeeCommandIssuer getCommandIssuer(Object issuer) {
    170        if (!(issuer instanceof CommandSender)) {
    171            throw new IllegalArgumentException(issuer.getClass().getName() + " is not a Command Issuer.");
    172        }
    173        return new BungeeCommandIssuer(this, (CommandSender) issuer);
    174    }
    175
    176    @Override
    177    public RootCommand createRootCommand(String cmd) {
    178        return new BungeeRootCommand(this, cmd);
    179    }
    180
    181    @Override
    182    public Collection<RootCommand> getRegisteredRootCommands() {
    183        return Collections.unmodifiableCollection(registeredCommands.values());
    184    }
    185
    186    @Override
    187    public BungeeCommandExecutionContext createCommandContext(RegisteredCommand command, CommandParameter parameter, CommandIssuer sender, List<String> args, int i, Map<String, Object> passedArgs) {
    188        return new BungeeCommandExecutionContext(command, parameter, (BungeeCommandIssuer) sender, args, i, passedArgs);
    189    }
    190
    191    @Override
    192    public CommandCompletionContext createCompletionContext(RegisteredCommand command, CommandIssuer sender, String input, String config, String[] args) {
    193        return new BungeeCommandCompletionContext(command, (BungeeCommandIssuer) sender, input, config, args);
    194    }
    195
    196    @Override
    197    public RegisteredCommand createRegisteredCommand(BaseCommand command, String cmdName, Method method, String prefSubCommand) {
    198        return new RegisteredCommand(command, cmdName, method, prefSubCommand);
    199    }
    200
    201    @Override
    202    public BungeeConditionContext createConditionContext(CommandIssuer issuer, String config) {
    203        return new BungeeConditionContext((BungeeCommandIssuer) issuer, config);
    204    }
    205
    206    @Override
    207    public void log(LogLevel level, String message, Throwable throwable) {
    208        Logger logger = this.plugin.getLogger();
    209        Level logLevel = level == LogLevel.INFO ? Level.INFO : Level.SEVERE;
    210        logger.log(logLevel, LogLevel.LOG_PREFIX + message);
    211        if (throwable != null) {
    212            for (String line : ACFPatterns.NEWLINE.split(ApacheCommonsExceptionUtil.getFullStackTrace(throwable))) {
    213                logger.log(logLevel, LogLevel.LOG_PREFIX + line);
    214            }
    215        }
    216    }
    217
    218
    219    @Override
    220    public String getCommandPrefix(CommandIssuer issuer) {
    221        return issuer.isPlayer() ? "/" : "";
    222    }
    223}