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