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