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.SimpleCommandMap; 036import org.bukkit.entity.Player; 037import org.bukkit.inventory.ItemFactory; 038import org.bukkit.plugin.Plugin; 039import org.bukkit.plugin.PluginManager; 040import org.bukkit.plugin.java.JavaPlugin; 041import org.bukkit.scheduler.BukkitScheduler; 042import org.bukkit.scheduler.BukkitTask; 043import org.bukkit.scoreboard.ScoreboardManager; 044import org.jetbrains.annotations.NotNull; 045 046import java.lang.reflect.Field; 047import java.lang.reflect.Method; 048import java.lang.reflect.Parameter; 049import java.util.HashMap; 050import java.util.List; 051import java.util.Locale; 052import java.util.Map; 053import java.util.Objects; 054import java.util.logging.Level; 055import java.util.logging.Logger; 056 057@SuppressWarnings("WeakerAccess") 058public class BukkitCommandManager extends CommandManager< 059 CommandSender, 060 BukkitCommandIssuer, 061 ChatColor, 062 BukkitMessageFormatter, 063 BukkitCommandExecutionContext, 064 BukkitConditionContext 065 > { 066 067 @SuppressWarnings("WeakerAccess") 068 protected final Plugin plugin; 069 private final CommandMap commandMap; 070 private final TimingManager timingManager; 071 private final BukkitTask localeTask; 072 private final Logger logger; 073 protected Map<String, Command> knownCommands = new HashMap<>(); 074 protected Map<String, BukkitRootCommand> registeredCommands = new HashMap<>(); 075 protected BukkitCommandContexts contexts; 076 protected BukkitCommandCompletions completions; 077 MCTiming commandTiming; 078 protected BukkitLocales locales; 079 private boolean cantReadLocale = false; 080 protected boolean autoDetectFromClient = true; 081 082 @SuppressWarnings("JavaReflectionMemberAccess") 083 public BukkitCommandManager(Plugin plugin) { 084 this.plugin = plugin; 085 this.logger = Logger.getLogger(this.plugin.getName()); 086 this.timingManager = TimingManager.of(plugin); 087 this.commandTiming = this.timingManager.of("Commands"); 088 this.commandMap = hookCommandMap(); 089 this.formatters.put(MessageType.ERROR, defaultFormatter = new BukkitMessageFormatter(ChatColor.RED, ChatColor.YELLOW, ChatColor.RED)); 090 this.formatters.put(MessageType.SYNTAX, new BukkitMessageFormatter(ChatColor.YELLOW, ChatColor.GREEN, ChatColor.WHITE)); 091 this.formatters.put(MessageType.INFO, new BukkitMessageFormatter(ChatColor.BLUE, ChatColor.DARK_GREEN, ChatColor.GREEN)); 092 this.formatters.put(MessageType.HELP, new BukkitMessageFormatter(ChatColor.AQUA, ChatColor.GREEN, ChatColor.YELLOW)); 093 094 Bukkit.getPluginManager().registerEvents(new ACFBukkitListener(this, plugin), plugin); 095 096 getLocales(); // auto load locales 097 this.localeTask = Bukkit.getScheduler().runTaskTimer(plugin, () -> { 098 if (this.cantReadLocale || !this.autoDetectFromClient) { 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 public Locale setPlayerLocale(Player player, Locale locale) { 266 return this.setIssuerLocale(player, locale); 267 } 268 269 void readPlayerLocale(Player player) { 270 if (!player.isOnline() || cantReadLocale) { 271 return; 272 } 273 try { 274 Field entityField = getEntityField(player); 275 if (entityField == null) { 276 return; 277 } 278 Object nmsPlayer = entityField.get(player); 279 if (nmsPlayer != null) { 280 Field localeField = nmsPlayer.getClass().getField("locale"); 281 Object localeString = localeField.get(nmsPlayer); 282 if (localeString instanceof String) { 283 String[] split = ACFPatterns.UNDERSCORE.split((String) localeString); 284 Locale locale = split.length > 1 ? new Locale(split[0], split[1]) : new Locale(split[0]); 285 Locale prev = issuersLocale.put(player.getUniqueId(), locale); 286 if (!Objects.equals(locale, prev)) { 287 this.notifyLocaleChange(getCommandIssuer(player), prev, locale); 288 } 289 } 290 } 291 } catch (Exception e) { 292 cantReadLocale = true; 293 this.localeTask.cancel(); 294 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); 295 } 296 } 297 298 public TimingManager getTimings() { 299 return timingManager; 300 } 301 302 @Override 303 public RootCommand createRootCommand(String cmd) { 304 return new BukkitRootCommand(this, cmd); 305 } 306 307 @Override 308 public BukkitCommandIssuer getCommandIssuer(Object issuer) { 309 if (!(issuer instanceof CommandSender)) { 310 throw new IllegalArgumentException(issuer.getClass().getName() + " is not a Command Issuer."); 311 } 312 return new BukkitCommandIssuer(this, (CommandSender) issuer); 313 } 314 315 @Override 316 public BukkitCommandExecutionContext createCommandContext(RegisteredCommand command, Parameter parameter, CommandIssuer sender, List<String> args, int i, Map<String, Object> passedArgs) { 317 return new BukkitCommandExecutionContext(command, parameter, (BukkitCommandIssuer) sender, args, i, passedArgs); 318 } 319 320 @Override 321 public BukkitCommandCompletionContext createCompletionContext(RegisteredCommand command, CommandIssuer sender, String input, String config, String[] args) { 322 return new BukkitCommandCompletionContext(command, (BukkitCommandIssuer) sender, input, config, args); 323 } 324 325 @Override 326 public RegisteredCommand createRegisteredCommand(BaseCommand command, String cmdName, Method method, String prefSubCommand) { 327 return new BukkitRegisteredCommand(command, cmdName, method, prefSubCommand); 328 } 329 330 @Override 331 public BukkitConditionContext createConditionContext(CommandIssuer issuer, String config) { 332 return new BukkitConditionContext((BukkitCommandIssuer) issuer, config); 333 } 334 335 336 @Override 337 public void log(LogLevel level, String message, Throwable throwable) { 338 Level logLevel = level == LogLevel.INFO ? Level.INFO : Level.SEVERE; 339 logger.log(logLevel, LogLevel.LOG_PREFIX + message); 340 if (throwable != null) { 341 for (String line : ACFPatterns.NEWLINE.split(ApacheCommonsExceptionUtil.getFullStackTrace(throwable))) { 342 logger.log(logLevel, LogLevel.LOG_PREFIX + line); 343 } 344 } 345 } 346 347 public boolean usePerIssuerLocale(boolean usePerIssuerLocale, boolean autoDetectFromClient) { 348 boolean old = this.usePerIssuerLocale; 349 this.usePerIssuerLocale = usePerIssuerLocale; 350 this.autoDetectFromClient = autoDetectFromClient; 351 return old; 352 } 353}