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