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 co.aikar.timings.lib.MCTiming;
028import co.aikar.timings.lib.TimingManager;
029import org.bukkit.Bukkit;
030import org.bukkit.ChatColor;
031import org.bukkit.Server;
032import org.bukkit.command.Command;
033import org.bukkit.command.CommandMap;
034import org.bukkit.command.CommandSender;
035import org.bukkit.command.PluginIdentifiableCommand;
036import org.bukkit.command.SimpleCommandMap;
037import org.bukkit.entity.Player;
038import org.bukkit.inventory.ItemFactory;
039import org.bukkit.plugin.Plugin;
040import org.bukkit.plugin.PluginManager;
041import org.bukkit.plugin.java.JavaPlugin;
042import org.bukkit.scheduler.BukkitScheduler;
043import org.bukkit.scheduler.BukkitTask;
044import org.bukkit.scoreboard.ScoreboardManager;
045import org.jetbrains.annotations.NotNull;
046
047import java.lang.reflect.Field;
048import java.lang.reflect.Method;
049import java.util.HashMap;
050import java.util.List;
051import java.util.Locale;
052import java.util.Map;
053import java.util.Objects;
054import java.util.logging.Level;
055import java.util.logging.Logger;
056
057@SuppressWarnings("WeakerAccess")
058public class BukkitCommandManager extends CommandManager<
059        CommandSender,
060        BukkitCommandIssuer,
061        ChatColor,
062        BukkitMessageFormatter,
063        BukkitCommandExecutionContext,
064        BukkitConditionContext
065        > {
066
067    @SuppressWarnings("WeakerAccess")
068    protected final Plugin plugin;
069    private final CommandMap commandMap;
070    private final TimingManager timingManager;
071    private final BukkitTask localeTask;
072    private final Logger logger;
073    protected Map<String, Command> knownCommands = new HashMap<>();
074    protected Map<String, BukkitRootCommand> registeredCommands = new HashMap<>();
075    protected BukkitCommandContexts contexts;
076    protected BukkitCommandCompletions completions;
077    MCTiming commandTiming;
078    protected BukkitLocales locales;
079    private boolean cantReadLocale = false;
080    protected boolean autoDetectFromClient = true;
081
082    @SuppressWarnings("JavaReflectionMemberAccess")
083    public BukkitCommandManager(Plugin plugin) {
084        this.plugin = plugin;
085        this.logger = Logger.getLogger(this.plugin.getName());
086        this.timingManager = TimingManager.of(plugin);
087        this.commandTiming = this.timingManager.of("Commands");
088        this.commandMap = hookCommandMap();
089        this.formatters.put(MessageType.ERROR, defaultFormatter = new BukkitMessageFormatter(ChatColor.RED, ChatColor.YELLOW, ChatColor.RED));
090        this.formatters.put(MessageType.SYNTAX, new BukkitMessageFormatter(ChatColor.YELLOW, ChatColor.GREEN, ChatColor.WHITE));
091        this.formatters.put(MessageType.INFO, new BukkitMessageFormatter(ChatColor.BLUE, ChatColor.DARK_GREEN, ChatColor.GREEN));
092        this.formatters.put(MessageType.HELP, new BukkitMessageFormatter(ChatColor.AQUA, ChatColor.GREEN, ChatColor.YELLOW));
093
094        Bukkit.getPluginManager().registerEvents(new ACFBukkitListener(this, plugin), plugin);
095
096        getLocales(); // auto load locales
097        this.localeTask = Bukkit.getScheduler().runTaskTimer(plugin, () -> {
098            if (this.cantReadLocale || !this.autoDetectFromClient) {
099                return;
100            }
101            Bukkit.getOnlinePlayers().forEach(this::readPlayerLocale);
102        }, 5, 5);
103
104        registerDependency(plugin.getClass(), plugin);
105        registerDependency(Plugin.class, plugin);
106        registerDependency(JavaPlugin.class, plugin);
107        registerDependency(PluginManager.class, Bukkit.getPluginManager());
108        registerDependency(Server.class, Bukkit.getServer());
109        registerDependency(BukkitScheduler.class, Bukkit.getScheduler());
110        registerDependency(ScoreboardManager.class, Bukkit.getScoreboardManager());
111        registerDependency(ItemFactory.class, Bukkit.getItemFactory());
112    }
113
114    @NotNull private CommandMap hookCommandMap() {
115        CommandMap commandMap = null;
116        try {
117            Server server = Bukkit.getServer();
118            Method getCommandMap = server.getClass().getDeclaredMethod("getCommandMap");
119            getCommandMap.setAccessible(true);
120            commandMap = (CommandMap) getCommandMap.invoke(server);
121            if (!SimpleCommandMap.class.isAssignableFrom(commandMap.getClass())) {
122                this.log(LogLevel.ERROR, "ERROR: CommandMap has been hijacked! Offending command map is located at: " + commandMap.getClass().getName());
123                this.log(LogLevel.ERROR, "We are going to try to hijack it back and resolve this, but you are now in dangerous territory.");
124                this.log(LogLevel.ERROR, "We can not guarantee things are going to work.");
125                Field cmField = server.getClass().getDeclaredField("commandMap");
126                commandMap = new ProxyCommandMap(this, commandMap);
127                cmField.set(server, commandMap);
128                this.log(LogLevel.INFO, "Injected Proxy Command Map... good luck...");
129            }
130            Field knownCommands = SimpleCommandMap.class.getDeclaredField("knownCommands");
131            knownCommands.setAccessible(true);
132            //noinspection unchecked
133            this.knownCommands = (Map<String, Command>) knownCommands.get(commandMap);
134        } catch (Exception e) {
135            this.log(LogLevel.ERROR, "Failed to get Command Map. ACF will not function.");
136            ACFUtil.sneaky(e);
137        }
138        return commandMap;
139    }
140
141    public Plugin getPlugin() {
142        return this.plugin;
143    }
144
145    @Override
146    public boolean isCommandIssuer(Class<?> type) {
147        return CommandSender.class.isAssignableFrom(type);
148    }
149
150    @Override
151    public synchronized CommandContexts<BukkitCommandExecutionContext> getCommandContexts() {
152        if (this.contexts == null) {
153            this.contexts = new BukkitCommandContexts(this);
154        }
155        return contexts;
156    }
157
158    @Override
159    public synchronized CommandCompletions<BukkitCommandCompletionContext> getCommandCompletions() {
160        if (this.completions == null) {
161            this.completions = new BukkitCommandCompletions(this);
162        }
163        return completions;
164    }
165
166
167    @Override
168    public BukkitLocales getLocales() {
169        if (this.locales == null) {
170            this.locales = new BukkitLocales(this);
171            this.locales.loadLanguages();
172        }
173        return locales;
174    }
175
176
177    @Override
178    public boolean hasRegisteredCommands() {
179        return !registeredCommands.isEmpty();
180    }
181
182    public void registerCommand(BaseCommand command, boolean force) {
183        final String plugin = this.plugin.getName().toLowerCase();
184        command.onRegister(this);
185        for (Map.Entry<String, RootCommand> entry : command.registeredCommands.entrySet()) {
186            String commandName = entry.getKey().toLowerCase();
187            BukkitRootCommand bukkitCommand = (BukkitRootCommand) entry.getValue();
188            if (!bukkitCommand.isRegistered) {
189                Command oldCommand = commandMap.getCommand(commandName);
190                if (oldCommand instanceof PluginIdentifiableCommand && ((PluginIdentifiableCommand) oldCommand).getPlugin() == this.plugin) {
191                    knownCommands.remove(commandName);
192                    oldCommand.unregister(commandMap);
193                } else if (oldCommand != null && force) {
194                    knownCommands.remove(commandName);
195                    for (Map.Entry<String, Command> ce : knownCommands.entrySet()) {
196                        String key = ce.getKey();
197                        Command value = ce.getValue();
198                        if (key.contains(":") && oldCommand.equals(value)) {
199                            String[] split = ACFPatterns.COLON.split(key, 2);
200                            if (split.length > 1) {
201                                oldCommand.unregister(commandMap);
202                                oldCommand.setLabel(split[0] + ":" + command.getName());
203                                oldCommand.register(commandMap);
204                            }
205                        }
206                    }
207                }
208                commandMap.register(commandName, plugin, bukkitCommand);
209            }
210            bukkitCommand.isRegistered = true;
211            registeredCommands.put(commandName, bukkitCommand);
212        }
213    }
214
215    @Override
216    public void registerCommand(BaseCommand command) {
217        registerCommand(command, false);
218    }
219
220    public void unregisterCommand(BaseCommand command) {
221        for (RootCommand rootcommand : command.registeredCommands.values()) {
222            BukkitRootCommand bukkitCommand = (BukkitRootCommand) rootcommand;
223            bukkitCommand.getSubCommands().values().removeAll(command.subCommands.values());
224            if (bukkitCommand.isRegistered && bukkitCommand.getSubCommands().isEmpty()) {
225                unregisterCommand(bukkitCommand);
226                bukkitCommand.isRegistered = false;
227            }
228        }
229    }
230
231    /**
232     * @deprecated Use unregisterCommand(BaseCommand) - this will be visibility reduced later.
233     * @param command
234     */
235    @Deprecated
236    public void unregisterCommand(BukkitRootCommand command) {
237        final String plugin = this.plugin.getName().toLowerCase();
238        command.unregister(commandMap);
239        String key = command.getName();
240        Command registered = knownCommands.get(key);
241        if (command.equals(registered)) {
242            knownCommands.remove(key);
243        }
244        knownCommands.remove(plugin + ":" + key);
245    }
246
247    public void unregisterCommands() {
248        for (Map.Entry<String, BukkitRootCommand> entry : registeredCommands.entrySet()) {
249            unregisterCommand(entry.getValue());
250        }
251        this.registeredCommands.clear();
252    }
253
254
255    private Field getEntityField(Player player) throws NoSuchFieldException {
256        Class cls = player.getClass();
257        while (cls != Object.class) {
258            if (cls.getName().endsWith("CraftEntity")) {
259                Field field = cls.getDeclaredField("entity");
260                field.setAccessible(true);
261                return field;
262            }
263            cls = cls.getSuperclass();
264        }
265        return null;
266    }
267
268    public Locale setPlayerLocale(Player player, Locale locale) {
269        return this.setIssuerLocale(player, locale);
270    }
271
272    void readPlayerLocale(Player player) {
273        if (!player.isOnline() || cantReadLocale) {
274            return;
275        }
276        try {
277            Field entityField = getEntityField(player);
278            if (entityField == null) {
279                return;
280            }
281            Object nmsPlayer = entityField.get(player);
282            if (nmsPlayer != null) {
283                Field localeField = nmsPlayer.getClass().getField("locale");
284                Object localeString = localeField.get(nmsPlayer);
285                if (localeString instanceof String) {
286                    String[] split = ACFPatterns.UNDERSCORE.split((String) localeString);
287                    Locale locale = split.length > 1 ? new Locale(split[0], split[1]) : new Locale(split[0]);
288                    Locale prev = issuersLocale.put(player.getUniqueId(), locale);
289                    if (!Objects.equals(locale, prev)) {
290                        this.notifyLocaleChange(getCommandIssuer(player), prev, locale);
291                    }
292                }
293            }
294        } catch (Exception e) {
295            cantReadLocale = true;
296            this.localeTask.cancel();
297            this.log(LogLevel.INFO, "Can't read players locale, you will be unable to automatically detect players language. Only Bukkit 1.7+ is supported for this.", e);
298        }
299    }
300
301    public TimingManager getTimings() {
302        return timingManager;
303    }
304
305    @Override
306    public RootCommand createRootCommand(String cmd) {
307        return new BukkitRootCommand(this, cmd);
308    }
309
310    @Override
311    public BukkitCommandIssuer getCommandIssuer(Object issuer) {
312        if (!(issuer instanceof CommandSender)) {
313            throw new IllegalArgumentException(issuer.getClass().getName() + " is not a Command Issuer.");
314        }
315        return new BukkitCommandIssuer(this, (CommandSender) issuer);
316    }
317
318    @Override
319    public BukkitCommandExecutionContext createCommandContext(RegisteredCommand command, CommandParameter parameter, CommandIssuer sender, List<String> args, int i, Map<String, Object> passedArgs) {
320        return new BukkitCommandExecutionContext(command, parameter, (BukkitCommandIssuer) sender, args, i, passedArgs);
321    }
322
323    @Override
324    public BukkitCommandCompletionContext createCompletionContext(RegisteredCommand command, CommandIssuer sender, String input, String config, String[] args) {
325        return new BukkitCommandCompletionContext(command, (BukkitCommandIssuer) sender, input, config, args);
326    }
327
328    @Override
329    public RegisteredCommand createRegisteredCommand(BaseCommand command, String cmdName, Method method, String prefSubCommand) {
330        return new BukkitRegisteredCommand(command, cmdName, method, prefSubCommand);
331    }
332
333    @Override
334    public BukkitConditionContext createConditionContext(CommandIssuer issuer, String config) {
335        return new BukkitConditionContext((BukkitCommandIssuer) issuer, config);
336    }
337
338
339    @Override
340    public void log(LogLevel level, String message, Throwable throwable) {
341        Level logLevel = level == LogLevel.INFO ? Level.INFO : Level.SEVERE;
342        logger.log(logLevel, LogLevel.LOG_PREFIX + message);
343        if (throwable != null) {
344            for (String line : ACFPatterns.NEWLINE.split(ApacheCommonsExceptionUtil.getFullStackTrace(throwable))) {
345                logger.log(logLevel, LogLevel.LOG_PREFIX + line);
346            }
347        }
348    }
349
350    public boolean usePerIssuerLocale(boolean usePerIssuerLocale, boolean autoDetectFromClient) {
351        boolean old = this.usePerIssuerLocale;
352        this.usePerIssuerLocale = usePerIssuerLocale;
353        this.autoDetectFromClient = autoDetectFromClient;
354        return old;
355    }
356}