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