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