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