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.HashMap;
035import java.util.List;
036import java.util.Locale;
037import java.util.Map;
038import java.util.concurrent.TimeUnit;
039import java.util.logging.Level;
040import java.util.logging.Logger;
041
042public class BungeeCommandManager extends CommandManager<
043        CommandSender,
044        BungeeCommandIssuer,
045        ChatColor,
046        BungeeMessageFormatter,
047        BungeeCommandExecutionContext,
048        BungeeConditionContext
049    > {
050
051    protected final Plugin plugin;
052    protected Map<String, BungeeRootCommand> registeredCommands = new HashMap<>();
053    protected BungeeCommandContexts contexts;
054    protected BungeeCommandCompletions completions;
055    protected BungeeLocales locales;
056
057    public BungeeCommandManager(Plugin plugin) {
058        this.plugin = plugin;
059        this.formatters.put(MessageType.ERROR, defaultFormatter = new BungeeMessageFormatter(ChatColor.RED, ChatColor.YELLOW, ChatColor.RED));
060        this.formatters.put(MessageType.SYNTAX, new BungeeMessageFormatter(ChatColor.YELLOW, ChatColor.GREEN, ChatColor.WHITE));
061        this.formatters.put(MessageType.INFO, new BungeeMessageFormatter(ChatColor.BLUE, ChatColor.DARK_GREEN, ChatColor.GREEN));
062        this.formatters.put(MessageType.HELP, new BungeeMessageFormatter(ChatColor.AQUA, ChatColor.GREEN, ChatColor.YELLOW));
063
064        getLocales(); // auto load locales
065
066        plugin.getProxy().getPluginManager().registerListener(plugin, new ACFBungeeListener(this, plugin));
067
068        //BungeeCord has no event for listening for client setting changes
069        plugin.getProxy().getScheduler().schedule(plugin, () -> {
070            ProxyServer.getInstance().getPlayers().forEach(this::readLocale);
071        }, 5, 5, TimeUnit.SECONDS);
072
073        // TODO more default dependencies for bungee
074        registerDependency(plugin.getClass(), plugin);
075        registerDependency(Plugin.class, plugin);
076    }
077
078    public Plugin getPlugin() {
079        return this.plugin;
080    }
081
082    @Override
083    public synchronized CommandContexts<BungeeCommandExecutionContext> getCommandContexts() {
084        if (this.contexts == null) {
085            this.contexts = new BungeeCommandContexts(this);
086        }
087        return contexts;
088    }
089
090    @Override
091    public synchronized CommandCompletions<BungeeCommandCompletionContext> getCommandCompletions() {
092        if (this.completions == null) {
093            this.completions = new BungeeCommandCompletions(this);
094        }
095        return completions;
096    }
097
098    @Override
099    public BungeeLocales getLocales() {
100        if (this.locales == null) {
101            this.locales = new BungeeLocales(this);
102            this.locales.loadLanguages();
103        }
104        return locales;
105    }
106
107    public void readLocale(ProxiedPlayer player) {
108        if (!player.isConnected()) {
109            return;
110        }
111
112        //This can be null if we didn't received a settings packet
113        Locale locale = player.getLocale();
114        if (locale != null) {
115            setIssuerLocale(player, player.getLocale());
116        }
117    }
118
119    @Override
120    public void registerCommand(BaseCommand command) {
121        command.onRegister(this);
122        for (Map.Entry<String, RootCommand> entry : command.registeredCommands.entrySet()) {
123            String commandName = entry.getKey().toLowerCase();
124            BungeeRootCommand bungeeCommand = (BungeeRootCommand) entry.getValue();
125            if (!bungeeCommand.isRegistered) {
126                this.plugin.getProxy().getPluginManager().registerCommand(this.plugin, bungeeCommand);
127            }
128            bungeeCommand.isRegistered = true;
129            registeredCommands.put(commandName, bungeeCommand);
130        }
131    }
132
133    public void unregisterCommand(BaseCommand command) {
134        for (Map.Entry<String, RootCommand> entry : command.registeredCommands.entrySet()) {
135            String commandName = entry.getKey().toLowerCase();
136            BungeeRootCommand bungeeCommand = (BungeeRootCommand) entry.getValue();
137            bungeeCommand.getSubCommands().values().removeAll(command.subCommands.values());
138            if (bungeeCommand.getSubCommands().isEmpty() && bungeeCommand.isRegistered)  {
139                unregisterCommand(bungeeCommand);
140                bungeeCommand.isRegistered = false;
141                registeredCommands.remove(commandName);
142            }
143        }
144    }
145
146    public void unregisterCommand(BungeeRootCommand command) {
147        this.plugin.getProxy().getPluginManager().unregisterCommand(command);
148    }
149
150    public void unregisterCommands() {
151        for (Map.Entry<String, BungeeRootCommand> entry : registeredCommands.entrySet()) {
152            unregisterCommand(entry.getValue());
153        }
154    }
155
156    @Override
157    public boolean hasRegisteredCommands() {
158        return !registeredCommands.isEmpty();
159    }
160
161    @Override
162    public boolean isCommandIssuer(Class<?> aClass) {
163        return CommandSender.class.isAssignableFrom(aClass);
164    }
165
166    @Override
167    public BungeeCommandIssuer getCommandIssuer(Object issuer) {
168        if (!(issuer instanceof CommandSender)) {
169            throw new IllegalArgumentException(issuer.getClass().getName() + " is not a Command Issuer.");
170        }
171        return new BungeeCommandIssuer(this, (CommandSender) issuer);
172    }
173
174    @Override
175    public RootCommand createRootCommand(String cmd) {
176        return new BungeeRootCommand(this, cmd);
177    }
178
179    @Override
180    public BungeeCommandExecutionContext createCommandContext(RegisteredCommand command, CommandParameter parameter, CommandIssuer sender, List<String> args, int i, Map<String, Object> passedArgs) {
181        return new BungeeCommandExecutionContext(command, parameter, (BungeeCommandIssuer) sender, args, i, passedArgs);
182    }
183
184    @Override
185    public CommandCompletionContext createCompletionContext(RegisteredCommand command, CommandIssuer sender, String input, String config, String[] args) {
186        return new BungeeCommandCompletionContext(command, (BungeeCommandIssuer) sender, input, config, args);
187    }
188
189    @Override
190    public RegisteredCommand createRegisteredCommand(BaseCommand command, String cmdName, Method method, String prefSubCommand) {
191        return new RegisteredCommand(command, cmdName, method, prefSubCommand);
192    }
193
194    @Override
195    public BungeeConditionContext createConditionContext(CommandIssuer issuer, String config) {
196        return new BungeeConditionContext((BungeeCommandIssuer) issuer, config);
197    }
198
199    @Override
200    public void log(LogLevel level, String message, Throwable throwable) {
201        Logger logger = this.plugin.getLogger();
202        Level logLevel = level == LogLevel.INFO ? Level.INFO : Level.SEVERE;
203        logger.log(logLevel, LogLevel.LOG_PREFIX + message);
204        if (throwable != null) {
205            for (String line : ACFPatterns.NEWLINE.split(ApacheCommonsExceptionUtil.getFullStackTrace(throwable))) {
206                logger.log(logLevel, LogLevel.LOG_PREFIX + line);
207            }
208        }
209    }
210
211
212    @Override
213    public String getCommandPrefix(CommandIssuer issuer) {
214        return issuer.isPlayer() ? "/" : "";
215    }
216}