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