diff --git a/README.md b/README.md index 7d0dc3ee2..f5320ed2d 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,7 @@ A permissions implementation for Bukkit/Spigot, BungeeCord and Sponge. * **Tracks / paths / ladders** - users can be promoted/demoted along multiple group tracks * **Vault Support** - hooks into Vault to integrate with other plugins * **Developer API** - easily integrate LuckPerms into your own projects +* **Advanced action logging** - keep track of permission changes over time * **Easy and simple setup and configuration using commands** - no editing yml files, yuck * **Negated permissions and groups** - define special rules for certain users/groups * **Regex permissions** - define special permissions using regex @@ -237,5 +238,13 @@ Additionally, you can use wildcards to grant users access to a selection of comm * /perms track \ remove \ - luckperms.track.remove * /perms track \ clear - luckperms.track.clear +### Log +* /perms log recent [user] [page] - luckperms.log.recent +* /perms log search \ [page] - luckperms.log.search +* /perms log notify [on|off] - luckperms.log.notify +* /perms log userhistory \ [page] - luckperms.log.userhistory +* /perms log grouphistory \ [page] - luckperms.log.grouphistory +* /perms log trackhistory \ [page] - luckperms.log.trackhistory + ## License See LICENSE.md. \ No newline at end of file diff --git a/api/pom.xml b/api/pom.xml index 99c7a678f..985de3da0 100644 --- a/api/pom.xml +++ b/api/pom.xml @@ -5,7 +5,7 @@ luckperms me.lucko.luckperms - 2.2 + 2.3 4.0.0 diff --git a/api/src/main/java/me/lucko/luckperms/api/Datastore.java b/api/src/main/java/me/lucko/luckperms/api/Datastore.java index 18c94f1b3..84873d66b 100644 --- a/api/src/main/java/me/lucko/luckperms/api/Datastore.java +++ b/api/src/main/java/me/lucko/luckperms/api/Datastore.java @@ -40,8 +40,11 @@ public interface Datastore { Async async(); Sync sync(); + Future future(); interface Async { + void logAction(LogEntry entry, Callback callback); + void getLog(Callback callback); void loadOrCreateUser(UUID uuid, String username, Callback callback); void loadUser(UUID uuid, Callback callback); void saveUser(User user, Callback callback); @@ -60,6 +63,8 @@ public interface Datastore { } interface Sync { + boolean logAction(LogEntry entry); + Log getLog(); boolean loadOrCreateUser(UUID uuid, String username); boolean loadUser(UUID uuid); boolean saveUser(User user); @@ -76,4 +81,24 @@ public interface Datastore { boolean saveUUIDData(String username, UUID uuid); UUID getUUID(String username); } + + interface Future { + java.util.concurrent.Future logAction(LogEntry entry); + java.util.concurrent.Future getLog(); + java.util.concurrent.Future loadOrCreateUser(UUID uuid, String username); + java.util.concurrent.Future loadUser(UUID uuid); + java.util.concurrent.Future saveUser(User user); + java.util.concurrent.Future createAndLoadGroup(String name); + java.util.concurrent.Future loadGroup(String name); + java.util.concurrent.Future loadAllGroups(); + java.util.concurrent.Future saveGroup(Group group); + java.util.concurrent.Future deleteGroup(Group group); + java.util.concurrent.Future createAndLoadTrack(String name); + java.util.concurrent.Future loadTrack(String name); + java.util.concurrent.Future loadAllTracks(); + java.util.concurrent.Future saveTrack(Track track); + java.util.concurrent.Future deleteTrack(Track track); + java.util.concurrent.Future saveUUIDData(String username, UUID uuid); + java.util.concurrent.Future getUUID(String username); + } } diff --git a/api/src/main/java/me/lucko/luckperms/api/Log.java b/api/src/main/java/me/lucko/luckperms/api/Log.java new file mode 100644 index 000000000..653b7393b --- /dev/null +++ b/api/src/main/java/me/lucko/luckperms/api/Log.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2016 Lucko (Luck) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.luckperms.api; + +import java.util.SortedMap; +import java.util.SortedSet; +import java.util.UUID; + +/** + * Represents the internal LuckPerms log. + * All content is immutable. You can add to the log using the {@link Datastore}, and then request an updated copy. + */ +@SuppressWarnings("unused") +public interface Log { + + /** + * @return a {@link SortedSet} of all of the {@link LogEntry} objects in this {@link Log} + */ + SortedSet getContent(); + + SortedSet getRecent(); + SortedMap getRecent(int pageNo); + int getRecentMaxPages(); + + SortedSet getRecent(UUID actor); + SortedMap getRecent(int pageNo, UUID actor); + int getRecentMaxPages(UUID actor); + + SortedSet getUserHistory(UUID uuid); + SortedMap getUserHistory(int pageNo, UUID uuid); + int getUserHistoryMaxPages(UUID uuid); + + SortedSet getGroupHistory(String name); + SortedMap getGroupHistory(int pageNo, String name); + int getGroupHistoryMaxPages(String name); + + SortedSet getTrackHistory(String name); + SortedMap getTrackHistory(int pageNo, String name); + int getTrackHistoryMaxPages(String name); + + SortedSet getSearch(String query); + SortedMap getSearch(int pageNo, String query); + int getSearchMaxPages(String query); +} diff --git a/api/src/main/java/me/lucko/luckperms/api/LogEntry.java b/api/src/main/java/me/lucko/luckperms/api/LogEntry.java new file mode 100644 index 000000000..de5f9694f --- /dev/null +++ b/api/src/main/java/me/lucko/luckperms/api/LogEntry.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2016 Lucko (Luck) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.luckperms.api; + +import lombok.*; + +import java.util.UUID; + +@Getter +@Builder +@ToString +@EqualsAndHashCode +@AllArgsConstructor +public final class LogEntry implements Comparable { + private static final String FORMAT = "&8(&e%s&8) [&a%s&8] (&b%s&8) &7--> &f%s"; + + @NonNull private final long timestamp; + @NonNull private final UUID actor; + @NonNull private final String actorName; + @NonNull private final char type; + private final UUID acted; + @NonNull private final String actedName; + @NonNull private final String action; + + @Override + public int compareTo(LogEntry o) { + return Long.compare(timestamp, o.getTimestamp()); + } + + public boolean matchesSearch(String query) { + query = query.toLowerCase(); + return actorName.toLowerCase().contains(query) || actedName.toLowerCase().contains(query) + || action.toLowerCase().contains(query); + } + + public String getFormatted() { + return String.format(FORMAT, + getActorName(), + Character.toString(getType()), + getActedName(), + getAction() + ); + } +} diff --git a/api/src/main/java/me/lucko/luckperms/api/LuckPermsApi.java b/api/src/main/java/me/lucko/luckperms/api/LuckPermsApi.java index 78e7a9a0f..043ac5662 100644 --- a/api/src/main/java/me/lucko/luckperms/api/LuckPermsApi.java +++ b/api/src/main/java/me/lucko/luckperms/api/LuckPermsApi.java @@ -23,6 +23,7 @@ package me.lucko.luckperms.api; import java.util.Optional; +import java.util.Set; import java.util.UUID; /** @@ -82,7 +83,7 @@ public interface LuckPermsApi { /** * Gets a wrapped user object from the user storage * @param name the username of the user to get - * @return a a {@link User} object, if one matching the uuid is loaded, or null if not + * @return a {@link User} object, if one matching the uuid is loaded, or null if not */ User getUser(String name); @@ -93,6 +94,12 @@ public interface LuckPermsApi { */ Optional getUserSafe(String name); + /** + * Gets a set of all loaded users. + * @return a {@link Set} of {@link User} objects + */ + Set getUsers(); + /** * Check if a user is loaded in memory * @param uuid the uuid to check for @@ -114,6 +121,12 @@ public interface LuckPermsApi { */ Optional getGroupSafe(String name); + /** + * Gets a set of all loaded groups. + * @return a {@link Set} of {@link Group} objects + */ + Set getGroups(); + /** * Check if a group is loaded in memory * @param name the name to check for @@ -135,6 +148,12 @@ public interface LuckPermsApi { */ Optional getTrackSafe(String name); + /** + * Gets a set of all loaded tracks. + * @return a {@link Set} of {@link Track} objects + */ + Set getTracks(); + /** * Check if a track is loaded in memory * @param name the name to check for diff --git a/api/src/main/java/me/lucko/luckperms/api/data/Callback.java b/api/src/main/java/me/lucko/luckperms/api/data/Callback.java index a772b0c5f..d23314713 100644 --- a/api/src/main/java/me/lucko/luckperms/api/data/Callback.java +++ b/api/src/main/java/me/lucko/luckperms/api/data/Callback.java @@ -22,8 +22,24 @@ package me.lucko.luckperms.api.data; +import lombok.NonNull; + +import java.util.function.Consumer; + public interface Callback { void onComplete(T t); + static Callback empty() { + return t -> {}; + } + + static Callback of(@NonNull Runnable runnable) { + return t -> runnable.run(); + } + + static Callback of(@NonNull Consumer consumer) { + return consumer::accept; + } + } diff --git a/bukkit/pom.xml b/bukkit/pom.xml index 7ea50c59a..13e3a2413 100644 --- a/bukkit/pom.xml +++ b/bukkit/pom.xml @@ -5,7 +5,7 @@ luckperms me.lucko.luckperms - 2.2 + 2.3 4.0.0 diff --git a/bukkit/src/main/java/me/lucko/luckperms/BukkitCommand.java b/bukkit/src/main/java/me/lucko/luckperms/BukkitCommand.java index 0df3a5fbb..289c174f2 100644 --- a/bukkit/src/main/java/me/lucko/luckperms/BukkitCommand.java +++ b/bukkit/src/main/java/me/lucko/luckperms/BukkitCommand.java @@ -22,8 +22,8 @@ package me.lucko.luckperms; +import me.lucko.luckperms.api.data.Callback; import me.lucko.luckperms.commands.CommandManager; -import me.lucko.luckperms.commands.SenderFactory; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; @@ -33,33 +33,19 @@ import java.util.Arrays; import java.util.List; class BukkitCommand extends CommandManager implements CommandExecutor, TabExecutor { - private static final Factory FACTORY = new Factory(); - BukkitCommand(LuckPermsPlugin plugin) { super(plugin); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - return onCommand(FACTORY.wrap(sender), label, Arrays.asList(args)); + onCommand(BukkitSenderFactory.get().wrap(sender), label, Arrays.asList(args), Callback.empty()); + return true; } @Override public List onTabComplete(CommandSender sender, Command command, String label, String[] args) { - return onTabComplete(FACTORY.wrap(sender), Arrays.asList(args)); - } - - private static class Factory extends SenderFactory { - - @Override - protected void sendMessage(CommandSender sender, String s) { - sender.sendMessage(s); - } - - @Override - protected boolean hasPermission(CommandSender sender, String node) { - return sender.hasPermission(node); - } + return onTabComplete(BukkitSenderFactory.get().wrap(sender), Arrays.asList(args)); } } diff --git a/bukkit/src/main/java/me/lucko/luckperms/BukkitConfig.java b/bukkit/src/main/java/me/lucko/luckperms/BukkitConfig.java index 3aac851f1..873dd9b66 100644 --- a/bukkit/src/main/java/me/lucko/luckperms/BukkitConfig.java +++ b/bukkit/src/main/java/me/lucko/luckperms/BukkitConfig.java @@ -22,7 +22,7 @@ package me.lucko.luckperms; -import me.lucko.luckperms.utils.LPConfiguration; +import me.lucko.luckperms.core.LPConfiguration; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; diff --git a/bukkit/src/main/java/me/lucko/luckperms/BukkitListener.java b/bukkit/src/main/java/me/lucko/luckperms/BukkitListener.java index 4d4dabd54..cc3fd52e8 100644 --- a/bukkit/src/main/java/me/lucko/luckperms/BukkitListener.java +++ b/bukkit/src/main/java/me/lucko/luckperms/BukkitListener.java @@ -53,7 +53,7 @@ class BukkitListener extends AbstractListener implements Listener { @EventHandler public void onPlayerLogin(PlayerLoginEvent e) { final Player player = e.getPlayer(); - final User user = plugin.getUserManager().getUser(plugin.getUuidCache().getUUID(player.getUniqueId())); + final User user = plugin.getUserManager().get(plugin.getUuidCache().getUUID(player.getUniqueId())); if (user == null) { e.disallow(PlayerLoginEvent.Result.KICK_OTHER, Message.LOADING_ERROR.toString()); diff --git a/bukkit/src/main/java/me/lucko/luckperms/BukkitSenderFactory.java b/bukkit/src/main/java/me/lucko/luckperms/BukkitSenderFactory.java new file mode 100644 index 000000000..219f1ed46 --- /dev/null +++ b/bukkit/src/main/java/me/lucko/luckperms/BukkitSenderFactory.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2016 Lucko (Luck) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.luckperms; + +import lombok.AccessLevel; +import lombok.NoArgsConstructor; +import me.lucko.luckperms.commands.SenderFactory; +import me.lucko.luckperms.constants.Constants; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.UUID; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class BukkitSenderFactory extends SenderFactory { + private static BukkitSenderFactory instance = null; + public static BukkitSenderFactory get() { + if (instance == null){ + instance = new BukkitSenderFactory(); + } + return instance; + } + + @Override + protected String getName(CommandSender sender) { + if (sender instanceof Player) { + return sender.getName(); + } + return Constants.getConsoleName(); + } + + @Override + protected UUID getUuid(CommandSender sender) { + if (sender instanceof Player) { + return ((Player) sender).getUniqueId(); + } + return Constants.getConsoleUUID(); + } + + @Override + protected void sendMessage(CommandSender sender, String s) { + sender.sendMessage(s); + } + + @Override + protected boolean hasPermission(CommandSender sender, String node) { + return sender.hasPermission(node); + } +} diff --git a/bukkit/src/main/java/me/lucko/luckperms/LPBukkitPlugin.java b/bukkit/src/main/java/me/lucko/luckperms/LPBukkitPlugin.java index 111984060..65a6ff687 100644 --- a/bukkit/src/main/java/me/lucko/luckperms/LPBukkitPlugin.java +++ b/bukkit/src/main/java/me/lucko/luckperms/LPBukkitPlugin.java @@ -27,19 +27,20 @@ import me.lucko.luckperms.api.Logger; import me.lucko.luckperms.api.LuckPermsApi; import me.lucko.luckperms.api.implementation.ApiProvider; import me.lucko.luckperms.api.vault.VaultHook; +import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.constants.Message; -import me.lucko.luckperms.data.Datastore; -import me.lucko.luckperms.data.methods.FlatfileDatastore; -import me.lucko.luckperms.data.methods.MySQLDatastore; -import me.lucko.luckperms.data.methods.SQLiteDatastore; +import me.lucko.luckperms.core.LPConfiguration; +import me.lucko.luckperms.core.UuidCache; import me.lucko.luckperms.groups.GroupManager; import me.lucko.luckperms.runnables.UpdateTask; +import me.lucko.luckperms.storage.Datastore; +import me.lucko.luckperms.storage.methods.FlatfileDatastore; +import me.lucko.luckperms.storage.methods.MySQLDatastore; +import me.lucko.luckperms.storage.methods.SQLiteDatastore; import me.lucko.luckperms.tracks.TrackManager; import me.lucko.luckperms.users.BukkitUserManager; import me.lucko.luckperms.users.UserManager; -import me.lucko.luckperms.utils.LPConfiguration; -import me.lucko.luckperms.utils.LogUtil; -import me.lucko.luckperms.utils.UuidCache; +import me.lucko.luckperms.utils.LogFactory; import org.bukkit.command.PluginCommand; import org.bukkit.entity.Player; import org.bukkit.plugin.PluginManager; @@ -47,14 +48,12 @@ import org.bukkit.plugin.ServicePriority; import org.bukkit.plugin.java.JavaPlugin; import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.UUID; +import java.util.*; import java.util.stream.Collectors; @Getter public class LPBukkitPlugin extends JavaPlugin implements LuckPermsPlugin { + private final Set ignoringLogs = new HashSet<>(); private LPConfiguration configuration; private UserManager userManager; private GroupManager groupManager; @@ -65,7 +64,7 @@ public class LPBukkitPlugin extends JavaPlugin implements LuckPermsPlugin { @Override public void onEnable() { - log = LogUtil.wrap(getLogger()); + log = LogFactory.wrap(getLogger()); getLog().info("Loading configuration..."); configuration = new BukkitConfig(this); @@ -121,6 +120,8 @@ public class LPBukkitPlugin extends JavaPlugin implements LuckPermsPlugin { getServer().getScheduler().runTaskTimerAsynchronously(this, new UpdateTask(this), ticks, ticks); } + getServer().getScheduler().runTaskTimer(this, BukkitSenderFactory.get(), 1L, 1L); + // Provide vault support getLog().info("Attempting to hook into Vault..."); try { @@ -183,6 +184,11 @@ public class LPBukkitPlugin extends JavaPlugin implements LuckPermsPlugin { return getServer().getOnlinePlayers().stream().map(Player::getName).collect(Collectors.toList()); } + @Override + public List getSenders() { + return getServer().getOnlinePlayers().stream().map(p -> BukkitSenderFactory.get().wrap(p)).collect(Collectors.toList()); + } + @Override public List getPossiblePermissions() { final List perms = new ArrayList<>(); diff --git a/bukkit/src/main/java/me/lucko/luckperms/api/vault/VaultPermissionHook.java b/bukkit/src/main/java/me/lucko/luckperms/api/vault/VaultPermissionHook.java index 750788573..2cc0dc52a 100644 --- a/bukkit/src/main/java/me/lucko/luckperms/api/vault/VaultPermissionHook.java +++ b/bukkit/src/main/java/me/lucko/luckperms/api/vault/VaultPermissionHook.java @@ -25,11 +25,12 @@ package me.lucko.luckperms.api.vault; import lombok.NonNull; import lombok.Setter; import me.lucko.luckperms.LPBukkitPlugin; +import me.lucko.luckperms.api.data.Callback; +import me.lucko.luckperms.core.PermissionHolder; import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import me.lucko.luckperms.exceptions.ObjectLacksException; import me.lucko.luckperms.groups.Group; import me.lucko.luckperms.users.User; -import me.lucko.luckperms.utils.PermissionHolder; import net.milkbowl.vault.permission.Permission; class VaultPermissionHook extends Permission { @@ -95,54 +96,54 @@ class VaultPermissionHook extends Permission { private void objectSave(PermissionHolder t) { if (t instanceof User) { ((User) t).refreshPermissions(); - plugin.getDatastore().saveUser(((User) t), aBoolean -> {}); + plugin.getDatastore().saveUser(((User) t), Callback.empty()); } if (t instanceof Group) { - plugin.getDatastore().saveGroup(((Group) t), aBoolean -> plugin.runUpdateTask()); + plugin.getDatastore().saveGroup(((Group) t), c -> plugin.runUpdateTask()); } } @Override public boolean playerHas(String world, @NonNull String player, @NonNull String permission) { - return objectHas(world, plugin.getUserManager().getUser(player), permission); + return objectHas(world, plugin.getUserManager().get(player), permission); } @Override public boolean playerAdd(String world, @NonNull String player, @NonNull String permission) { - final User user = plugin.getUserManager().getUser(player); + final User user = plugin.getUserManager().get(player); return objectAdd(world, user, permission); } @Override public boolean playerRemove(String world, @NonNull String player, @NonNull String permission) { - final User user = plugin.getUserManager().getUser(player); + final User user = plugin.getUserManager().get(player); return objectRemove(world, user, permission); } @Override public boolean groupHas(String world, @NonNull String groupName, @NonNull String permission) { - final Group group = plugin.getGroupManager().getGroup(groupName); + final Group group = plugin.getGroupManager().get(groupName); return objectHas(world, group, permission); } @Override public boolean groupAdd(String world, @NonNull String groupName, @NonNull String permission) { - final Group group = plugin.getGroupManager().getGroup(groupName); + final Group group = plugin.getGroupManager().get(groupName); return objectAdd(world, group, permission); } @Override public boolean groupRemove(String world, @NonNull String groupName, @NonNull String permission) { - final Group group = plugin.getGroupManager().getGroup(groupName); + final Group group = plugin.getGroupManager().get(groupName); return objectRemove(world, group, permission); } @Override public boolean playerInGroup(String world, @NonNull String player, @NonNull String group) { - final User user = plugin.getUserManager().getUser(player); + final User user = plugin.getUserManager().get(player); if (user == null) return false; - final Group group1 = plugin.getGroupManager().getGroup(group); + final Group group1 = plugin.getGroupManager().get(group); if (group1 == null) return false; if (world != null && !world.equals("")) { @@ -154,10 +155,10 @@ class VaultPermissionHook extends Permission { @Override public boolean playerAddGroup(String world, @NonNull String player, @NonNull String groupName) { - final User user = plugin.getUserManager().getUser(player); + final User user = plugin.getUserManager().get(player); if (user == null) return false; - final Group group = plugin.getGroupManager().getGroup(groupName); + final Group group = plugin.getGroupManager().get(groupName); if (group == null) return false; try { @@ -173,10 +174,10 @@ class VaultPermissionHook extends Permission { @Override public boolean playerRemoveGroup(String world, @NonNull String player, @NonNull String groupName) { - final User user = plugin.getUserManager().getUser(player); + final User user = plugin.getUserManager().get(player); if (user == null) return false; - final Group group = plugin.getGroupManager().getGroup(groupName); + final Group group = plugin.getGroupManager().get(groupName); if (group == null) return false; try { @@ -192,7 +193,7 @@ class VaultPermissionHook extends Permission { @Override public String[] getPlayerGroups(String world, @NonNull String player) { - final User user = plugin.getUserManager().getUser(player); + final User user = plugin.getUserManager().get(player); return (user == null) ? new String[0] : world != null && !world.equals("") ? user.getLocalGroups("global", world).toArray(new String[0]) : user.getGroupNames().toArray(new String[0]); @@ -200,13 +201,13 @@ class VaultPermissionHook extends Permission { @Override public String getPrimaryGroup(String world, @NonNull String player) { - final User user = plugin.getUserManager().getUser(player); + final User user = plugin.getUserManager().get(player); return (user == null) ? null : user.getPrimaryGroup(); } @Override public String[] getGroups() { - return plugin.getGroupManager().getGroups().keySet().toArray(new String[0]); + return plugin.getGroupManager().getAll().keySet().toArray(new String[0]); } @Override diff --git a/bukkit/src/main/java/me/lucko/luckperms/users/BukkitUserManager.java b/bukkit/src/main/java/me/lucko/luckperms/users/BukkitUserManager.java index 2df83a8c9..e6eef2dca 100644 --- a/bukkit/src/main/java/me/lucko/luckperms/users/BukkitUserManager.java +++ b/bukkit/src/main/java/me/lucko/luckperms/users/BukkitUserManager.java @@ -38,7 +38,7 @@ public class BukkitUserManager extends UserManager { } @Override - public void unloadUser(User user) { + public void unload(User user) { if (user != null) { if (user instanceof BukkitUser) { @@ -54,24 +54,24 @@ public class BukkitUserManager extends UserManager { } } - getUsers().remove(user.getUuid()); + getAll().remove(user.getUuid()); } } @Override - public void cleanupUser(User user) { + public void cleanup(User user) { if (plugin.getServer().getPlayer(plugin.getUuidCache().getExternalUUID(user.getUuid())) == null) { - unloadUser(user); + unload(user); } } @Override - public User makeUser(UUID uuid) { + public User make(UUID uuid) { return new BukkitUser(uuid, plugin); } @Override - public User makeUser(UUID uuid, String username) { + public User make(UUID uuid, String username) { return new BukkitUser(uuid, username, plugin); } diff --git a/bukkit/src/main/resources/plugin.yml b/bukkit/src/main/resources/plugin.yml index 96452f809..9197974d6 100644 --- a/bukkit/src/main/resources/plugin.yml +++ b/bukkit/src/main/resources/plugin.yml @@ -59,6 +59,13 @@ permissions: luckperms.track.insert: true luckperms.track.remove: true luckperms.track.clear: true + luckperms.log.export: true + luckperms.log.userhistory: true + luckperms.log.grouphistory: true + luckperms.log.trackhistory: true + luckperms.log.notify: true + luckperms.log.recent: true + luckperms.log.search: true luckperms.user.*: description: Gives access to all LuckPerms user commands children: @@ -105,4 +112,14 @@ permissions: luckperms.track.append: true luckperms.track.insert: true luckperms.track.remove: true - luckperms.track.clear: true \ No newline at end of file + luckperms.track.clear: true + luckperms.log.*: + description: Gives access to all LuckPerms log commands + children: + luckperms.log.export: true + luckperms.log.userhistory: true + luckperms.log.grouphistory: true + luckperms.log.trackhistory: true + luckperms.log.notify: true + luckperms.log.recent: true + luckperms.log.search: true \ No newline at end of file diff --git a/bungee/pom.xml b/bungee/pom.xml index ab2779965..b765770aa 100644 --- a/bungee/pom.xml +++ b/bungee/pom.xml @@ -5,7 +5,7 @@ luckperms me.lucko.luckperms - 2.2 + 2.3 4.0.0 diff --git a/bungee/src/main/java/me/lucko/luckperms/BungeeCommand.java b/bungee/src/main/java/me/lucko/luckperms/BungeeCommand.java index 05bd53786..1794b5527 100644 --- a/bungee/src/main/java/me/lucko/luckperms/BungeeCommand.java +++ b/bungee/src/main/java/me/lucko/luckperms/BungeeCommand.java @@ -22,44 +22,29 @@ package me.lucko.luckperms; +import me.lucko.luckperms.api.data.Callback; import me.lucko.luckperms.commands.CommandManager; -import me.lucko.luckperms.commands.SenderFactory; import net.md_5.bungee.api.CommandSender; -import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.plugin.Command; import net.md_5.bungee.api.plugin.TabExecutor; import java.util.Arrays; class BungeeCommand extends Command implements TabExecutor { - private static final Factory FACTORY = new Factory(); private final CommandManager manager; - public BungeeCommand(CommandManager manager) { + BungeeCommand(CommandManager manager) { super("luckpermsbungee", null, "bperms", "lpb", "bpermissions", "bp", "bperm"); this.manager = manager; } @Override public void execute(CommandSender sender, String[] args) { - manager.onCommand(FACTORY.wrap(sender), "bperms", Arrays.asList(args)); + manager.onCommand(BungeeSenderFactory.get().wrap(sender), "bperms", Arrays.asList(args), Callback.empty()); } @Override public Iterable onTabComplete(CommandSender sender, String[] args) { - return manager.onTabComplete(FACTORY.wrap(sender), Arrays.asList(args)); - } - - private static class Factory extends SenderFactory { - - @Override - protected void sendMessage(CommandSender sender, String s) { - sender.sendMessage(new TextComponent(s)); - } - - @Override - protected boolean hasPermission(CommandSender sender, String node) { - return sender.hasPermission(node); - } + return manager.onTabComplete(BungeeSenderFactory.get().wrap(sender), Arrays.asList(args)); } } diff --git a/bungee/src/main/java/me/lucko/luckperms/BungeeConfig.java b/bungee/src/main/java/me/lucko/luckperms/BungeeConfig.java index e75e92a3b..349cd9855 100644 --- a/bungee/src/main/java/me/lucko/luckperms/BungeeConfig.java +++ b/bungee/src/main/java/me/lucko/luckperms/BungeeConfig.java @@ -22,7 +22,7 @@ package me.lucko.luckperms; -import me.lucko.luckperms.utils.LPConfiguration; +import me.lucko.luckperms.core.LPConfiguration; import net.md_5.bungee.config.Configuration; import net.md_5.bungee.config.ConfigurationProvider; import net.md_5.bungee.config.YamlConfiguration; diff --git a/bungee/src/main/java/me/lucko/luckperms/BungeeListener.java b/bungee/src/main/java/me/lucko/luckperms/BungeeListener.java index c0ac23b77..3aa871525 100644 --- a/bungee/src/main/java/me/lucko/luckperms/BungeeListener.java +++ b/bungee/src/main/java/me/lucko/luckperms/BungeeListener.java @@ -23,9 +23,9 @@ package me.lucko.luckperms; import me.lucko.luckperms.constants.Message; +import me.lucko.luckperms.core.UuidCache; import me.lucko.luckperms.users.User; import me.lucko.luckperms.utils.AbstractListener; -import me.lucko.luckperms.utils.UuidCache; import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.connection.PendingConnection; import net.md_5.bungee.api.connection.ProxiedPlayer; @@ -55,7 +55,7 @@ class BungeeListener extends AbstractListener implements Listener { } final ProxiedPlayer player = ((ProxiedPlayer) e.getSender()); - final User user = plugin.getUserManager().getUser(plugin.getUuidCache().getUUID(player.getUniqueId())); + final User user = plugin.getUserManager().get(plugin.getUuidCache().getUUID(player.getUniqueId())); if (user == null) return; @@ -110,7 +110,7 @@ class BungeeListener extends AbstractListener implements Listener { final ProxiedPlayer player = e.getPlayer(); final WeakReference p = new WeakReference<>(player); - final User user = plugin.getUserManager().getUser(plugin.getUuidCache().getUUID(e.getPlayer().getUniqueId())); + final User user = plugin.getUserManager().get(plugin.getUuidCache().getUUID(e.getPlayer().getUniqueId())); if (user == null) { plugin.getProxy().getScheduler().schedule(plugin, () -> { final ProxiedPlayer pl = p.get(); diff --git a/bungee/src/main/java/me/lucko/luckperms/BungeeSenderFactory.java b/bungee/src/main/java/me/lucko/luckperms/BungeeSenderFactory.java new file mode 100644 index 000000000..8c04aba83 --- /dev/null +++ b/bungee/src/main/java/me/lucko/luckperms/BungeeSenderFactory.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2016 Lucko (Luck) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.luckperms; + +import lombok.AccessLevel; +import lombok.NoArgsConstructor; +import me.lucko.luckperms.commands.SenderFactory; +import me.lucko.luckperms.constants.Constants; +import net.md_5.bungee.api.CommandSender; +import net.md_5.bungee.api.chat.TextComponent; +import net.md_5.bungee.api.connection.ProxiedPlayer; + +import java.util.UUID; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class BungeeSenderFactory extends SenderFactory { + private static BungeeSenderFactory instance = null; + public static BungeeSenderFactory get() { + if (instance == null){ + instance = new BungeeSenderFactory(); + } + return instance; + } + + @Override + protected String getName(CommandSender sender) { + if (sender instanceof ProxiedPlayer) { + return sender.getName(); + } + return Constants.getConsoleName(); + } + + @Override + protected UUID getUuid(CommandSender sender) { + if (sender instanceof ProxiedPlayer) { + return ((ProxiedPlayer) sender).getUniqueId(); + } + return Constants.getConsoleUUID(); + } + + @Override + protected void sendMessage(CommandSender sender, String s) { + sender.sendMessage(new TextComponent(s)); + } + + @Override + protected boolean hasPermission(CommandSender sender, String node) { + return sender.hasPermission(node); + } +} diff --git a/bungee/src/main/java/me/lucko/luckperms/LPBungeePlugin.java b/bungee/src/main/java/me/lucko/luckperms/LPBungeePlugin.java index 6378ff542..f0b8e181b 100644 --- a/bungee/src/main/java/me/lucko/luckperms/LPBungeePlugin.java +++ b/bungee/src/main/java/me/lucko/luckperms/LPBungeePlugin.java @@ -26,29 +26,29 @@ import lombok.Getter; import me.lucko.luckperms.api.Logger; import me.lucko.luckperms.api.implementation.ApiProvider; import me.lucko.luckperms.commands.CommandManager; +import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.constants.Message; -import me.lucko.luckperms.data.Datastore; -import me.lucko.luckperms.data.methods.FlatfileDatastore; -import me.lucko.luckperms.data.methods.MySQLDatastore; +import me.lucko.luckperms.core.LPConfiguration; +import me.lucko.luckperms.core.UuidCache; import me.lucko.luckperms.groups.GroupManager; import me.lucko.luckperms.runnables.UpdateTask; +import me.lucko.luckperms.storage.Datastore; +import me.lucko.luckperms.storage.methods.FlatfileDatastore; +import me.lucko.luckperms.storage.methods.MySQLDatastore; import me.lucko.luckperms.tracks.TrackManager; import me.lucko.luckperms.users.BungeeUserManager; import me.lucko.luckperms.users.UserManager; -import me.lucko.luckperms.utils.LPConfiguration; -import me.lucko.luckperms.utils.LogUtil; -import me.lucko.luckperms.utils.UuidCache; +import me.lucko.luckperms.utils.LogFactory; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Plugin; -import java.util.Collections; -import java.util.List; -import java.util.UUID; +import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @Getter public class LPBungeePlugin extends Plugin implements LuckPermsPlugin { + private final Set ignoringLogs = new HashSet<>(); private LPConfiguration configuration; private UserManager userManager; private GroupManager groupManager; @@ -59,7 +59,7 @@ public class LPBungeePlugin extends Plugin implements LuckPermsPlugin { @Override public void onEnable() { - log = LogUtil.wrap(getLogger()); + log = LogFactory.wrap(getLogger()); getLog().info("Loading configuration..."); configuration = new BungeeConfig(this); @@ -109,6 +109,9 @@ public class LPBungeePlugin extends Plugin implements LuckPermsPlugin { getProxy().getScheduler().schedule(this, new UpdateTask(this), mins, mins, TimeUnit.MINUTES); } + // 20 times per second (once per "tick") + getProxy().getScheduler().schedule(this, BungeeSenderFactory.get(), 50L, 50L, TimeUnit.MILLISECONDS); + getLog().info("Registering API..."); LuckPerms.registerProvider(new ApiProvider(this)); @@ -144,6 +147,11 @@ public class LPBungeePlugin extends Plugin implements LuckPermsPlugin { return getProxy().getPlayers().stream().map(ProxiedPlayer::getName).collect(Collectors.toList()); } + @Override + public List getSenders() { + return getProxy().getPlayers().stream().map(p -> BungeeSenderFactory.get().wrap(p)).collect(Collectors.toList()); + } + @Override public List getPossiblePermissions() { // No such thing on Bungee. Wildcards are processed in the listener instead. diff --git a/bungee/src/main/java/me/lucko/luckperms/users/BungeeUserManager.java b/bungee/src/main/java/me/lucko/luckperms/users/BungeeUserManager.java index 37034cb95..8ff79af73 100644 --- a/bungee/src/main/java/me/lucko/luckperms/users/BungeeUserManager.java +++ b/bungee/src/main/java/me/lucko/luckperms/users/BungeeUserManager.java @@ -35,28 +35,28 @@ public class BungeeUserManager extends UserManager { } @Override - public void unloadUser(User user) { + public void unload(User user) { if (user != null) { // Cannot clear the ProxiedPlayer's permission map, they're leaving so that will get GCed anyway // Calling getPermissions.clear() throws an UnsupportedOperationException - getUsers().remove(user.getUuid()); + getAll().remove(user.getUuid()); } } @Override - public void cleanupUser(User user) { + public void cleanup(User user) { if (plugin.getProxy().getPlayer(plugin.getUuidCache().getExternalUUID(user.getUuid())) == null) { - unloadUser(user); + unload(user); } } @Override - public User makeUser(UUID uuid) { + public User make(UUID uuid) { return new BungeeUser(uuid, plugin); } @Override - public User makeUser(UUID uuid, String username) { + public User make(UUID uuid, String username) { return new BungeeUser(uuid, username, plugin); } diff --git a/common/pom.xml b/common/pom.xml index aead2a23f..37e7df71b 100644 --- a/common/pom.xml +++ b/common/pom.xml @@ -5,7 +5,7 @@ luckperms me.lucko.luckperms - 2.2 + 2.3 4.0.0 @@ -53,6 +53,13 @@ 2.7 provided + + + com.google.guava + guava + 19.0 + provided + diff --git a/common/src/main/java/me/lucko/luckperms/LuckPermsPlugin.java b/common/src/main/java/me/lucko/luckperms/LuckPermsPlugin.java index 9662aec47..982eb7391 100644 --- a/common/src/main/java/me/lucko/luckperms/LuckPermsPlugin.java +++ b/common/src/main/java/me/lucko/luckperms/LuckPermsPlugin.java @@ -23,15 +23,17 @@ package me.lucko.luckperms; import me.lucko.luckperms.api.Logger; +import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.constants.Message; -import me.lucko.luckperms.data.Datastore; +import me.lucko.luckperms.core.LPConfiguration; +import me.lucko.luckperms.core.UuidCache; import me.lucko.luckperms.groups.GroupManager; +import me.lucko.luckperms.storage.Datastore; import me.lucko.luckperms.tracks.TrackManager; import me.lucko.luckperms.users.UserManager; -import me.lucko.luckperms.utils.LPConfiguration; -import me.lucko.luckperms.utils.UuidCache; import java.util.List; +import java.util.Set; import java.util.UUID; /** @@ -106,12 +108,24 @@ public interface LuckPermsPlugin { */ List getPlayerList(); + /** + * Gets a list of all Senders online on the platform + * @return a {@link List} of senders + */ + List getSenders(); + /** * Gets all possible permission nodes, used for resolving wildcards * @return a {@link List} of permission nodes */ List getPossiblePermissions(); + /** + * Gets a set of players ignoring logging output + * @return a {@link Set} of uuids + */ + Set getIgnoringLogs(); + /** * Runs an update task */ diff --git a/common/src/main/java/me/lucko/luckperms/api/implementation/ApiProvider.java b/common/src/main/java/me/lucko/luckperms/api/implementation/ApiProvider.java index 9f43fb809..af80c1733 100644 --- a/common/src/main/java/me/lucko/luckperms/api/implementation/ApiProvider.java +++ b/common/src/main/java/me/lucko/luckperms/api/implementation/ApiProvider.java @@ -29,7 +29,9 @@ import me.lucko.luckperms.api.*; import me.lucko.luckperms.api.implementation.internal.*; import java.util.Optional; +import java.util.Set; import java.util.UUID; +import java.util.stream.Collectors; /** * Provides static access to LuckPerms @@ -70,7 +72,7 @@ public class ApiProvider implements LuckPermsApi { @Override public User getUser(@NonNull UUID uuid) { - final me.lucko.luckperms.users.User user = plugin.getUserManager().getUser(uuid); + final me.lucko.luckperms.users.User user = plugin.getUserManager().get(uuid); if (user == null) { return null; } @@ -85,7 +87,7 @@ public class ApiProvider implements LuckPermsApi { @Override public User getUser(@NonNull String name) { - final me.lucko.luckperms.users.User user = plugin.getUserManager().getUser(name); + final me.lucko.luckperms.users.User user = plugin.getUserManager().get(name); if (user == null) { return null; } @@ -98,6 +100,11 @@ public class ApiProvider implements LuckPermsApi { return Optional.ofNullable(getUser(name)); } + @Override + public Set getUsers() { + return plugin.getUserManager().getAll().values().stream().map(UserLink::new).collect(Collectors.toSet()); + } + @Override public boolean isUserLoaded(@NonNull UUID uuid) { return plugin.getUserManager().isLoaded(uuid); @@ -105,7 +112,7 @@ public class ApiProvider implements LuckPermsApi { @Override public Group getGroup(@NonNull String name) { - final me.lucko.luckperms.groups.Group group = plugin.getGroupManager().getGroup(name); + final me.lucko.luckperms.groups.Group group = plugin.getGroupManager().get(name); if (group == null) { return null; } @@ -118,6 +125,11 @@ public class ApiProvider implements LuckPermsApi { return Optional.ofNullable(getGroup(name)); } + @Override + public Set getGroups() { + return plugin.getGroupManager().getAll().values().stream().map(GroupLink::new).collect(Collectors.toSet()); + } + @Override public boolean isGroupLoaded(@NonNull String name) { return plugin.getGroupManager().isLoaded(name); @@ -125,7 +137,7 @@ public class ApiProvider implements LuckPermsApi { @Override public Track getTrack(@NonNull String name) { - final me.lucko.luckperms.tracks.Track track = plugin.getTrackManager().getTrack(name); + final me.lucko.luckperms.tracks.Track track = plugin.getTrackManager().get(name); if (track == null) { return null; } @@ -138,6 +150,11 @@ public class ApiProvider implements LuckPermsApi { return Optional.ofNullable(getTrack(name)); } + @Override + public Set getTracks() { + return plugin.getTrackManager().getAll().values().stream().map(TrackLink::new).collect(Collectors.toSet()); + } + @Override public boolean isTrackLoaded(@NonNull String name) { return plugin.getTrackManager().isLoaded(name); diff --git a/common/src/main/java/me/lucko/luckperms/api/implementation/internal/DatastoreLink.java b/common/src/main/java/me/lucko/luckperms/api/implementation/internal/DatastoreLink.java index 9d0bd99d6..84265862b 100644 --- a/common/src/main/java/me/lucko/luckperms/api/implementation/internal/DatastoreLink.java +++ b/common/src/main/java/me/lucko/luckperms/api/implementation/internal/DatastoreLink.java @@ -22,41 +22,45 @@ package me.lucko.luckperms.api.implementation.internal; +import lombok.AccessLevel; import lombok.AllArgsConstructor; +import lombok.NoArgsConstructor; import lombok.NonNull; import me.lucko.luckperms.LuckPermsPlugin; -import me.lucko.luckperms.api.Datastore; -import me.lucko.luckperms.api.Group; -import me.lucko.luckperms.api.Track; -import me.lucko.luckperms.api.User; +import me.lucko.luckperms.api.*; import me.lucko.luckperms.api.data.Callback; import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import static me.lucko.luckperms.api.implementation.internal.Utils.*; /** - * Provides a link between {@link Datastore} and {@link me.lucko.luckperms.data.Datastore} + * Provides a link between {@link Datastore} and {@link me.lucko.luckperms.storage.Datastore} */ @SuppressWarnings({"unused", "WeakerAccess"}) public class DatastoreLink implements Datastore { private final LuckPermsPlugin plugin; - private final me.lucko.luckperms.data.Datastore master; + private final me.lucko.luckperms.storage.Datastore master; private final Async async; private final Sync sync; + private final Future future; - public DatastoreLink(@NonNull LuckPermsPlugin plugin, @NonNull me.lucko.luckperms.data.Datastore master) { + public DatastoreLink(@NonNull LuckPermsPlugin plugin, @NonNull me.lucko.luckperms.storage.Datastore master) { this.plugin = plugin; this.master = master; this.async = new Async(master); this.sync = new Sync(master); + this.future = new Future(master); } private static Callback checkCallback(Callback c) { // If no callback was given, just send an empty one if (c == null) { - c = t -> {}; + c = Callback.empty(); } return c; } @@ -72,18 +76,33 @@ public class DatastoreLink implements Datastore { } @Override - public Async async() { + public Datastore.Async async() { return async; } @Override - public Sync sync() { + public Datastore.Sync sync() { return sync; } + @Override + public Datastore.Future future() { + return future; + } + @AllArgsConstructor public class Async implements Datastore.Async { - private final me.lucko.luckperms.data.Datastore master; + private final me.lucko.luckperms.storage.Datastore master; + + @Override + public void logAction(@NonNull LogEntry entry, Callback callback) { + master.logAction(entry, checkCallback(callback)); + } + + @Override + public void getLog(Callback callback) { + master.getLog(log -> callback.onComplete(new LogLink(log))); + } @Override public void loadOrCreateUser(@NonNull UUID uuid, @NonNull String username, Callback callback) { @@ -171,7 +190,17 @@ public class DatastoreLink implements Datastore { @AllArgsConstructor public class Sync implements Datastore.Sync { - private final me.lucko.luckperms.data.Datastore master; + private final me.lucko.luckperms.storage.Datastore master; + + @Override + public boolean logAction(@NonNull LogEntry entry) { + return master.logAction(entry); + } + + @Override + public Log getLog() { + return new LogLink(master.getLog()); + } @Override public boolean loadOrCreateUser(@NonNull UUID uuid, @NonNull String username) { @@ -257,4 +286,179 @@ public class DatastoreLink implements Datastore { } } + @AllArgsConstructor + public class Future implements Datastore.Future { + private final me.lucko.luckperms.storage.Datastore master; + + @Override + public java.util.concurrent.Future logAction(@NonNull LogEntry entry) { + LPFuture lpf = new LPFuture<>(); + master.logAction(entry, lpf); + return lpf; + } + + @Override + public java.util.concurrent.Future getLog() { + LPFuture lpf = new LPFuture<>(); + master.getLog(log -> lpf.onComplete(new LogLink(log))); + return lpf; + } + + @Override + public java.util.concurrent.Future loadOrCreateUser(@NonNull UUID uuid, @NonNull String username) { + LPFuture lpf = new LPFuture<>(); + master.loadOrCreateUser(uuid, checkUsername(username), lpf); + return lpf; + } + + @Override + public java.util.concurrent.Future loadUser(@NonNull UUID uuid) { + LPFuture lpf = new LPFuture<>(); + master.loadUser(uuid, lpf); + return lpf; + } + + @Override + public java.util.concurrent.Future saveUser(@NonNull User user) { + LPFuture lpf = new LPFuture<>(); + checkUser(user); + master.saveUser(((UserLink) user).getMaster(), lpf); + return lpf; + } + + @Override + public java.util.concurrent.Future createAndLoadGroup(@NonNull String name) { + LPFuture lpf = new LPFuture<>(); + master.createAndLoadGroup(checkName(name), lpf); + return lpf; + } + + @Override + public java.util.concurrent.Future loadGroup(@NonNull String name) { + LPFuture lpf = new LPFuture<>(); + master.loadGroup(checkName(name), lpf); + return lpf; + } + + @Override + public java.util.concurrent.Future loadAllGroups() { + LPFuture lpf = new LPFuture<>(); + master.loadAllGroups(lpf); + return lpf; + } + + @Override + public java.util.concurrent.Future saveGroup(@NonNull Group group) { + LPFuture lpf = new LPFuture<>(); + checkGroup(group); + master.saveGroup(((GroupLink) group).getMaster(), lpf); + return lpf; + } + + @Override + public java.util.concurrent.Future deleteGroup(@NonNull Group group) { + LPFuture lpf = new LPFuture<>(); + checkGroup(group); + if (group.getName().equalsIgnoreCase(plugin.getConfiguration().getDefaultGroupName())) { + throw new IllegalArgumentException("Cannot delete the default group."); + } + master.deleteGroup(((GroupLink) group).getMaster(), lpf); + return lpf; + } + + @Override + public java.util.concurrent.Future createAndLoadTrack(@NonNull String name) { + LPFuture lpf = new LPFuture<>(); + master.createAndLoadTrack(checkName(name), lpf); + return lpf; + } + + @Override + public java.util.concurrent.Future loadTrack(@NonNull String name) { + LPFuture lpf = new LPFuture<>(); + master.loadTrack(checkName(name), lpf); + return lpf; + } + + @Override + public java.util.concurrent.Future loadAllTracks() { + LPFuture lpf = new LPFuture<>(); + master.loadAllTracks(lpf); + return lpf; + } + + @Override + public java.util.concurrent.Future saveTrack(@NonNull Track track) { + LPFuture lpf = new LPFuture<>(); + checkTrack(track); + master.saveTrack(((TrackLink) track).getMaster(), lpf); + return lpf; + } + + @Override + public java.util.concurrent.Future deleteTrack(@NonNull Track track) { + LPFuture lpf = new LPFuture<>(); + checkTrack(track); + master.deleteTrack(((TrackLink) track).getMaster(), lpf); + return lpf; + } + + @Override + public java.util.concurrent.Future saveUUIDData(@NonNull String username, @NonNull UUID uuid) { + LPFuture lpf = new LPFuture<>(); + master.saveUUIDData(checkUsername(username), uuid, lpf); + return lpf; + } + + @Override + public java.util.concurrent.Future getUUID(@NonNull String username) { + LPFuture lpf = new LPFuture<>(); + master.getUUID(checkUsername(username), lpf); + return lpf; + } + } + + @NoArgsConstructor(access = AccessLevel.PRIVATE) + public static class LPFuture implements Callback, java.util.concurrent.Future { + private final CountDownLatch latch = new CountDownLatch(1); + private T value; + + @Override + public void onComplete(T t) { + value = t; + latch.countDown(); + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + // Not supported + return false; + } + + @Override + public boolean isCancelled() { + return false; + } + + @Override + public boolean isDone() { + return latch.getCount() == 0; + } + + @Override + public T get() throws InterruptedException { + latch.await(); + return value; + } + + @Override + public T get(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { + if (latch.await(timeout, unit)) { + return value; + } else { + throw new TimeoutException(); + } + } + } + } diff --git a/common/src/main/java/me/lucko/luckperms/api/implementation/internal/GroupLink.java b/common/src/main/java/me/lucko/luckperms/api/implementation/internal/GroupLink.java index 67b33d2be..c2ac46a0b 100644 --- a/common/src/main/java/me/lucko/luckperms/api/implementation/internal/GroupLink.java +++ b/common/src/main/java/me/lucko/luckperms/api/implementation/internal/GroupLink.java @@ -23,6 +23,7 @@ package me.lucko.luckperms.api.implementation.internal; import lombok.AccessLevel; +import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NonNull; import me.lucko.luckperms.api.Group; @@ -36,20 +37,20 @@ import static me.lucko.luckperms.api.implementation.internal.Utils.*; /** * Provides a link between {@link Group} and {@link me.lucko.luckperms.groups.Group} */ +@EqualsAndHashCode(of = {"name"}, callSuper = false) @SuppressWarnings("unused") public class GroupLink extends PermissionHolderLink implements Group { @Getter(AccessLevel.PACKAGE) private final me.lucko.luckperms.groups.Group master; + @Getter + private final String name; + public GroupLink(@NonNull me.lucko.luckperms.groups.Group master) { super(master); this.master = master; - } - - @Override - public String getName() { - return master.getName(); + this.name = master.getName(); } @Override diff --git a/common/src/main/java/me/lucko/luckperms/api/implementation/internal/LPConfigurationLink.java b/common/src/main/java/me/lucko/luckperms/api/implementation/internal/LPConfigurationLink.java index c5ab7edc6..38f137d91 100644 --- a/common/src/main/java/me/lucko/luckperms/api/implementation/internal/LPConfigurationLink.java +++ b/common/src/main/java/me/lucko/luckperms/api/implementation/internal/LPConfigurationLink.java @@ -27,11 +27,11 @@ import me.lucko.luckperms.api.LPConfiguration; import me.lucko.luckperms.api.data.MySQLConfiguration; /** - * Provides a link between {@link LPConfiguration} and {@link me.lucko.luckperms.utils.LPConfiguration} + * Provides a link between {@link LPConfiguration} and {@link me.lucko.luckperms.core.LPConfiguration} */ @AllArgsConstructor public class LPConfigurationLink implements LPConfiguration { - private final me.lucko.luckperms.utils.LPConfiguration master; + private final me.lucko.luckperms.core.LPConfiguration master; @Override public String getServer() { diff --git a/common/src/main/java/me/lucko/luckperms/api/implementation/internal/LogLink.java b/common/src/main/java/me/lucko/luckperms/api/implementation/internal/LogLink.java new file mode 100644 index 000000000..397370ec9 --- /dev/null +++ b/common/src/main/java/me/lucko/luckperms/api/implementation/internal/LogLink.java @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2016 Lucko (Luck) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.luckperms.api.implementation.internal; + +import lombok.AllArgsConstructor; +import lombok.NonNull; +import me.lucko.luckperms.api.Log; +import me.lucko.luckperms.api.LogEntry; + +import java.util.SortedMap; +import java.util.SortedSet; +import java.util.UUID; + +import static me.lucko.luckperms.api.implementation.internal.Utils.checkName; + +/** + * Provides a link between {@link Log} and {@link me.lucko.luckperms.data.Log} + */ +@AllArgsConstructor +public class LogLink implements Log { + private final me.lucko.luckperms.data.Log master; + + @Override + public SortedSet getContent() { + return master.getContent(); + } + + @Override + public SortedSet getRecent() { + return master.getRecent(); + } + + @Override + public SortedMap getRecent(int pageNo) { + return master.getRecent(pageNo); + } + + @Override + public int getRecentMaxPages() { + return master.getRecentMaxPages(); + } + + @Override + public SortedSet getRecent(@NonNull UUID actor) { + return master.getRecent(actor); + } + + @Override + public SortedMap getRecent(int pageNo, @NonNull UUID actor) { + return master.getRecent(pageNo, actor); + } + + @Override + public int getRecentMaxPages(@NonNull UUID actor) { + return master.getRecentMaxPages(actor); + } + + @Override + public SortedSet getUserHistory(@NonNull UUID uuid) { + return master.getUserHistory(uuid); + } + + @Override + public SortedMap getUserHistory(int pageNo, @NonNull UUID uuid) { + return master.getUserHistory(pageNo, uuid); + } + + @Override + public int getUserHistoryMaxPages(@NonNull UUID uuid) { + return master.getUserHistoryMaxPages(uuid); + } + + @Override + public SortedSet getGroupHistory(@NonNull String name) { + return master.getGroupHistory(checkName(name)); + } + + @Override + public SortedMap getGroupHistory(int pageNo, @NonNull String name) { + return master.getGroupHistory(pageNo, checkName(name)); + } + + @Override + public int getGroupHistoryMaxPages(@NonNull String name) { + return master.getGroupHistoryMaxPages(checkName(name)); + } + + @Override + public SortedSet getTrackHistory(@NonNull String name) { + return master.getTrackHistory(checkName(name)); + } + + @Override + public SortedMap getTrackHistory(int pageNo, @NonNull String name) { + return master.getTrackHistory(pageNo, checkName(name)); + } + + @Override + public int getTrackHistoryMaxPages(@NonNull String name) { + return master.getTrackHistoryMaxPages(checkName(name)); + } + + @Override + public SortedSet getSearch(@NonNull String query) { + return master.getSearch(query); + } + + @Override + public SortedMap getSearch(int pageNo, @NonNull String query) { + return master.getSearch(pageNo, query); + } + + @Override + public int getSearchMaxPages(@NonNull String query) { + return master.getSearchMaxPages(query); + } +} diff --git a/common/src/main/java/me/lucko/luckperms/api/implementation/internal/PermissionHolderLink.java b/common/src/main/java/me/lucko/luckperms/api/implementation/internal/PermissionHolderLink.java index a8dbd67d4..2ababe9a9 100644 --- a/common/src/main/java/me/lucko/luckperms/api/implementation/internal/PermissionHolderLink.java +++ b/common/src/main/java/me/lucko/luckperms/api/implementation/internal/PermissionHolderLink.java @@ -36,14 +36,14 @@ import java.util.Map; import static me.lucko.luckperms.api.implementation.internal.Utils.*; /** - * Provides a link between {@link PermissionHolder} and {@link me.lucko.luckperms.utils.PermissionHolder} + * Provides a link between {@link PermissionHolder} and {@link me.lucko.luckperms.core.PermissionHolder} */ @SuppressWarnings("unused") @AllArgsConstructor(access = AccessLevel.PACKAGE) class PermissionHolderLink implements PermissionHolder { @NonNull - private final me.lucko.luckperms.utils.PermissionHolder master; + private final me.lucko.luckperms.core.PermissionHolder master; @Override public String getObjectName() { diff --git a/common/src/main/java/me/lucko/luckperms/api/implementation/internal/TrackLink.java b/common/src/main/java/me/lucko/luckperms/api/implementation/internal/TrackLink.java index 62c008906..9d20c4537 100644 --- a/common/src/main/java/me/lucko/luckperms/api/implementation/internal/TrackLink.java +++ b/common/src/main/java/me/lucko/luckperms/api/implementation/internal/TrackLink.java @@ -23,7 +23,7 @@ package me.lucko.luckperms.api.implementation.internal; import lombok.AccessLevel; -import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NonNull; import me.lucko.luckperms.api.Group; @@ -38,17 +38,19 @@ import static me.lucko.luckperms.api.implementation.internal.Utils.checkGroup; /** * Provides a link between {@link Track} and {@link me.lucko.luckperms.tracks.Track} */ +@EqualsAndHashCode(of = {"name"}) @SuppressWarnings("unused") -@AllArgsConstructor public class TrackLink implements Track { - @NonNull @Getter(AccessLevel.PACKAGE) private final me.lucko.luckperms.tracks.Track master; - @Override - public String getName() { - return master.getName(); + @Getter + private final String name; + + public TrackLink(@NonNull me.lucko.luckperms.tracks.Track master) { + this.master = master; + this.name = master.getName(); } @Override diff --git a/common/src/main/java/me/lucko/luckperms/api/implementation/internal/UserLink.java b/common/src/main/java/me/lucko/luckperms/api/implementation/internal/UserLink.java index a99575e56..313c12de4 100644 --- a/common/src/main/java/me/lucko/luckperms/api/implementation/internal/UserLink.java +++ b/common/src/main/java/me/lucko/luckperms/api/implementation/internal/UserLink.java @@ -23,6 +23,7 @@ package me.lucko.luckperms.api.implementation.internal; import lombok.AccessLevel; +import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NonNull; import me.lucko.luckperms.api.Group; @@ -38,20 +39,20 @@ import static me.lucko.luckperms.api.implementation.internal.Utils.*; /** * Provides a link between {@link User} and {@link me.lucko.luckperms.users.User} */ +@EqualsAndHashCode(of = {"uuid"}, callSuper = false) @SuppressWarnings("unused") public class UserLink extends PermissionHolderLink implements User { @Getter(AccessLevel.PACKAGE) private final me.lucko.luckperms.users.User master; + @Getter + private final UUID uuid; + public UserLink(@NonNull me.lucko.luckperms.users.User master) { super(master); this.master = master; - } - - @Override - public UUID getUuid() { - return master.getUuid(); + this.uuid = master.getUuid(); } @Override diff --git a/common/src/main/java/me/lucko/luckperms/api/implementation/internal/Utils.java b/common/src/main/java/me/lucko/luckperms/api/implementation/internal/Utils.java index 53a528a1c..af67f2ffc 100644 --- a/common/src/main/java/me/lucko/luckperms/api/implementation/internal/Utils.java +++ b/common/src/main/java/me/lucko/luckperms/api/implementation/internal/Utils.java @@ -50,7 +50,7 @@ class Utils { } static String checkUsername(String s) { - if (!ArgumentChecker.checkUsername(s)) { + if (ArgumentChecker.checkUsername(s)) { throw new IllegalArgumentException("Invalid username entry '" + s + "'. Usernames must be less than 16 chars" + " and only contain 'a-z A-Z 1-9 _'."); } @@ -58,7 +58,7 @@ class Utils { } static String checkName(String s) { - if (!ArgumentChecker.checkName(s)) { + if (ArgumentChecker.checkName(s)) { throw new IllegalArgumentException("Invalid name entry '" + s + "'. Names must be less than 37 chars" + " and only contain 'a-z A-Z 1-9'."); } @@ -66,21 +66,21 @@ class Utils { } static String checkServer(String s) { - if (!ArgumentChecker.checkServer(s)) { + if (ArgumentChecker.checkServer(s)) { throw new IllegalArgumentException("Invalid server entry '" + s + "'. Server names can only contain alphanumeric characters."); } return s; } static String checkNode(String s) { - if (!ArgumentChecker.checkNode(s)) { + if (ArgumentChecker.checkNode(s)) { throw new IllegalArgumentException("Invalid node entry '" + s + "'. Nodes cannot contain '/' or '$' characters."); } return s; } static long checkTime(long l) { - if (!ArgumentChecker.checkTime(l)) { + if (ArgumentChecker.checkTime(l)) { throw new IllegalArgumentException("Unix time '" + l + "' is invalid, as it has already passed."); } return l; diff --git a/common/src/main/java/me/lucko/luckperms/api/implementation/internal/UuidCacheLink.java b/common/src/main/java/me/lucko/luckperms/api/implementation/internal/UuidCacheLink.java index c61eeb8ab..9555da054 100644 --- a/common/src/main/java/me/lucko/luckperms/api/implementation/internal/UuidCacheLink.java +++ b/common/src/main/java/me/lucko/luckperms/api/implementation/internal/UuidCacheLink.java @@ -28,11 +28,11 @@ import me.lucko.luckperms.api.UuidCache; import java.util.UUID; /** - * Provides a link between {@link UuidCache} and {@link me.lucko.luckperms.utils.UuidCache} + * Provides a link between {@link UuidCache} and {@link me.lucko.luckperms.core.UuidCache} */ @AllArgsConstructor public class UuidCacheLink implements UuidCache { - private final me.lucko.luckperms.utils.UuidCache master; + private final me.lucko.luckperms.core.UuidCache master; @Override public UUID getUUID(UUID external) { diff --git a/common/src/main/java/me/lucko/luckperms/commands/CommandManager.java b/common/src/main/java/me/lucko/luckperms/commands/CommandManager.java index 4d08733d9..f29efe6b9 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/CommandManager.java +++ b/common/src/main/java/me/lucko/luckperms/commands/CommandManager.java @@ -22,13 +22,16 @@ package me.lucko.luckperms.commands; +import com.google.common.collect.ImmutableList; +import lombok.AllArgsConstructor; import lombok.Getter; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.api.data.Callback; import me.lucko.luckperms.commands.group.CreateGroup; import me.lucko.luckperms.commands.group.DeleteGroup; import me.lucko.luckperms.commands.group.GroupMainCommand; import me.lucko.luckperms.commands.group.ListGroups; -import me.lucko.luckperms.commands.group.subcommands.*; +import me.lucko.luckperms.commands.log.LogMainCommand; import me.lucko.luckperms.commands.misc.DebugCommand; import me.lucko.luckperms.commands.misc.InfoCommand; import me.lucko.luckperms.commands.misc.SyncCommand; @@ -36,9 +39,7 @@ import me.lucko.luckperms.commands.track.CreateTrack; import me.lucko.luckperms.commands.track.DeleteTrack; import me.lucko.luckperms.commands.track.ListTracks; import me.lucko.luckperms.commands.track.TrackMainCommand; -import me.lucko.luckperms.commands.track.subcommands.*; import me.lucko.luckperms.commands.user.UserMainCommand; -import me.lucko.luckperms.commands.user.subcommands.*; import me.lucko.luckperms.constants.Message; import java.util.ArrayList; @@ -47,71 +48,41 @@ import java.util.List; import java.util.Optional; import java.util.stream.Collectors; +@AllArgsConstructor public class CommandManager { private final LuckPermsPlugin plugin; @Getter - private final List mainCommands = new ArrayList<>(); + private final List mainCommands = ImmutableList.builder() + .add(new UserMainCommand()) + .add(new GroupMainCommand()) + .add(new TrackMainCommand()) + .add(new LogMainCommand()) + .add(new SyncCommand()) + .add(new InfoCommand()) + .add(new DebugCommand()) + .add(new CreateGroup()) + .add(new DeleteGroup()) + .add(new ListGroups()) + .add(new CreateTrack()) + .add(new DeleteTrack()) + .add(new ListTracks()) + .build(); - public CommandManager(LuckPermsPlugin plugin) { - this.plugin = plugin; - UserMainCommand userCommand = new UserMainCommand(); - this.registerMainCommand(userCommand); - userCommand.registerSubCommand(new UserInfo()); - userCommand.registerSubCommand(new UserGetUUID()); - userCommand.registerSubCommand(new UserListNodes()); - userCommand.registerSubCommand(new UserHasPerm()); - userCommand.registerSubCommand(new UserInheritsPerm()); - userCommand.registerSubCommand(new UserSetPermission()); - userCommand.registerSubCommand(new UserUnSetPermission()); - userCommand.registerSubCommand(new UserAddGroup()); - userCommand.registerSubCommand(new UserRemoveGroup()); - userCommand.registerSubCommand(new UserSetTempPermission()); - userCommand.registerSubCommand(new UserUnsetTempPermission()); - userCommand.registerSubCommand(new UserAddTempGroup()); - userCommand.registerSubCommand(new UserRemoveTempGroup()); - userCommand.registerSubCommand(new UserSetPrimaryGroup()); - userCommand.registerSubCommand(new UserShowTracks()); - userCommand.registerSubCommand(new UserPromote()); - userCommand.registerSubCommand(new UserDemote()); - userCommand.registerSubCommand(new UserShowPos()); - userCommand.registerSubCommand(new UserClear()); - - GroupMainCommand groupCommand = new GroupMainCommand(); - this.registerMainCommand(groupCommand); - groupCommand.registerSubCommand(new GroupInfo()); - groupCommand.registerSubCommand(new GroupListNodes()); - groupCommand.registerSubCommand(new GroupHasPerm()); - groupCommand.registerSubCommand(new GroupInheritsPerm()); - groupCommand.registerSubCommand(new GroupSetPermission()); - groupCommand.registerSubCommand(new GroupUnSetPermission()); - groupCommand.registerSubCommand(new GroupSetInherit()); - groupCommand.registerSubCommand(new GroupUnsetInherit()); - groupCommand.registerSubCommand(new GroupSetTempPermission()); - groupCommand.registerSubCommand(new GroupUnsetTempPermission()); - groupCommand.registerSubCommand(new GroupSetTempInherit()); - groupCommand.registerSubCommand(new GroupUnsetTempInherit()); - groupCommand.registerSubCommand(new GroupShowTracks()); - groupCommand.registerSubCommand(new GroupClear()); - - TrackMainCommand trackCommand = new TrackMainCommand(); - this.registerMainCommand(trackCommand); - trackCommand.registerSubCommand(new TrackInfo()); - trackCommand.registerSubCommand(new TrackAppend()); - trackCommand.registerSubCommand(new TrackInsert()); - trackCommand.registerSubCommand(new TrackRemove()); - trackCommand.registerSubCommand(new TrackClear()); - - this.registerMainCommand(new SyncCommand()); - this.registerMainCommand(new InfoCommand()); - this.registerMainCommand(new DebugCommand()); - this.registerMainCommand(new CreateGroup()); - this.registerMainCommand(new DeleteGroup()); - this.registerMainCommand(new ListGroups()); - this.registerMainCommand(new CreateTrack()); - this.registerMainCommand(new DeleteTrack()); - this.registerMainCommand(new ListTracks()); + /** + * Generic on command method to be called from the command executor object of the platform + * Unlike {@link #onCommand(Sender, String, List)}, this method is called in a new thread + * @param sender who sent the command + * @param label the command label used + * @param args the arguments provided + * @param result the callback to be called when the command has fully executed + */ + public void onCommand(Sender sender, String label, List args, Callback result) { + plugin.doAsync(() -> { + CommandResult r = onCommand(sender, label, args); + plugin.doSync(() -> result.onComplete(r)); + }); } /** @@ -121,38 +92,48 @@ public class CommandManager { * @param args the arguments provided * @return if the command was successful */ - public boolean onCommand(Sender sender, String label, List args) { + public CommandResult onCommand(Sender sender, String label, List args) { if (args.size() == 0) { sendCommandUsage(sender, label); - return true; + return CommandResult.INVALID_ARGS; } - Optional o = mainCommands.stream().filter(m -> m.getName().equalsIgnoreCase(args.get(0))).limit(1).findAny(); + Optional o = mainCommands.stream() + .filter(m -> m.getName().equalsIgnoreCase(args.get(0))) + .limit(1) + .findAny(); if (!o.isPresent()) { sendCommandUsage(sender, label); - return true; + return CommandResult.INVALID_ARGS; } final MainCommand main = o.get(); if (!main.isAuthorized(sender)) { sendCommandUsage(sender, label); - return true; + return CommandResult.NO_PERMISSION; } if (main.getRequiredArgsLength() == 0) { - main.execute(plugin, sender, null, label); - return true; + try { + return main.execute(plugin, sender, null, label); + } catch (Exception e) { + e.printStackTrace(); + return CommandResult.FAILURE; + } } if (args.size() == 1) { main.sendUsage(sender, label); - return true; + return CommandResult.INVALID_ARGS; } - main.execute(plugin, sender, new ArrayList<>(args.subList(1, args.size())), label); - return true; - + try { + return main.execute(plugin, sender, new ArrayList<>(args.subList(1, args.size())), label); + } catch (Exception e) { + e.printStackTrace(); + return CommandResult.FAILURE; + } } /** @@ -182,11 +163,6 @@ public class CommandManager { return o.get().onTabComplete(sender, args.subList(1, args.size()), plugin); } - private void registerMainCommand(MainCommand command) { - plugin.getLog().info("[CommandManager] Registered main command '" + command.getName() + "'"); - mainCommands.add(command); - } - private void sendCommandUsage(Sender sender, String label) { Message.INFO_BRIEF.send(sender, plugin.getVersion()); diff --git a/common/src/main/java/me/lucko/luckperms/commands/CommandResult.java b/common/src/main/java/me/lucko/luckperms/commands/CommandResult.java new file mode 100644 index 000000000..e619f75d8 --- /dev/null +++ b/common/src/main/java/me/lucko/luckperms/commands/CommandResult.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2016 Lucko (Luck) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.luckperms.commands; + +import lombok.AllArgsConstructor; + +@AllArgsConstructor +public enum CommandResult { + SUCCESS(true), + FAILURE(false), + + LOADING_ERROR(false), + STATE_ERROR(false), + INVALID_ARGS(false), + NO_PERMISSION(false); + + private boolean booleanValue; + + public boolean booleanValue() { + return booleanValue; + } + + static CommandResult of(boolean b) { + return b ? SUCCESS : FAILURE; + } + +} diff --git a/common/src/main/java/me/lucko/luckperms/commands/MainCommand.java b/common/src/main/java/me/lucko/luckperms/commands/MainCommand.java index 4ddef86e2..86d9491b8 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/MainCommand.java +++ b/common/src/main/java/me/lucko/luckperms/commands/MainCommand.java @@ -22,10 +22,10 @@ package me.lucko.luckperms.commands; +import com.google.common.collect.ImmutableList; +import lombok.AllArgsConstructor; import lombok.Getter; -import lombok.RequiredArgsConstructor; import me.lucko.luckperms.LuckPermsPlugin; -import me.lucko.luckperms.api.data.Callback; import me.lucko.luckperms.constants.Message; import java.util.ArrayList; @@ -35,7 +35,7 @@ import java.util.Optional; import java.util.stream.Collectors; @Getter -@RequiredArgsConstructor +@AllArgsConstructor public abstract class MainCommand { /** @@ -57,7 +57,11 @@ public abstract class MainCommand { * A list of the sub commands under this main command */ @Getter - private final List> subCommands = new ArrayList<>(); + private final List> subCommands; + + MainCommand(String name, String usage, int requiredArgsLength) { + this(name, usage, requiredArgsLength, ImmutableList.of()); + } /** * Called when this main command is ran @@ -66,37 +70,44 @@ public abstract class MainCommand { * @param args the stripped arguments given * @param label the command label used */ - protected void execute(LuckPermsPlugin plugin, Sender sender, List args, String label) { - if (args.size() < 2) { + protected CommandResult execute(LuckPermsPlugin plugin, Sender sender, List args, String label) { + if (args.size() < requiredArgsLength) { sendUsage(sender, label); - return; + return CommandResult.INVALID_ARGS; } - Optional> o = subCommands.stream().filter(s -> s.getName().equalsIgnoreCase(args.get(1))).limit(1).findAny(); + Optional> o = subCommands.stream().filter(s -> s.getName().equalsIgnoreCase(args.get(requiredArgsLength - 1))).limit(1).findAny(); if (!o.isPresent()) { Message.COMMAND_NOT_RECOGNISED.send(sender); - return; + return CommandResult.INVALID_ARGS; } final SubCommand sub = o.get(); if (!sub.isAuthorized(sender)) { Message.COMMAND_NO_PERMISSION.send(sender); - return; + return CommandResult.NO_PERMISSION; } List strippedArgs = new ArrayList<>(); - if (args.size() > 2) { - strippedArgs.addAll(args.subList(2, args.size())); + if (args.size() > requiredArgsLength) { + strippedArgs.addAll(args.subList(requiredArgsLength, args.size())); } if (sub.getIsArgumentInvalid().test(strippedArgs.size())) { sub.sendUsage(sender, label); - return; + return CommandResult.INVALID_ARGS; } final String name = args.get(0).toLowerCase(); - getTarget(name, plugin, sender, t -> sub.execute(plugin, sender, t, strippedArgs, label)); + T t = getTarget(name, plugin, sender); + if (t != null) { + CommandResult result = sub.execute(plugin, sender, t, strippedArgs, label); + cleanup(t, plugin); + return result; + } + + return CommandResult.LOADING_ERROR; } /** @@ -104,9 +115,10 @@ public abstract class MainCommand { * @param target the name of the object to be looked up * @param plugin a link to the main plugin instance * @param sender the user who send the command (used to send error messages if the lookup was unsuccessful) - * @param onSuccess the callback to run when the lookup is completed */ - protected abstract void getTarget(String target, LuckPermsPlugin plugin, Sender sender, Callback onSuccess); + protected abstract T getTarget(String target, LuckPermsPlugin plugin, Sender sender); + + protected abstract void cleanup(T t, LuckPermsPlugin plugin); /** * Get a list of objects for tab completion @@ -174,10 +186,6 @@ public abstract class MainCommand { return Collections.emptyList(); } - return o.get().onTabComplete(sender, args.subList(2, args.size()), plugin); - } - - public void registerSubCommand(SubCommand subCommand) { - subCommands.add(subCommand); + return o.get().onTabComplete(plugin, sender, args.subList(2, args.size())); } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/Predicate.java b/common/src/main/java/me/lucko/luckperms/commands/Predicate.java index 61daa5ff4..179c91b21 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/Predicate.java +++ b/common/src/main/java/me/lucko/luckperms/commands/Predicate.java @@ -28,6 +28,7 @@ import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; +@SuppressWarnings({"WeakerAccess", "unused"}) @UtilityClass public class Predicate { public static java.util.function.Predicate alwaysFalse() { diff --git a/common/src/main/java/me/lucko/luckperms/commands/Sender.java b/common/src/main/java/me/lucko/luckperms/commands/Sender.java index acfa7c02c..669adb1fc 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/Sender.java +++ b/common/src/main/java/me/lucko/luckperms/commands/Sender.java @@ -22,12 +22,18 @@ package me.lucko.luckperms.commands; +import me.lucko.luckperms.constants.Permission; + +import java.util.UUID; + /** - * Wrapper class to represent a CommandSender in Bukkit/Bungee within the luckperms-common command implementations. + * Wrapper interface to represent a CommandSender/CommandSource within the luckperms-common command implementations. */ public interface Sender { + String getName(); + UUID getUuid(); void sendMessage(String s); - boolean hasPermission(String node); + boolean hasPermission(Permission permission); } diff --git a/common/src/main/java/me/lucko/luckperms/commands/SenderFactory.java b/common/src/main/java/me/lucko/luckperms/commands/SenderFactory.java index 74e2c685d..5954165c8 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/SenderFactory.java +++ b/common/src/main/java/me/lucko/luckperms/commands/SenderFactory.java @@ -22,31 +22,69 @@ package me.lucko.luckperms.commands; +import lombok.Getter; +import me.lucko.luckperms.constants.Permission; + import java.lang.ref.WeakReference; +import java.util.*; +import java.util.stream.Collectors; -public abstract class SenderFactory { +/** + * Factory class to make a thread-safe sender instance + * @param the command sender type + */ +public abstract class SenderFactory implements Runnable { + // Ensures messages are sent in order, etc. + private final List tasks = new ArrayList<>(); + private final SenderFactory factory = this; + + protected abstract String getName(T t); + protected abstract UUID getUuid(T t); protected abstract void sendMessage(T t, String s); protected abstract boolean hasPermission(T t, String node); - public Sender wrap(T t) { - final SenderFactory factory = this; + public final Sender wrap(T t) { return new Sender() { - final WeakReference cs = new WeakReference<>(t); + final WeakReference tRef = new WeakReference<>(t); + + // Cache these permissions, so they can be accessed async + final Map perms = Arrays.stream(Permission.values()) + .map(p -> new AbstractMap.SimpleEntry<>(p, factory.hasPermission(t, p.getNode()))) + .collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue)); + + @Getter + final String name = factory.getName(t); + + @Getter + final UUID uuid = factory.getUuid(t); @Override public void sendMessage(String s) { - final T c = cs.get(); - if (c != null) { - factory.sendMessage(c, s); + final T t = tRef.get(); + if (t != null) { + synchronized (tasks) { + tasks.add(() -> factory.sendMessage(t, s)); + } } } @Override - public boolean hasPermission(String node) { - final T c = cs.get(); - return c != null && factory.hasPermission(c, node); + public boolean hasPermission(Permission permission) { + synchronized (perms) { + return perms.get(permission); + } } }; } + + @Override + public final void run() { + synchronized (tasks) { + if (!tasks.isEmpty()) { + tasks.forEach(Runnable::run); + tasks.clear(); + } + } + } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/SingleMainCommand.java b/common/src/main/java/me/lucko/luckperms/commands/SingleMainCommand.java index 905a54d23..4966b230d 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/SingleMainCommand.java +++ b/common/src/main/java/me/lucko/luckperms/commands/SingleMainCommand.java @@ -23,7 +23,6 @@ package me.lucko.luckperms.commands; import me.lucko.luckperms.LuckPermsPlugin; -import me.lucko.luckperms.api.data.Callback; import me.lucko.luckperms.constants.Permission; import java.util.Collections; @@ -41,13 +40,19 @@ public class SingleMainCommand extends MainCommand { } @Override - protected void execute(LuckPermsPlugin plugin, Sender sender, List args, String label) { + protected CommandResult execute(LuckPermsPlugin plugin, Sender sender, List args, String label) { // Do nothing, allow the implementation to override this + return null; } @Override - protected void getTarget(String target, LuckPermsPlugin plugin, Sender sender, Callback onSuccess) { - // Do nothing, don't run callback + protected Object getTarget(String target, LuckPermsPlugin plugin, Sender sender) { + return null; + } + + @Override + protected void cleanup(Object o, LuckPermsPlugin plugin) { + // Do nothing } @Override diff --git a/common/src/main/java/me/lucko/luckperms/commands/SubCommand.java b/common/src/main/java/me/lucko/luckperms/commands/SubCommand.java index c6d30d032..aeb328826 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/SubCommand.java +++ b/common/src/main/java/me/lucko/luckperms/commands/SubCommand.java @@ -78,7 +78,19 @@ public abstract class SubCommand { * @param args the stripped arguments given * @param label the command label used */ - public abstract void execute(LuckPermsPlugin plugin, Sender sender, T t, List args, String label); + public abstract CommandResult execute(LuckPermsPlugin plugin, Sender sender, T t, List args, String label); + + /** + * Returns a list of suggestions, which are empty by default. Sub classes that give tab complete suggestions override + * this method to give their own list. + * @param plugin the plugin instance + * @param sender who is tab completing + * @param args the arguments so far + * @return a list of suggestions + */ + public List onTabComplete(LuckPermsPlugin plugin, Sender sender, List args) { + return Collections.emptyList(); + } /** * Send the command usage to a sender @@ -98,18 +110,6 @@ public abstract class SubCommand { return permission.isAuthorized(sender); } - /** - * Returns a list of suggestions, which are empty by default. Sub classes that give tab complete suggestions override - * this method to give their own list. - * @param sender who is tab completing - * @param args the arguments so far - * @param plugin the plugin instance - * @return a list of suggestions - */ - public List onTabComplete(Sender sender, List args, LuckPermsPlugin plugin) { - return Collections.emptyList(); - } - /* ---------------------------------------------------------------------------------- Utility methods used by #onTabComplete and #execute implementations in sub classes @@ -117,11 +117,11 @@ public abstract class SubCommand { */ protected static List getGroupTabComplete(List args, LuckPermsPlugin plugin) { - return getTabComplete(new ArrayList<>(plugin.getGroupManager().getGroups().keySet()), args); + return getTabComplete(new ArrayList<>(plugin.getGroupManager().getAll().keySet()), args); } protected static List getTrackTabComplete(List args, LuckPermsPlugin plugin) { - return getTabComplete(new ArrayList<>(plugin.getTrackManager().getTracks().keySet()), args); + return getTabComplete(new ArrayList<>(plugin.getTrackManager().getAll().keySet()), args); } protected static List getBoolTabComplete(List args) { @@ -144,7 +144,7 @@ public abstract class SubCommand { return Collections.emptyList(); } - protected static void saveUser(User user, Sender sender, LuckPermsPlugin plugin) { + protected static void save(User user, Sender sender, LuckPermsPlugin plugin) { user.refreshPermissions(); plugin.getDatastore().saveUser(user, success -> { @@ -156,7 +156,7 @@ public abstract class SubCommand { }); } - protected static void saveGroup(Group group, Sender sender, LuckPermsPlugin plugin) { + protected static void save(Group group, Sender sender, LuckPermsPlugin plugin) { plugin.getDatastore().saveGroup(group, success -> { if (success) { Message.GROUP_SAVE_SUCCESS.send(sender); @@ -168,7 +168,7 @@ public abstract class SubCommand { }); } - protected static void saveTrack(Track track, Sender sender, LuckPermsPlugin plugin) { + protected static void save(Track track, Sender sender, LuckPermsPlugin plugin) { plugin.getDatastore().saveTrack(track, success -> { if (success) { Message.TRACK_SAVE_SUCCESS.send(sender); diff --git a/common/src/main/java/me/lucko/luckperms/commands/Util.java b/common/src/main/java/me/lucko/luckperms/commands/Util.java index 65b454245..c4ba2300c 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/Util.java +++ b/common/src/main/java/me/lucko/luckperms/commands/Util.java @@ -24,6 +24,7 @@ package me.lucko.luckperms.commands; import lombok.experimental.UtilityClass; import me.lucko.luckperms.constants.Message; +import me.lucko.luckperms.constants.Patterns; import me.lucko.luckperms.utils.DateUtil; import java.util.List; @@ -55,12 +56,16 @@ public class Util { return new String(b); } + public static String stripColor(String s) { + return s == null ? null : Patterns.STRIP_COLOR_PATTERN.matcher(s).replaceAll(""); + } + + public static String formatBoolean(boolean b) { + return b ? "&atrue" : "&cfalse"; + } + public static void sendBoolean(Sender sender, String node, boolean b) { - if (b) { - sender.sendMessage(Util.color("&b" + node + ": &atrue")); - } else { - sender.sendMessage(Util.color("&b" + node + ": &cfalse")); - } + sender.sendMessage(Util.color("&b" + node + ": " + formatBoolean(b))); } public static String listToCommaSep(List strings) { diff --git a/common/src/main/java/me/lucko/luckperms/commands/group/CreateGroup.java b/common/src/main/java/me/lucko/luckperms/commands/group/CreateGroup.java index bf540e7f6..3c20b57c9 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/group/CreateGroup.java +++ b/common/src/main/java/me/lucko/luckperms/commands/group/CreateGroup.java @@ -23,10 +23,12 @@ package me.lucko.luckperms.commands.group; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SingleMainCommand; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.utils.ArgumentChecker; import java.util.List; @@ -37,31 +39,31 @@ public class CreateGroup extends SingleMainCommand { } @Override - protected void execute(LuckPermsPlugin plugin, Sender sender, List args, String label) { + protected CommandResult execute(LuckPermsPlugin plugin, Sender sender, List args, String label) { if (args.size() == 0) { sendUsage(sender, label); - return; + return CommandResult.INVALID_ARGS; } String groupName = args.get(0).toLowerCase(); - if (!ArgumentChecker.checkName(groupName)) { + if (ArgumentChecker.checkName(groupName)) { Message.GROUP_INVALID_ENTRY.send(sender); - return; + return CommandResult.INVALID_ARGS; } - plugin.getDatastore().loadGroup(groupName, success -> { - if (success) { - Message.GROUP_ALREADY_EXISTS.send(sender); - } else { - plugin.getDatastore().createAndLoadGroup(groupName, success1 -> { - if (!success1) { - Message.CREATE_GROUP_ERROR.send(sender); - } else { - Message.CREATE_SUCCESS.send(sender, groupName); - plugin.runUpdateTask(); - } - }); - } - }); + if (plugin.getDatastore().loadGroup(groupName)) { + Message.GROUP_ALREADY_EXISTS.send(sender); + return CommandResult.INVALID_ARGS; + } + + if (!plugin.getDatastore().createAndLoadGroup(groupName)) { + Message.CREATE_GROUP_ERROR.send(sender); + return CommandResult.FAILURE; + } + + Message.CREATE_SUCCESS.send(sender, groupName); + LogEntryBuilder.get().actor(sender).actedName(groupName).type('G').action("create").submit(plugin); + plugin.runUpdateTask(); + return CommandResult.SUCCESS; } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/group/DeleteGroup.java b/common/src/main/java/me/lucko/luckperms/commands/group/DeleteGroup.java index 7b8b64092..61307e716 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/group/DeleteGroup.java +++ b/common/src/main/java/me/lucko/luckperms/commands/group/DeleteGroup.java @@ -23,10 +23,12 @@ package me.lucko.luckperms.commands.group; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SingleMainCommand; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.groups.Group; import me.lucko.luckperms.utils.ArgumentChecker; @@ -41,49 +43,49 @@ public class DeleteGroup extends SingleMainCommand { } @Override - protected void execute(LuckPermsPlugin plugin, Sender sender, List args, String label) { + protected CommandResult execute(LuckPermsPlugin plugin, Sender sender, List args, String label) { if (args.size() == 0) { sendUsage(sender, label); - return; + return CommandResult.INVALID_ARGS; } String groupName = args.get(0).toLowerCase(); if (groupName.equalsIgnoreCase(plugin.getConfiguration().getDefaultGroupName())) { Message.DELETE_GROUP_ERROR_DEFAULT.send(sender); - return; + return CommandResult.INVALID_ARGS; } - if (!ArgumentChecker.checkName(groupName)) { + if (ArgumentChecker.checkName(groupName)) { Message.GROUP_INVALID_ENTRY.send(sender); - return; + return CommandResult.INVALID_ARGS; } - plugin.getDatastore().loadGroup(groupName, success -> { - if (!success) { - Message.GROUP_DOES_NOT_EXIST.send(sender); - } else { + if (!plugin.getDatastore().loadGroup(groupName)) { + Message.GROUP_DOES_NOT_EXIST.send(sender); + return CommandResult.INVALID_ARGS; + } - Group group = plugin.getGroupManager().getGroup(groupName); - if (group == null) { - Message.GROUP_LOAD_ERROR.send(sender); - } else { - plugin.getDatastore().deleteGroup(group, success1 -> { - if (!success1) { - Message.DELETE_GROUP_ERROR.send(sender); - } else { - Message.DELETE_SUCCESS.send(sender, groupName); - plugin.runUpdateTask(); - } - }); - } - } - }); + Group group = plugin.getGroupManager().get(groupName); + if (group == null) { + Message.GROUP_LOAD_ERROR.send(sender); + return CommandResult.LOADING_ERROR; + } + + if (!plugin.getDatastore().deleteGroup(group)) { + Message.DELETE_GROUP_ERROR.send(sender); + return CommandResult.FAILURE; + } + + Message.DELETE_SUCCESS.send(sender, groupName); + LogEntryBuilder.get().actor(sender).actedName(groupName).type('G').action("delete").submit(plugin); + plugin.runUpdateTask(); + return CommandResult.SUCCESS; } @Override protected List onTabComplete(Sender sender, List args, LuckPermsPlugin plugin) { - final List groups = new ArrayList<>(plugin.getGroupManager().getGroups().keySet()); + final List groups = new ArrayList<>(plugin.getGroupManager().getAll().keySet()); if (args.size() <= 1) { if (args.isEmpty() || args.get(0).equalsIgnoreCase("")) { diff --git a/common/src/main/java/me/lucko/luckperms/commands/group/GroupMainCommand.java b/common/src/main/java/me/lucko/luckperms/commands/group/GroupMainCommand.java index c7198723b..6d10ca87f 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/group/GroupMainCommand.java +++ b/common/src/main/java/me/lucko/luckperms/commands/group/GroupMainCommand.java @@ -22,10 +22,12 @@ package me.lucko.luckperms.commands.group; +import com.google.common.collect.ImmutableList; import me.lucko.luckperms.LuckPermsPlugin; -import me.lucko.luckperms.api.data.Callback; import me.lucko.luckperms.commands.MainCommand; import me.lucko.luckperms.commands.Sender; +import me.lucko.luckperms.commands.SubCommand; +import me.lucko.luckperms.commands.group.subcommands.*; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.groups.Group; import me.lucko.luckperms.utils.ArgumentChecker; @@ -35,34 +37,53 @@ import java.util.List; public class GroupMainCommand extends MainCommand { public GroupMainCommand() { - super("Group", "/%s group ", 2); + super("Group", "/%s group ", 2, ImmutableList.>builder() + .add(new GroupInfo()) + .add(new GroupListNodes()) + .add(new GroupHasPerm()) + .add(new GroupInheritsPerm()) + .add(new GroupSetPermission()) + .add(new GroupUnSetPermission()) + .add(new GroupSetInherit()) + .add(new GroupUnsetInherit()) + .add(new GroupSetTempPermission()) + .add(new GroupUnsetTempPermission()) + .add(new GroupSetTempInherit()) + .add(new GroupUnsetTempInherit()) + .add(new GroupShowTracks()) + .add(new GroupClear()) + .build() + ); } @Override - protected void getTarget(String target, LuckPermsPlugin plugin, Sender sender, Callback onSuccess) { - if (!ArgumentChecker.checkName(target)) { + protected Group getTarget(String target, LuckPermsPlugin plugin, Sender sender) { + if (ArgumentChecker.checkName(target)) { Message.GROUP_INVALID_ENTRY.send(sender); - return; + return null; } - plugin.getDatastore().loadGroup(target, success -> { - if (!success) { - Message.GROUP_NOT_FOUND.send(sender); - return; - } + if (!plugin.getDatastore().loadGroup(target)) { + Message.GROUP_NOT_FOUND.send(sender); + return null; + } - Group group = plugin.getGroupManager().getGroup(target); - if (group == null) { - Message.GROUP_NOT_FOUND.send(sender); - return; - } + Group group = plugin.getGroupManager().get(target); + + if (group == null) { + Message.GROUP_NOT_FOUND.send(sender); + } + + return group; + } + + @Override + protected void cleanup(Group group, LuckPermsPlugin plugin) { - onSuccess.onComplete(group); - }); } @Override protected List getObjects(LuckPermsPlugin plugin) { - return new ArrayList<>(plugin.getGroupManager().getGroups().keySet()); + return new ArrayList<>(plugin.getGroupManager().getAll().keySet()); } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/group/ListGroups.java b/common/src/main/java/me/lucko/luckperms/commands/group/ListGroups.java index cfb83beeb..d7b2f66f5 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/group/ListGroups.java +++ b/common/src/main/java/me/lucko/luckperms/commands/group/ListGroups.java @@ -23,6 +23,7 @@ package me.lucko.luckperms.commands.group; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SingleMainCommand; import me.lucko.luckperms.commands.Util; @@ -38,13 +39,13 @@ public class ListGroups extends SingleMainCommand { } @Override - protected void execute(LuckPermsPlugin plugin, Sender sender, List args, String label) { - plugin.getDatastore().loadAllGroups(success -> { - if (!success) { - Message.GROUPS_LOAD_ERROR.send(sender); - } else { - Message.GROUPS_LIST.send(sender, Util.listToCommaSep(new ArrayList<>(plugin.getGroupManager().getGroups().keySet()))); - } - }); + protected CommandResult execute(LuckPermsPlugin plugin, Sender sender, List args, String label) { + if (!plugin.getDatastore().loadAllGroups()) { + Message.GROUPS_LOAD_ERROR.send(sender); + return CommandResult.LOADING_ERROR; + } + + Message.GROUPS_LIST.send(sender, Util.listToCommaSep(new ArrayList<>(plugin.getGroupManager().getAll().keySet()))); + return CommandResult.SUCCESS; } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupClear.java b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupClear.java index 083ec9649..29df3c5ce 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupClear.java +++ b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupClear.java @@ -23,11 +23,13 @@ package me.lucko.luckperms.commands.group.subcommands; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Predicate; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SubCommand; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.groups.Group; import java.util.List; @@ -39,10 +41,11 @@ public class GroupClear extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { group.clearNodes(); Message.CLEAR_SUCCESS.send(sender, group.getName()); - - saveGroup(group, sender, plugin); + LogEntryBuilder.get().actor(sender).acted(group).action("clear").submit(plugin); + save(group, sender, plugin); + return CommandResult.SUCCESS; } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupHasPerm.java b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupHasPerm.java index 0dc91a8f1..a0498a413 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupHasPerm.java +++ b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupHasPerm.java @@ -23,10 +23,7 @@ package me.lucko.luckperms.commands.group.subcommands; import me.lucko.luckperms.LuckPermsPlugin; -import me.lucko.luckperms.commands.Predicate; -import me.lucko.luckperms.commands.Sender; -import me.lucko.luckperms.commands.SubCommand; -import me.lucko.luckperms.commands.Util; +import me.lucko.luckperms.commands.*; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; import me.lucko.luckperms.groups.Group; @@ -42,11 +39,11 @@ public class GroupHasPerm extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { if (args.size() >= 2) { - if (!ArgumentChecker.checkServer(args.get(1))) { + if (ArgumentChecker.checkServer(args.get(1))) { Message.SERVER_INVALID_ENTRY.send(sender); - return; + return CommandResult.INVALID_ARGS; } if (args.size() == 2) { @@ -58,5 +55,6 @@ public class GroupHasPerm extends SubCommand { } else { Util.sendBoolean(sender, args.get(0), group.hasPermission(args.get(0), true, "global")); } + return CommandResult.SUCCESS; } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupInfo.java b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupInfo.java index 22e692af1..b317967d0 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupInfo.java +++ b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupInfo.java @@ -23,6 +23,7 @@ package me.lucko.luckperms.commands.group.subcommands; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Predicate; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SubCommand; @@ -39,8 +40,14 @@ public class GroupInfo extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { - Message.GROUP_INFO.send(sender, group.getName(), group.getPermanentNodes().keySet().size(), - group.getTemporaryNodes().keySet().size(), label, group.getName()); + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { + Message.GROUP_INFO.send(sender, + group.getName(), + group.getPermanentNodes().keySet().size(), + group.getTemporaryNodes().keySet().size(), + label, + group.getName() + ); + return CommandResult.SUCCESS; } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupInheritsPerm.java b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupInheritsPerm.java index b872d6438..5e1bc7799 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupInheritsPerm.java +++ b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupInheritsPerm.java @@ -23,10 +23,7 @@ package me.lucko.luckperms.commands.group.subcommands; import me.lucko.luckperms.LuckPermsPlugin; -import me.lucko.luckperms.commands.Predicate; -import me.lucko.luckperms.commands.Sender; -import me.lucko.luckperms.commands.SubCommand; -import me.lucko.luckperms.commands.Util; +import me.lucko.luckperms.commands.*; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; import me.lucko.luckperms.groups.Group; @@ -42,11 +39,11 @@ public class GroupInheritsPerm extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { if (args.size() >= 2) { - if (!ArgumentChecker.checkServer(args.get(1))) { + if (ArgumentChecker.checkServer(args.get(1))) { Message.SERVER_INVALID_ENTRY.send(sender); - return; + return CommandResult.INVALID_ARGS; } if (args.size() == 2) { @@ -58,5 +55,6 @@ public class GroupInheritsPerm extends SubCommand { } else { Util.sendBoolean(sender, args.get(0), group.inheritsPermission(args.get(0), true)); } + return CommandResult.SUCCESS; } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupListNodes.java b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupListNodes.java index aaccce146..bdefa900e 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupListNodes.java +++ b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupListNodes.java @@ -23,10 +23,7 @@ package me.lucko.luckperms.commands.group.subcommands; import me.lucko.luckperms.LuckPermsPlugin; -import me.lucko.luckperms.commands.Predicate; -import me.lucko.luckperms.commands.Sender; -import me.lucko.luckperms.commands.SubCommand; -import me.lucko.luckperms.commands.Util; +import me.lucko.luckperms.commands.*; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; import me.lucko.luckperms.groups.Group; @@ -40,8 +37,9 @@ public class GroupListNodes extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { Message.LISTNODES.send(sender, group.getName(), Util.permNodesToString(group.getPermanentNodes())); Message.LISTNODES_TEMP.send(sender, group.getName(), Util.tempNodesToString(group.getTemporaryNodes())); + return CommandResult.SUCCESS; } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupSetInherit.java b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupSetInherit.java index 00bf7c320..e7f60b1e4 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupSetInherit.java +++ b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupSetInherit.java @@ -23,11 +23,13 @@ package me.lucko.luckperms.commands.group.subcommands; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Predicate; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SubCommand; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import me.lucko.luckperms.groups.Group; import me.lucko.luckperms.utils.ArgumentChecker; @@ -42,50 +44,66 @@ public class GroupSetInherit extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { String groupName = args.get(0).toLowerCase(); - if (!ArgumentChecker.checkNode(groupName)) { + if (ArgumentChecker.checkNode(groupName)) { sendUsage(sender, label); - return; + return CommandResult.INVALID_ARGS; } - plugin.getDatastore().loadGroup(groupName, success -> { - if (!success) { - Message.GROUP_LOAD_ERROR.send(sender); - } else { - try { - if (args.size() >= 2) { - final String server = args.get(1).toLowerCase(); - if (!ArgumentChecker.checkServer(server)) { - Message.SERVER_INVALID_ENTRY.send(sender); - return; - } + if (!plugin.getDatastore().loadGroup(groupName)) { + Message.GROUP_DOES_NOT_EXIST.send(sender); + return CommandResult.INVALID_ARGS; + } - if (args.size() == 2) { - group.setPermission("group." + groupName, true, server); - Message.GROUP_SETINHERIT_SERVER_SUCCESS.send(sender, group.getName(), groupName, server); - } else { - final String world = args.get(2).toLowerCase(); - group.setPermission("group." + groupName, true, server, world); - Message.GROUP_SETINHERIT_SERVER_WORLD_SUCCESS.send(sender, group.getName(), groupName, server, world); - } + Group group1 = plugin.getGroupManager().get(groupName); + if (group1 == null) { + Message.GROUP_DOES_NOT_EXIST.send(sender); + return CommandResult.LOADING_ERROR; + } - } else { - group.setPermission("group." + groupName, true); - Message.GROUP_SETINHERIT_SUCCESS.send(sender, group.getName(), groupName); - } - - saveGroup(group, sender, plugin); - } catch (ObjectAlreadyHasException e) { - Message.GROUP_ALREADY_INHERITS.send(sender, group.getName(), groupName); + try { + if (args.size() >= 2) { + final String server = args.get(1).toLowerCase(); + if (ArgumentChecker.checkServer(server)) { + Message.SERVER_INVALID_ENTRY.send(sender); + return CommandResult.INVALID_ARGS; } + + if (args.size() == 2) { + group.setInheritGroup(group1, server); + Message.GROUP_SETINHERIT_SERVER_SUCCESS.send(sender, group.getName(), group1.getName(), server); + LogEntryBuilder.get().actor(sender).acted(group) + .action("setinherit " + group1.getName() + " " + server) + .submit(plugin); + } else { + final String world = args.get(2).toLowerCase(); + group.setInheritGroup(group1, server, world); + Message.GROUP_SETINHERIT_SERVER_WORLD_SUCCESS.send(sender, group.getName(), group1.getName(), server, world); + LogEntryBuilder.get().actor(sender).acted(group) + .action("setinherit " + group1.getName() + " " + server + " " + world) + .submit(plugin); + } + + } else { + group.setInheritGroup(group1); + Message.GROUP_SETINHERIT_SUCCESS.send(sender, group.getName(), group1.getName()); + LogEntryBuilder.get().actor(sender).acted(group) + .action("setinherit " + group1.getName()) + .submit(plugin); } - }); + + save(group, sender, plugin); + return CommandResult.SUCCESS; + } catch (ObjectAlreadyHasException e) { + Message.GROUP_ALREADY_INHERITS.send(sender, group.getName(), group1.getName()); + return CommandResult.STATE_ERROR; + } } @Override - public List onTabComplete(Sender sender, List args, LuckPermsPlugin plugin) { + public List onTabComplete(LuckPermsPlugin plugin, Sender sender, List args) { return getGroupTabComplete(args, plugin); } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupSetPermission.java b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupSetPermission.java index 537b52e84..5cf51d86b 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupSetPermission.java +++ b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupSetPermission.java @@ -23,15 +23,17 @@ package me.lucko.luckperms.commands.group.subcommands; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Predicate; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SubCommand; import me.lucko.luckperms.constants.Message; +import me.lucko.luckperms.constants.Patterns; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import me.lucko.luckperms.groups.Group; import me.lucko.luckperms.utils.ArgumentChecker; -import me.lucko.luckperms.utils.Patterns; import java.util.List; @@ -42,23 +44,23 @@ public class GroupSetPermission extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { String node = args.get(0); String bool = args.get(1).toLowerCase(); - if (!ArgumentChecker.checkNode(node)) { + if (ArgumentChecker.checkNode(node)) { sendUsage(sender, label); - return; + return CommandResult.INVALID_ARGS; } if (Patterns.GROUP_MATCH.matcher(node).matches()) { Message.GROUP_USE_INHERIT.send(sender); - return; + return CommandResult.INVALID_ARGS; } if (!bool.equalsIgnoreCase("true") && !bool.equalsIgnoreCase("false")) { sendUsage(sender, label); - return; + return CommandResult.INVALID_ARGS; } boolean b = Boolean.parseBoolean(bool); @@ -66,33 +68,44 @@ public class GroupSetPermission extends SubCommand { try { if (args.size() >= 3) { final String server = args.get(2).toLowerCase(); - if (!ArgumentChecker.checkServer(server)) { + if (ArgumentChecker.checkServer(server)) { Message.SERVER_INVALID_ENTRY.send(sender); - return; + return CommandResult.INVALID_ARGS; } if (args.size() == 3) { group.setPermission(node, b, server); Message.SETPERMISSION_SERVER_SUCCESS.send(sender, node, bool, group.getName(), server); + LogEntryBuilder.get().actor(sender).acted(group) + .action("set " + node + " " + b + " " + server) + .submit(plugin); } else { final String world = args.get(3).toLowerCase(); group.setPermission(node, b, server, world); Message.SETPERMISSION_SERVER_WORLD_SUCCESS.send(sender, node, bool, group.getName(), server, world); + LogEntryBuilder.get().actor(sender).acted(group) + .action("set " + node + " " + b + " " + server + " " + world) + .submit(plugin); } } else { group.setPermission(node, b); Message.SETPERMISSION_SUCCESS.send(sender, node, bool, group.getName()); + LogEntryBuilder.get().actor(sender).acted(group) + .action("set " + node + " " + b) + .submit(plugin); } - saveGroup(group, sender, plugin); + save(group, sender, plugin); + return CommandResult.SUCCESS; } catch (ObjectAlreadyHasException e) { Message.ALREADY_HASPERMISSION.send(sender, group.getName()); + return CommandResult.STATE_ERROR; } } @Override - public List onTabComplete(Sender sender, List args, LuckPermsPlugin plugin) { + public List onTabComplete(LuckPermsPlugin plugin, Sender sender, List args) { return getBoolTabComplete(args); } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupSetTempInherit.java b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupSetTempInherit.java index c62a5620b..2da2517c4 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupSetTempInherit.java +++ b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupSetTempInherit.java @@ -23,11 +23,13 @@ package me.lucko.luckperms.commands.group.subcommands; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Predicate; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SubCommand; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import me.lucko.luckperms.groups.Group; import me.lucko.luckperms.utils.ArgumentChecker; @@ -43,12 +45,12 @@ public class GroupSetTempInherit extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { String groupName = args.get(0).toLowerCase(); - if (!ArgumentChecker.checkNode(groupName)) { + if (ArgumentChecker.checkNode(groupName)) { sendUsage(sender, label); - return; + return CommandResult.INVALID_ARGS; } long duration; @@ -56,52 +58,68 @@ public class GroupSetTempInherit extends SubCommand { duration = DateUtil.parseDateDiff(args.get(1), true); } catch (DateUtil.IllegalDateException e) { Message.ILLEGAL_DATE_ERROR.send(sender, args.get(1)); - return; + return CommandResult.INVALID_ARGS; } if (DateUtil.shouldExpire(duration)) { Message.PAST_DATE_ERROR.send(sender); - return; + return CommandResult.INVALID_ARGS; } - plugin.getDatastore().loadGroup(groupName, success -> { - if (!success) { - Message.GROUP_LOAD_ERROR.send(sender); - } else { - try { - if (args.size() >= 3) { - final String server = args.get(2).toLowerCase(); - if (!ArgumentChecker.checkServer(server)) { - Message.SERVER_INVALID_ENTRY.send(sender); - return; - } + if (!plugin.getDatastore().loadGroup(groupName)) { + Message.GROUP_DOES_NOT_EXIST.send(sender); + return CommandResult.INVALID_ARGS; + } - if (args.size() == 3) { - group.setPermission("group." + groupName, true, server, duration); - Message.GROUP_SET_TEMP_INHERIT_SERVER_SUCCESS.send(sender, group.getName(), groupName, server, - DateUtil.formatDateDiff(duration)); - } else { - final String world = args.get(3).toLowerCase(); - group.setPermission("group." + groupName, true, server, world, duration); - Message.GROUP_SET_TEMP_INHERIT_SERVER_WORLD_SUCCESS.send(sender, group.getName(), groupName, server, - world, DateUtil.formatDateDiff(duration)); - } + Group group1 = plugin.getGroupManager().get(groupName); + if (group1 == null) { + Message.GROUP_DOES_NOT_EXIST.send(sender); + return CommandResult.INVALID_ARGS; + } - } else { - group.setPermission("group." + groupName, true, duration); - Message.GROUP_SET_TEMP_INHERIT_SUCCESS.send(sender, group.getName(), groupName, DateUtil.formatDateDiff(duration)); - } - - saveGroup(group, sender, plugin); - } catch (ObjectAlreadyHasException e) { - Message.GROUP_ALREADY_TEMP_INHERITS.send(sender, group.getName(), groupName); + try { + if (args.size() >= 3) { + final String server = args.get(2).toLowerCase(); + if (ArgumentChecker.checkServer(server)) { + Message.SERVER_INVALID_ENTRY.send(sender); + return CommandResult.INVALID_ARGS; } + + if (args.size() == 3) { + group.setInheritGroup(group1, server, duration); + Message.GROUP_SET_TEMP_INHERIT_SERVER_SUCCESS.send(sender, group.getName(), group1.getName(), server, + DateUtil.formatDateDiff(duration)); + LogEntryBuilder.get().actor(sender).acted(group) + .action("settempinherit " + group1.getName() + " " + duration + " " + server) + .submit(plugin); + } else { + final String world = args.get(3).toLowerCase(); + group.setInheritGroup(group1, server, world, duration); + Message.GROUP_SET_TEMP_INHERIT_SERVER_WORLD_SUCCESS.send(sender, group.getName(), group1.getName(), server, + world, DateUtil.formatDateDiff(duration)); + LogEntryBuilder.get().actor(sender).acted(group) + .action("settempinherit " + group1.getName() + " " + duration + " " + server + " " + world) + .submit(plugin); + } + + } else { + group.setInheritGroup(group1, duration); + Message.GROUP_SET_TEMP_INHERIT_SUCCESS.send(sender, group.getName(), group1.getName(), DateUtil.formatDateDiff(duration)); + LogEntryBuilder.get().actor(sender).acted(group) + .action("settempinherit " + group1.getName() + " " + duration) + .submit(plugin); } - }); + + save(group, sender, plugin); + return CommandResult.SUCCESS; + } catch (ObjectAlreadyHasException e) { + Message.USER_ALREADY_TEMP_MEMBER_OF.send(sender, group.getName(), group1.getName()); + return CommandResult.STATE_ERROR; + } } @Override - public List onTabComplete(Sender sender, List args, LuckPermsPlugin plugin) { + public List onTabComplete(LuckPermsPlugin plugin, Sender sender, List args) { return getGroupTabComplete(args, plugin); } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupSetTempPermission.java b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupSetTempPermission.java index 750ef4017..39d415706 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupSetTempPermission.java +++ b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupSetTempPermission.java @@ -23,16 +23,18 @@ package me.lucko.luckperms.commands.group.subcommands; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Predicate; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SubCommand; import me.lucko.luckperms.constants.Message; +import me.lucko.luckperms.constants.Patterns; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import me.lucko.luckperms.groups.Group; import me.lucko.luckperms.utils.ArgumentChecker; import me.lucko.luckperms.utils.DateUtil; -import me.lucko.luckperms.utils.Patterns; import java.util.List; @@ -44,23 +46,23 @@ public class GroupSetTempPermission extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { String node = args.get(0); String bool = args.get(1).toLowerCase(); - if (!ArgumentChecker.checkNode(node)) { + if (ArgumentChecker.checkNode(node)) { sendUsage(sender, label); - return; + return CommandResult.INVALID_ARGS; } if (Patterns.GROUP_MATCH.matcher(node).matches()) { Message.GROUP_USE_INHERIT.send(sender); - return; + return CommandResult.INVALID_ARGS; } if (!bool.equalsIgnoreCase("true") && !bool.equalsIgnoreCase("false")) { sendUsage(sender, label); - return; + return CommandResult.INVALID_ARGS; } boolean b = Boolean.parseBoolean(bool); @@ -70,46 +72,57 @@ public class GroupSetTempPermission extends SubCommand { duration = DateUtil.parseDateDiff(args.get(2), true); } catch (DateUtil.IllegalDateException e) { Message.ILLEGAL_DATE_ERROR.send(sender, args.get(2)); - return; + return CommandResult.INVALID_ARGS; } if (DateUtil.shouldExpire(duration)) { Message.PAST_DATE_ERROR.send(sender); - return; + return CommandResult.INVALID_ARGS; } try { if (args.size() >= 4) { final String server = args.get(3).toLowerCase(); - if (!ArgumentChecker.checkServer(server)) { + if (ArgumentChecker.checkServer(server)) { Message.SERVER_INVALID_ENTRY.send(sender); - return; + return CommandResult.INVALID_ARGS; } if (args.size() == 4) { group.setPermission(node, b, server, duration); Message.SETPERMISSION_TEMP_SERVER_SUCCESS.send(sender, node, bool, group.getName(), server, DateUtil.formatDateDiff(duration)); + LogEntryBuilder.get().actor(sender).acted(group) + .action("settemp " + node + " " + b + " " + duration + " " + server) + .submit(plugin); } else { final String world = args.get(4).toLowerCase(); group.setPermission(node, b, server, world, duration); Message.SETPERMISSION_TEMP_SERVER_WORLD_SUCCESS.send(sender, node, bool, group.getName(), server, world, DateUtil.formatDateDiff(duration)); + LogEntryBuilder.get().actor(sender).acted(group) + .action("settemp " + node + " " + b + " " + duration + " " + server + " " + world) + .submit(plugin); } } else { group.setPermission(node, b, duration); Message.SETPERMISSION_TEMP_SUCCESS.send(sender, node, bool, group.getName(), DateUtil.formatDateDiff(duration)); + LogEntryBuilder.get().actor(sender).acted(group) + .action("settemp " + node + " " + b + " " + duration) + .submit(plugin); } - saveGroup(group, sender, plugin); + save(group, sender, plugin); + return CommandResult.SUCCESS; } catch (ObjectAlreadyHasException e) { Message.ALREADY_HAS_TEMP_PERMISSION.send(sender, group.getName()); + return CommandResult.STATE_ERROR; } } @Override - public List onTabComplete(Sender sender, List args, LuckPermsPlugin plugin) { + public List onTabComplete(LuckPermsPlugin plugin, Sender sender, List args) { return getBoolTabComplete(args); } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupShowTracks.java b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupShowTracks.java index 24e324fec..39cdd9cc4 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupShowTracks.java +++ b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupShowTracks.java @@ -23,10 +23,7 @@ package me.lucko.luckperms.commands.group.subcommands; import me.lucko.luckperms.LuckPermsPlugin; -import me.lucko.luckperms.commands.Predicate; -import me.lucko.luckperms.commands.Sender; -import me.lucko.luckperms.commands.SubCommand; -import me.lucko.luckperms.commands.Util; +import me.lucko.luckperms.commands.*; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; import me.lucko.luckperms.groups.Group; @@ -42,15 +39,19 @@ public class GroupShowTracks extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { - plugin.getDatastore().loadAllTracks(success -> { - if (!success) { - Message.TRACKS_LOAD_ERROR.send(sender); - return; - } + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { + if (!plugin.getDatastore().loadAllTracks()) { + Message.TRACKS_LOAD_ERROR.send(sender); + return CommandResult.LOADING_ERROR; + } - Message.TRACKS_LIST.send(sender, Util.listToCommaSep( - plugin.getTrackManager().getApplicableTracks(group.getName()).stream().map(Track::getName).collect(Collectors.toList()))); - }); + Message.TRACKS_LIST.send(sender, + Util.listToCommaSep(plugin.getTrackManager().getApplicableTracks(group.getName()).stream() + .map(Track::getName) + .collect(Collectors.toList()) + ) + ); + + return CommandResult.SUCCESS; } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupUnSetPermission.java b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupUnSetPermission.java index 8b04a2969..638e12cda 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupUnSetPermission.java +++ b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupUnSetPermission.java @@ -23,15 +23,17 @@ package me.lucko.luckperms.commands.group.subcommands; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Predicate; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SubCommand; import me.lucko.luckperms.constants.Message; +import me.lucko.luckperms.constants.Patterns; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.exceptions.ObjectLacksException; import me.lucko.luckperms.groups.Group; import me.lucko.luckperms.utils.ArgumentChecker; -import me.lucko.luckperms.utils.Patterns; import java.util.List; @@ -42,44 +44,55 @@ public class GroupUnSetPermission extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { String node = args.get(0); - if (!ArgumentChecker.checkNode(node)) { + if (ArgumentChecker.checkNode(node)) { sendUsage(sender, label); - return; + return CommandResult.INVALID_ARGS; } if (Patterns.GROUP_MATCH.matcher(node).matches()) { Message.GROUP_USE_UNINHERIT.send(sender); - return; + return CommandResult.INVALID_ARGS; } try { if (args.size() >= 2) { final String server = args.get(1).toLowerCase(); - if (!ArgumentChecker.checkServer(server)) { + if (ArgumentChecker.checkServer(server)) { Message.SERVER_INVALID_ENTRY.send(sender); - return; + return CommandResult.INVALID_ARGS; } if (args.size() == 2) { group.unsetPermission(node, server); Message.UNSETPERMISSION_SERVER_SUCCESS.send(sender, node, group.getName(), server); + LogEntryBuilder.get().actor(sender).acted(group) + .action("unset " + node + " " + server) + .submit(plugin); } else { final String world = args.get(2).toLowerCase(); group.unsetPermission(node, server, world); Message.UNSETPERMISSION_SERVER_WORLD_SUCCESS.send(sender, node, group.getName(), server, world); + LogEntryBuilder.get().actor(sender).acted(group) + .action("unset " + node + " " + server + " " + world) + .submit(plugin); } } else { group.unsetPermission(node); Message.UNSETPERMISSION_SUCCESS.send(sender, node, group.getName()); + LogEntryBuilder.get().actor(sender).acted(group) + .action("unset " + node) + .submit(plugin); } - saveGroup(group, sender, plugin); + save(group, sender, plugin); + return CommandResult.SUCCESS; } catch (ObjectLacksException e) { Message.DOES_NOT_HAVEPERMISSION.send(sender, group.getName()); + return CommandResult.STATE_ERROR; } } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupUnsetInherit.java b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupUnsetInherit.java index 724c2ed76..2fff7647d 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupUnsetInherit.java +++ b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupUnsetInherit.java @@ -23,11 +23,13 @@ package me.lucko.luckperms.commands.group.subcommands; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Predicate; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SubCommand; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.exceptions.ObjectLacksException; import me.lucko.luckperms.groups.Group; import me.lucko.luckperms.utils.ArgumentChecker; @@ -42,44 +44,55 @@ public class GroupUnsetInherit extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { String groupName = args.get(0).toLowerCase(); - if (!ArgumentChecker.checkNode(groupName)) { + if (ArgumentChecker.checkNode(groupName)) { sendUsage(sender, label); - return; + return CommandResult.INVALID_ARGS; } try { if (args.size() >= 2) { final String server = args.get(1).toLowerCase(); - if (!ArgumentChecker.checkServer(server)) { + if (ArgumentChecker.checkServer(server)) { Message.SERVER_INVALID_ENTRY.send(sender); - return; + return CommandResult.INVALID_ARGS; } if (args.size() == 2) { group.unsetPermission("group." + groupName, server); Message.GROUP_UNSETINHERIT_SERVER_SUCCESS.send(sender, group.getName(), groupName, server); + LogEntryBuilder.get().actor(sender).acted(group) + .action("unsetinherit " + groupName + " " + server) + .submit(plugin); } else { final String world = args.get(2).toLowerCase(); group.unsetPermission("group." + groupName, server, world); Message.GROUP_UNSETINHERIT_SERVER_WORLD_SUCCESS.send(sender, group.getName(), groupName, server, world); + LogEntryBuilder.get().actor(sender).acted(group) + .action("unsetinherit " + groupName + " " + server + " " + world) + .submit(plugin); } } else { group.unsetPermission("group." + groupName); Message.GROUP_UNSETINHERIT_SUCCESS.send(sender, group.getName(), groupName); + LogEntryBuilder.get().actor(sender).acted(group) + .action("unsetinherit " + groupName) + .submit(plugin); } - saveGroup(group, sender, plugin); + save(group, sender, plugin); + return CommandResult.SUCCESS; } catch (ObjectLacksException e) { Message.GROUP_DOES_NOT_INHERIT.send(sender, group.getName(), groupName); + return CommandResult.STATE_ERROR; } } @Override - public List onTabComplete(Sender sender, List args, LuckPermsPlugin plugin) { + public List onTabComplete(LuckPermsPlugin plugin, Sender sender, List args) { return getGroupTabComplete(args, plugin); } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupUnsetTempInherit.java b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupUnsetTempInherit.java index 9dd33b29f..d3ff21de8 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupUnsetTempInherit.java +++ b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupUnsetTempInherit.java @@ -23,11 +23,13 @@ package me.lucko.luckperms.commands.group.subcommands; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Predicate; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SubCommand; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.exceptions.ObjectLacksException; import me.lucko.luckperms.groups.Group; import me.lucko.luckperms.utils.ArgumentChecker; @@ -42,44 +44,55 @@ public class GroupUnsetTempInherit extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { String groupName = args.get(0).toLowerCase(); - if (!ArgumentChecker.checkNode(groupName)) { + if (ArgumentChecker.checkNode(groupName)) { sendUsage(sender, label); - return; + return CommandResult.INVALID_ARGS; } try { if (args.size() >= 2) { final String server = args.get(1).toLowerCase(); - if (!ArgumentChecker.checkServer(server)) { + if (ArgumentChecker.checkServer(server)) { Message.SERVER_INVALID_ENTRY.send(sender); - return; + return CommandResult.INVALID_ARGS; } if (args.size() == 2) { group.unsetPermission("group." + groupName, server, true); Message.GROUP_UNSET_TEMP_INHERIT_SERVER_SUCCESS.send(sender, group.getName(), groupName, server); + LogEntryBuilder.get().actor(sender).acted(group) + .action("unsettempinherit " + groupName + " " + server) + .submit(plugin); } else { final String world = args.get(2).toLowerCase(); group.unsetPermission("group." + groupName, server, world, true); Message.GROUP_UNSET_TEMP_INHERIT_SERVER_WORLD_SUCCESS.send(sender, group.getName(), groupName, server, world); + LogEntryBuilder.get().actor(sender).acted(group) + .action("unsettempinherit " + groupName + " " + server + " " + world) + .submit(plugin); } } else { group.unsetPermission("group." + groupName, true); Message.GROUP_UNSET_TEMP_INHERIT_SUCCESS.send(sender, group.getName(), groupName); + LogEntryBuilder.get().actor(sender).acted(group) + .action("unsettempinherit " + groupName) + .submit(plugin); } - saveGroup(group, sender, plugin); + save(group, sender, plugin); + return CommandResult.SUCCESS; } catch (ObjectLacksException e) { Message.GROUP_DOES_NOT_TEMP_INHERIT.send(sender, group.getName(), groupName); + return CommandResult.STATE_ERROR; } } @Override - public List onTabComplete(Sender sender, List args, LuckPermsPlugin plugin) { + public List onTabComplete(LuckPermsPlugin plugin, Sender sender, List args) { return getGroupTabComplete(args, plugin); } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupUnsetTempPermission.java b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupUnsetTempPermission.java index fbc375f30..4761b806d 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupUnsetTempPermission.java +++ b/common/src/main/java/me/lucko/luckperms/commands/group/subcommands/GroupUnsetTempPermission.java @@ -23,15 +23,17 @@ package me.lucko.luckperms.commands.group.subcommands; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Predicate; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SubCommand; import me.lucko.luckperms.constants.Message; +import me.lucko.luckperms.constants.Patterns; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.exceptions.ObjectLacksException; import me.lucko.luckperms.groups.Group; import me.lucko.luckperms.utils.ArgumentChecker; -import me.lucko.luckperms.utils.Patterns; import java.util.List; @@ -43,44 +45,55 @@ public class GroupUnsetTempPermission extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Group group, List args, String label) { String node = args.get(0); - if (!ArgumentChecker.checkNode(node)) { + if (ArgumentChecker.checkNode(node)) { sendUsage(sender, label); - return; + return CommandResult.INVALID_ARGS; } if (Patterns.GROUP_MATCH.matcher(node).matches()) { Message.GROUP_USE_UNINHERIT.send(sender); - return; + return CommandResult.INVALID_ARGS; } try { if (args.size() >= 2) { final String server = args.get(1).toLowerCase(); - if (!ArgumentChecker.checkServer(server)) { + if (ArgumentChecker.checkServer(server)) { Message.SERVER_INVALID_ENTRY.send(sender); - return; + return CommandResult.INVALID_ARGS; } if (args.size() == 2) { group.unsetPermission(node, server); Message.UNSET_TEMP_PERMISSION_SERVER_SUCCESS.send(sender, node, group.getName(), server); + LogEntryBuilder.get().actor(sender).acted(group) + .action("unsettemp " + node + " " + server) + .submit(plugin); } else { final String world = args.get(2).toLowerCase(); group.unsetPermission(node, server, world); Message.UNSET_TEMP_PERMISSION_SERVER_WORLD_SUCCESS.send(sender, node, group.getName(), server, world); + LogEntryBuilder.get().actor(sender).acted(group) + .action("unsettemp " + node + " " + server + " " + world) + .submit(plugin); } } else { group.unsetPermission(node, true); Message.UNSET_TEMP_PERMISSION_SUCCESS.send(sender, node, group.getName()); + LogEntryBuilder.get().actor(sender).acted(group) + .action("unsettemp " + node) + .submit(plugin); } - saveGroup(group, sender, plugin); + save(group, sender, plugin); + return CommandResult.SUCCESS; } catch (ObjectLacksException e) { Message.DOES_NOT_HAVE_TEMP_PERMISSION.send(sender, group.getName()); + return CommandResult.STATE_ERROR; } } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/log/LogMainCommand.java b/common/src/main/java/me/lucko/luckperms/commands/log/LogMainCommand.java new file mode 100644 index 000000000..875e9727c --- /dev/null +++ b/common/src/main/java/me/lucko/luckperms/commands/log/LogMainCommand.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2016 Lucko (Luck) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.luckperms.commands.log; + +import com.google.common.collect.ImmutableList; +import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.MainCommand; +import me.lucko.luckperms.commands.Sender; +import me.lucko.luckperms.commands.SubCommand; +import me.lucko.luckperms.commands.log.subcommands.*; +import me.lucko.luckperms.constants.Message; +import me.lucko.luckperms.data.Log; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +public class LogMainCommand extends MainCommand { + public LogMainCommand() { + super("Log", "/%s log", 1, ImmutableList.>builder() + .add(new LogRecent()) + .add(new LogSearch()) + .add(new LogNotify()) + // .add(new LogExport()) + .add(new LogUserHistory()) + .add(new LogGroupHistory()) + .add(new LogTrackHistory()) + .build() + ); + } + + @Override + protected Log getTarget(String target, LuckPermsPlugin plugin, Sender sender) { + Log log = plugin.getDatastore().getLog(); + + if (log == null) { + Message.LOG_LOAD_ERROR.send(sender); + } + + return log; + } + + @Override + protected void cleanup(Log log, LuckPermsPlugin plugin) { + + } + + @Override + protected List getObjects(LuckPermsPlugin plugin) { + return null; + } + + @Override + protected List onTabComplete(Sender sender, List args, LuckPermsPlugin plugin) { + final List> subs = getSubCommands().stream().filter(s -> s.isAuthorized(sender)).collect(Collectors.toList()); + if (args.size() <= 1) { + if (args.isEmpty() || args.get(0).equalsIgnoreCase("")) { + return subs.stream().map(SubCommand::getName).map(String::toLowerCase).collect(Collectors.toList()); + } + + return subs.stream().map(SubCommand::getName).map(String::toLowerCase) + .filter(s -> s.toLowerCase().startsWith(args.get(0).toLowerCase())).collect(Collectors.toList()); + } + + Optional> o = subs.stream().filter(s -> s.getName().equalsIgnoreCase(args.get(0))).limit(1).findAny(); + if (!o.isPresent()) { + return Collections.emptyList(); + } + + return o.get().onTabComplete(plugin, sender, args.subList(1, args.size())); + } +} diff --git a/common/src/main/java/me/lucko/luckperms/commands/log/subcommands/LogExport.java b/common/src/main/java/me/lucko/luckperms/commands/log/subcommands/LogExport.java new file mode 100644 index 000000000..0abd2f271 --- /dev/null +++ b/common/src/main/java/me/lucko/luckperms/commands/log/subcommands/LogExport.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2016 Lucko (Luck) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.luckperms.commands.log.subcommands; + +import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; +import me.lucko.luckperms.commands.Predicate; +import me.lucko.luckperms.commands.Sender; +import me.lucko.luckperms.commands.SubCommand; +import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.Log; + +import java.util.List; + +public class LogExport extends SubCommand { + public LogExport() { + super("export", "Export the log to a file", "/%s log export ", Permission.LOG_EXPORT, Predicate.not(1)); + } + + @Override + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Log log, List args, String label) { + // TODO: implement this + return CommandResult.SUCCESS; + } +} diff --git a/common/src/main/java/me/lucko/luckperms/commands/log/subcommands/LogGroupHistory.java b/common/src/main/java/me/lucko/luckperms/commands/log/subcommands/LogGroupHistory.java new file mode 100644 index 000000000..ed86ef266 --- /dev/null +++ b/common/src/main/java/me/lucko/luckperms/commands/log/subcommands/LogGroupHistory.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2016 Lucko (Luck) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.luckperms.commands.log.subcommands; + +import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.api.LogEntry; +import me.lucko.luckperms.commands.CommandResult; +import me.lucko.luckperms.commands.Predicate; +import me.lucko.luckperms.commands.Sender; +import me.lucko.luckperms.commands.SubCommand; +import me.lucko.luckperms.constants.Message; +import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.Log; +import me.lucko.luckperms.utils.ArgumentChecker; +import me.lucko.luckperms.utils.DateUtil; + +import java.util.List; +import java.util.Map; +import java.util.SortedMap; + +public class LogGroupHistory extends SubCommand { + public LogGroupHistory() { + super("grouphistory", "View an objects history", "/%s log grouphistory [page]", Permission.LOG_GROUP_HISTORY, + Predicate.notInRange(1, 2)); + } + + @Override + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Log log, List args, String label) { + String group = args.get(0); + int page = -999; + + if (args.size() == 2) { + try { + page = Integer.parseInt(args.get(1)); + } catch (NumberFormatException e) { + // invalid page + Message.LOG_INVALID_PAGE.send(sender); + return CommandResult.INVALID_ARGS; + } + } + + if (ArgumentChecker.checkName(group)) { + Message.GROUP_INVALID_ENTRY.send(sender); + return CommandResult.INVALID_ARGS; + } + + int maxPage = log.getGroupHistoryMaxPages(group); + if (maxPage == 0) { + Message.LOG_NO_ENTRIES.send(sender); + return CommandResult.STATE_ERROR; + } + + if (page == -999) { + page = maxPage; + } + + if (page < 1 || page > maxPage) { + Message.LOG_INVALID_PAGE_RANGE.send(sender, maxPage); + return CommandResult.INVALID_ARGS; + } + + SortedMap entries = log.getGroupHistory(page, group); + String name = entries.values().stream().findAny().get().getActedName(); + Message.LOG_HISTORY_GROUP_HEADER.send(sender, name, page, maxPage); + + for (Map.Entry e : entries.entrySet()) { + Message.LOG_ENTRY.send(sender, e.getKey(), DateUtil.formatDateDiff(e.getValue().getTimestamp()), e.getValue().getFormatted()); + } + + return CommandResult.SUCCESS; + } +} diff --git a/common/src/main/java/me/lucko/luckperms/commands/log/subcommands/LogNotify.java b/common/src/main/java/me/lucko/luckperms/commands/log/subcommands/LogNotify.java new file mode 100644 index 000000000..bb2072995 --- /dev/null +++ b/common/src/main/java/me/lucko/luckperms/commands/log/subcommands/LogNotify.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2016 Lucko (Luck) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.luckperms.commands.log.subcommands; + +import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; +import me.lucko.luckperms.commands.Predicate; +import me.lucko.luckperms.commands.Sender; +import me.lucko.luckperms.commands.SubCommand; +import me.lucko.luckperms.constants.Message; +import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.Log; + +import java.util.List; +import java.util.Set; +import java.util.UUID; + +public class LogNotify extends SubCommand { + public LogNotify() { + super("notify", "Toggle notifications", "/%s log notify [on|off]", Permission.LOG_NOTIFY, + Predicate.notInRange(0, 1)); + } + + @Override + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Log log, List args, String label) { + final Set ignoring = plugin.getIgnoringLogs(); + final UUID uuid = sender.getUuid(); + if (args.size() == 0) { + if (ignoring.contains(uuid)) { + // toggle on + ignoring.remove(uuid); + Message.LOG_NOTIFY_TOGGLE_ON.send(sender); + return CommandResult.SUCCESS; + } + // toggle off + ignoring.add(uuid); + Message.LOG_NOTIFY_TOGGLE_OFF.send(sender); + return CommandResult.SUCCESS; + } + + if (args.get(0).equalsIgnoreCase("on")) { + if (!ignoring.contains(uuid)) { + // already on + Message.LOG_NOTIFY_ALREADY_ON.send(sender); + return CommandResult.STATE_ERROR; + } + + // toggle on + ignoring.remove(uuid); + Message.LOG_NOTIFY_TOGGLE_ON.send(sender); + return CommandResult.SUCCESS; + } + + if (args.get(0).equalsIgnoreCase("off")) { + if (ignoring.contains(uuid)) { + // already off + Message.LOG_NOTIFY_ALREADY_OFF.send(sender); + return CommandResult.STATE_ERROR; + } + + // toggle off + ignoring.add(uuid); + Message.LOG_NOTIFY_TOGGLE_OFF.send(sender); + return CommandResult.SUCCESS; + } + + // not recognised + Message.LOG_NOTIFY_UNKNOWN.send(sender); + return CommandResult.INVALID_ARGS; + } +} diff --git a/common/src/main/java/me/lucko/luckperms/commands/log/subcommands/LogRecent.java b/common/src/main/java/me/lucko/luckperms/commands/log/subcommands/LogRecent.java new file mode 100644 index 000000000..a3276791d --- /dev/null +++ b/common/src/main/java/me/lucko/luckperms/commands/log/subcommands/LogRecent.java @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2016 Lucko (Luck) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.luckperms.commands.log.subcommands; + +import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.api.LogEntry; +import me.lucko.luckperms.commands.*; +import me.lucko.luckperms.constants.Message; +import me.lucko.luckperms.constants.Patterns; +import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.Log; +import me.lucko.luckperms.utils.DateUtil; + +import java.util.List; +import java.util.Map; +import java.util.SortedMap; +import java.util.UUID; + +public class LogRecent extends SubCommand { + public LogRecent() { + super("recent", "View recent actions", "/%s log recent [user] [page]", Permission.LOG_RECENT, + Predicate.notInRange(0, 2)); + } + + @Override + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Log log, List args, String label) { + if (args.size() == 0) { + // No page or user + return showLog(log.getRecentMaxPages(), null, sender, log); + } + + if (args.size() == 1) { + // Page or user + try { + int p = Integer.parseInt(args.get(0)); + // page + return showLog(p, null, sender, log); + } catch (NumberFormatException ignored) {} + } + + // User and possibly page + final String s = args.get(0); + UUID u = null; + + u = Util.parseUuid(s); + if (u == null) { + if (s.length() <= 16) { + if (Patterns.NON_USERNAME.matcher(s).find()) { + Message.USER_INVALID_ENTRY.send(sender, s); + return CommandResult.INVALID_ARGS; + } + + Message.USER_ATTEMPTING_LOOKUP.send(sender); + + UUID uuid = plugin.getDatastore().getUUID(s); + + if (uuid == null) { + Message.USER_NOT_FOUND.send(sender); + return CommandResult.INVALID_ARGS; + } + + if (args.size() != 2) { + // Just user + return showLog(log.getRecentMaxPages(uuid), uuid, sender, log); + } + + try { + int p = Integer.parseInt(args.get(1)); + // User and page + return showLog(p, uuid, sender, log); + } catch (NumberFormatException e) { + // Invalid page + return showLog(-1, null, null, null); + } + } + + Message.USER_INVALID_ENTRY.send(sender, s); + return CommandResult.INVALID_ARGS; + } + + if (args.size() != 2) { + // Just user + return showLog(log.getRecentMaxPages(u), u, sender, log); + } else { + try { + int p = Integer.parseInt(args.get(1)); + // User and page + return showLog(p, u, sender, log); + } catch (NumberFormatException e) { + // Invalid page + return showLog(-1, null, null, null); + } + } + } + + private static CommandResult showLog(int page, UUID filter, Sender sender, Log log) { + int maxPage = (filter != null) ? log.getRecentMaxPages(filter) : log.getRecentMaxPages(); + if (maxPage == 0) { + Message.LOG_NO_ENTRIES.send(sender); + return CommandResult.STATE_ERROR; + } + + if (page < 1 || page > maxPage) { + Message.LOG_INVALID_PAGE_RANGE.send(sender, maxPage); + return CommandResult.INVALID_ARGS; + } + + SortedMap entries = (filter != null) ? log.getRecent(page, filter) : log.getRecent(page); + if (filter != null) { + String name = entries.values().stream().findAny().get().getActorName(); + Message.LOG_RECENT_BY_HEADER.send(sender, name, page, maxPage); + } else { + Message.LOG_RECENT_HEADER.send(sender, page, maxPage); + } + + for (Map.Entry e : entries.entrySet()) { + Message.LOG_ENTRY.send(sender, e.getKey(), DateUtil.formatDateDiff(e.getValue().getTimestamp()), e.getValue().getFormatted()); + } + return CommandResult.SUCCESS; + } +} diff --git a/common/src/main/java/me/lucko/luckperms/commands/log/subcommands/LogSearch.java b/common/src/main/java/me/lucko/luckperms/commands/log/subcommands/LogSearch.java new file mode 100644 index 000000000..b9e16f7be --- /dev/null +++ b/common/src/main/java/me/lucko/luckperms/commands/log/subcommands/LogSearch.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2016 Lucko (Luck) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.luckperms.commands.log.subcommands; + +import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.api.LogEntry; +import me.lucko.luckperms.commands.CommandResult; +import me.lucko.luckperms.commands.Predicate; +import me.lucko.luckperms.commands.Sender; +import me.lucko.luckperms.commands.SubCommand; +import me.lucko.luckperms.constants.Message; +import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.Log; +import me.lucko.luckperms.utils.DateUtil; + +import java.util.List; +import java.util.Map; +import java.util.SortedMap; +import java.util.stream.Collectors; + +public class LogSearch extends SubCommand { + public LogSearch() { + super("search", "Search the log for an entry", "/%s log search [page]", Permission.LOG_SEARCH, + Predicate.is(0)); + } + + @Override + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Log log, List args, String label) { + int page = -999; + if (args.size() > 1) { + try { + page = Integer.parseInt(args.get(args.size() - 1)); + args.remove(args.size() - 1); + } catch (NumberFormatException ignored) {} + } + + final String query = args.stream().collect(Collectors.joining(" ")); + + int maxPage = log.getSearchMaxPages(query); + if (maxPage == 0) { + Message.LOG_NO_ENTRIES.send(sender); + return CommandResult.STATE_ERROR; + } + + if (page == -999) { + page = maxPage; + } + + if (page < 1 || page > maxPage) { + Message.LOG_INVALID_PAGE_RANGE.send(sender, maxPage); + return CommandResult.INVALID_ARGS; + } + + SortedMap entries = log.getSearch(page, query); + Message.LOG_SEARCH_HEADER.send(sender, query, page, maxPage); + + for (Map.Entry e : entries.entrySet()) { + Message.LOG_ENTRY.send(sender, e.getKey(), DateUtil.formatDateDiff(e.getValue().getTimestamp()), e.getValue().getFormatted()); + } + + return CommandResult.SUCCESS; + } +} diff --git a/common/src/main/java/me/lucko/luckperms/commands/log/subcommands/LogTrackHistory.java b/common/src/main/java/me/lucko/luckperms/commands/log/subcommands/LogTrackHistory.java new file mode 100644 index 000000000..869327520 --- /dev/null +++ b/common/src/main/java/me/lucko/luckperms/commands/log/subcommands/LogTrackHistory.java @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2016 Lucko (Luck) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.luckperms.commands.log.subcommands; + +import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.api.LogEntry; +import me.lucko.luckperms.commands.CommandResult; +import me.lucko.luckperms.commands.Predicate; +import me.lucko.luckperms.commands.Sender; +import me.lucko.luckperms.commands.SubCommand; +import me.lucko.luckperms.constants.Message; +import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.Log; +import me.lucko.luckperms.utils.ArgumentChecker; +import me.lucko.luckperms.utils.DateUtil; + +import java.util.List; +import java.util.Map; +import java.util.SortedMap; + +public class LogTrackHistory extends SubCommand { + public LogTrackHistory() { + super("trackhistory", "View an objects history", "/%s log trackhistory [page]", Permission.LOG_TRACK_HISTORY, + Predicate.notInRange(1, 2)); + } + + @Override + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Log log, List args, String label) { + String track = args.get(0); + int page = -999; + + if (args.size() == 2) { + try { + page = Integer.parseInt(args.get(1)); + } catch (NumberFormatException e) { + // invalid page + Message.LOG_INVALID_PAGE.send(sender); + return CommandResult.INVALID_ARGS; + } + } + + if (ArgumentChecker.checkName(track)) { + Message.TRACK_INVALID_ENTRY.send(sender); + return CommandResult.INVALID_ARGS; + } + + int maxPage = log.getTrackHistoryMaxPages(track); + if (maxPage == 0) { + Message.LOG_NO_ENTRIES.send(sender); + return CommandResult.STATE_ERROR; + } + + if (page == -999) { + page = maxPage; + } + + if (page < 1 || page > maxPage) { + Message.LOG_INVALID_PAGE_RANGE.send(sender, maxPage); + return CommandResult.INVALID_ARGS; + } + + SortedMap entries = log.getTrackHistory(page, track); + String name = entries.values().stream().findAny().get().getActedName(); + Message.LOG_HISTORY_TRACK_HEADER.send(sender, name, page, maxPage); + + for (Map.Entry e : entries.entrySet()) { + Message.LOG_ENTRY.send(sender, e.getKey(), DateUtil.formatDateDiff(e.getValue().getTimestamp()), e.getValue().getFormatted()); + } + + return CommandResult.SUCCESS; + } +} diff --git a/common/src/main/java/me/lucko/luckperms/commands/log/subcommands/LogUserHistory.java b/common/src/main/java/me/lucko/luckperms/commands/log/subcommands/LogUserHistory.java new file mode 100644 index 000000000..6fec3d20c --- /dev/null +++ b/common/src/main/java/me/lucko/luckperms/commands/log/subcommands/LogUserHistory.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2016 Lucko (Luck) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.luckperms.commands.log.subcommands; + +import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.api.LogEntry; +import me.lucko.luckperms.commands.*; +import me.lucko.luckperms.constants.Message; +import me.lucko.luckperms.constants.Patterns; +import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.Log; +import me.lucko.luckperms.utils.DateUtil; + +import java.util.List; +import java.util.Map; +import java.util.SortedMap; +import java.util.UUID; + +public class LogUserHistory extends SubCommand { + public LogUserHistory() { + super("userhistory", "View an objects history", "/%s log userhistory [page]", Permission.LOG_USER_HISTORY, + Predicate.notInRange(1, 2)); + } + + @Override + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Log log, List args, String label) { + String user = args.get(0); + final int[] page = {-999}; + + if (args.size() == 2) { + try { + page[0] = Integer.parseInt(args.get(1)); + } catch (NumberFormatException e) { + // invalid page + return showLog(-1, null, null, null); + } + } + + UUID uuid = Util.parseUuid(user); + if (uuid != null) { + if (page[0] == -999) { + page[0] = log.getUserHistoryMaxPages(uuid); + } + + return showLog(page[0], uuid, sender, log); + + } + + if (user.length() <= 16) { + if (Patterns.NON_USERNAME.matcher(user).find()) { + Message.USER_INVALID_ENTRY.send(sender, user); + return CommandResult.INVALID_ARGS; + } + + Message.USER_ATTEMPTING_LOOKUP.send(sender); + + UUID uuid1 = plugin.getDatastore().getUUID(user); + + if (uuid1 == null) { + Message.USER_NOT_FOUND.send(sender); + return CommandResult.INVALID_ARGS; + } + + if (page[0] == -999) { + page[0] = log.getUserHistoryMaxPages(uuid1); + } + + return showLog(page[0], uuid1, sender, log); + } + + Message.USER_INVALID_ENTRY.send(sender, user); + return CommandResult.INVALID_ARGS; + } + + private static CommandResult showLog(int page, UUID user, Sender sender, Log log) { + int maxPage = log.getUserHistoryMaxPages(user); + if (maxPage == 0) { + Message.LOG_NO_ENTRIES.send(sender); + return CommandResult.STATE_ERROR; + } + + if (page < 1 || page > maxPage) { + Message.LOG_INVALID_PAGE_RANGE.send(sender, maxPage); + return CommandResult.INVALID_ARGS; + } + + SortedMap entries = log.getUserHistory(page, user); + String name = entries.values().stream().findAny().get().getActedName(); + Message.LOG_HISTORY_USER_HEADER.send(sender, name, page, maxPage); + + for (Map.Entry e : entries.entrySet()) { + Message.LOG_ENTRY.send(sender, e.getKey(), DateUtil.formatDateDiff(e.getValue().getTimestamp()), e.getValue().getFormatted()); + } + + return CommandResult.SUCCESS; + } +} diff --git a/common/src/main/java/me/lucko/luckperms/commands/misc/DebugCommand.java b/common/src/main/java/me/lucko/luckperms/commands/misc/DebugCommand.java index e44bf2558..3f03b7053 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/misc/DebugCommand.java +++ b/common/src/main/java/me/lucko/luckperms/commands/misc/DebugCommand.java @@ -23,6 +23,7 @@ package me.lucko.luckperms.commands.misc; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SingleMainCommand; import me.lucko.luckperms.constants.Message; @@ -36,9 +37,13 @@ public class DebugCommand extends SingleMainCommand { } @Override - protected void execute(LuckPermsPlugin plugin, Sender sender, List args, String label) { - Message.DEBUG.send(sender, plugin.getPlayerCount(), plugin.getUserManager().getUsers().size(), - plugin.getGroupManager().getGroups().size(), plugin.getTrackManager().getTracks().size() + protected CommandResult execute(LuckPermsPlugin plugin, Sender sender, List args, String label) { + Message.DEBUG.send(sender, + plugin.getPlayerCount(), + plugin.getUserManager().getAll().size(), + plugin.getGroupManager().getAll().size(), + plugin.getTrackManager().getAll().size() ); + return CommandResult.SUCCESS; } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/misc/InfoCommand.java b/common/src/main/java/me/lucko/luckperms/commands/misc/InfoCommand.java index 50090bea6..35322a555 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/misc/InfoCommand.java +++ b/common/src/main/java/me/lucko/luckperms/commands/misc/InfoCommand.java @@ -23,23 +23,38 @@ package me.lucko.luckperms.commands.misc; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SingleMainCommand; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; -import me.lucko.luckperms.utils.LPConfiguration; +import me.lucko.luckperms.core.LPConfiguration; import java.util.List; +import static me.lucko.luckperms.commands.Util.formatBoolean; + public class InfoCommand extends SingleMainCommand { public InfoCommand() { super("Info", "/%s info", 0, Permission.INFO); } @Override - protected void execute(LuckPermsPlugin plugin, Sender sender, List args, String label) { + protected CommandResult execute(LuckPermsPlugin plugin, Sender sender, List args, String label) { final LPConfiguration c = plugin.getConfiguration(); - Message.INFO.send(sender, plugin.getVersion(), plugin.getDatastore().getName(), c.getServer(), - c.getDefaultGroupName(), c.getSyncTime(), c.getIncludeGlobalPerms(), c.getOnlineMode(), c.getApplyWildcards()); + Message.INFO.send(sender, + plugin.getVersion(), + plugin.getDatastore().getName(), + c.getServer(), + c.getDefaultGroupName(), + c.getSyncTime(), + formatBoolean(c.getIncludeGlobalPerms()), + formatBoolean(c.getOnlineMode()), + formatBoolean(c.getApplyWildcards()), + formatBoolean(c.getApplyRegex()), + formatBoolean(c.getApplyShorthand()) + ); + + return CommandResult.SUCCESS; } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/misc/SyncCommand.java b/common/src/main/java/me/lucko/luckperms/commands/misc/SyncCommand.java index 902a1557a..4aca76715 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/misc/SyncCommand.java +++ b/common/src/main/java/me/lucko/luckperms/commands/misc/SyncCommand.java @@ -23,6 +23,7 @@ package me.lucko.luckperms.commands.misc; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SingleMainCommand; import me.lucko.luckperms.constants.Message; @@ -36,8 +37,9 @@ public class SyncCommand extends SingleMainCommand { } @Override - protected void execute(LuckPermsPlugin plugin, Sender sender, List args, String label) { + protected CommandResult execute(LuckPermsPlugin plugin, Sender sender, List args, String label) { Message.UPDATE_TASK_RUN.send(sender); plugin.runUpdateTask(); + return CommandResult.SUCCESS; } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/track/CreateTrack.java b/common/src/main/java/me/lucko/luckperms/commands/track/CreateTrack.java index 3a2b884c9..d8290fb81 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/track/CreateTrack.java +++ b/common/src/main/java/me/lucko/luckperms/commands/track/CreateTrack.java @@ -23,10 +23,12 @@ package me.lucko.luckperms.commands.track; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SingleMainCommand; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.utils.ArgumentChecker; import java.util.List; @@ -37,31 +39,31 @@ public class CreateTrack extends SingleMainCommand { } @Override - protected void execute(LuckPermsPlugin plugin, Sender sender, List args, String label) { + protected CommandResult execute(LuckPermsPlugin plugin, Sender sender, List args, String label) { if (args.size() == 0) { sendUsage(sender, label); - return; + return CommandResult.INVALID_ARGS; } String trackName = args.get(0).toLowerCase(); - if (!ArgumentChecker.checkName(trackName)) { + if (ArgumentChecker.checkName(trackName)) { Message.TRACK_INVALID_ENTRY.send(sender); - return; + return CommandResult.INVALID_ARGS; } - plugin.getDatastore().loadTrack(trackName, success -> { - if (success) { - Message.TRACK_ALREADY_EXISTS.send(sender); - } else { - plugin.getDatastore().createAndLoadTrack(trackName, success1 -> { - if (!success1) { - Message.CREATE_TRACK_ERROR.send(sender); - } else { - Message.CREATE_SUCCESS.send(sender, trackName); - plugin.runUpdateTask(); - } - }); - } - }); + if (plugin.getDatastore().loadTrack(trackName)) { + Message.TRACK_ALREADY_EXISTS.send(sender); + return CommandResult.INVALID_ARGS; + } + + if (!plugin.getDatastore().createAndLoadTrack(trackName)) { + Message.CREATE_TRACK_ERROR.send(sender); + return CommandResult.FAILURE; + } + + Message.CREATE_SUCCESS.send(sender, trackName); + LogEntryBuilder.get().actor(sender).actedName(trackName).type('T').action("create").submit(plugin); + plugin.runUpdateTask(); + return CommandResult.SUCCESS; } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/track/DeleteTrack.java b/common/src/main/java/me/lucko/luckperms/commands/track/DeleteTrack.java index 439143179..bebc433db 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/track/DeleteTrack.java +++ b/common/src/main/java/me/lucko/luckperms/commands/track/DeleteTrack.java @@ -23,10 +23,12 @@ package me.lucko.luckperms.commands.track; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SingleMainCommand; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.tracks.Track; import me.lucko.luckperms.utils.ArgumentChecker; @@ -41,43 +43,43 @@ public class DeleteTrack extends SingleMainCommand { } @Override - protected void execute(LuckPermsPlugin plugin, Sender sender, List args, String label) { + protected CommandResult execute(LuckPermsPlugin plugin, Sender sender, List args, String label) { if (args.size() == 0) { sendUsage(sender, label); - return; + return CommandResult.INVALID_ARGS; } String trackName = args.get(0).toLowerCase(); - if (!ArgumentChecker.checkName(trackName)) { + if (ArgumentChecker.checkName(trackName)) { Message.TRACK_INVALID_ENTRY.send(sender); - return; + return CommandResult.INVALID_ARGS; } - plugin.getDatastore().loadTrack(trackName, success -> { - if (!success) { - Message.TRACK_DOES_NOT_EXIST.send(sender); - } else { + if (!plugin.getDatastore().loadTrack(trackName)) { + Message.TRACK_DOES_NOT_EXIST.send(sender); + return CommandResult.INVALID_ARGS; + } - Track track = plugin.getTrackManager().getTrack(trackName); - if (track == null) { - Message.TRACK_LOAD_ERROR.send(sender); - } else { - plugin.getDatastore().deleteTrack(track, success1 -> { - if (!success1) { - Message.DELETE_TRACK_ERROR.send(sender); - } else { - Message.DELETE_SUCCESS.send(sender, trackName); - plugin.runUpdateTask(); - } - }); - } - } - }); + Track track = plugin.getTrackManager().get(trackName); + if (track == null) { + Message.TRACK_LOAD_ERROR.send(sender); + return CommandResult.LOADING_ERROR; + } + + if (!plugin.getDatastore().deleteTrack(track)) { + Message.DELETE_TRACK_ERROR.send(sender); + return CommandResult.FAILURE; + } + + Message.DELETE_SUCCESS.send(sender, trackName); + LogEntryBuilder.get().actor(sender).actedName(trackName).type('T').action("delete").submit(plugin); + plugin.runUpdateTask(); + return CommandResult.SUCCESS; } @Override protected List onTabComplete(Sender sender, List args, LuckPermsPlugin plugin) { - final List tracks = new ArrayList<>(plugin.getTrackManager().getTracks().keySet()); + final List tracks = new ArrayList<>(plugin.getTrackManager().getAll().keySet()); if (args.size() <= 1) { if (args.isEmpty() || args.get(0).equalsIgnoreCase("")) { diff --git a/common/src/main/java/me/lucko/luckperms/commands/track/ListTracks.java b/common/src/main/java/me/lucko/luckperms/commands/track/ListTracks.java index 6a50b61a1..366e2b661 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/track/ListTracks.java +++ b/common/src/main/java/me/lucko/luckperms/commands/track/ListTracks.java @@ -23,6 +23,7 @@ package me.lucko.luckperms.commands.track; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SingleMainCommand; import me.lucko.luckperms.commands.Util; @@ -38,13 +39,13 @@ public class ListTracks extends SingleMainCommand { } @Override - protected void execute(LuckPermsPlugin plugin, Sender sender, List args, String label) { - plugin.getDatastore().loadAllTracks(success -> { - if (!success) { - Message.TRACKS_LOAD_ERROR.send(sender); - } else { - Message.TRACKS_LIST.send(sender, Util.listToCommaSep(new ArrayList<>(plugin.getTrackManager().getTracks().keySet()))); - } - }); + protected CommandResult execute(LuckPermsPlugin plugin, Sender sender, List args, String label) { + if (!plugin.getDatastore().loadAllTracks()) { + Message.TRACKS_LOAD_ERROR.send(sender); + return CommandResult.LOADING_ERROR; + } + + Message.TRACKS_LIST.send(sender, Util.listToCommaSep(new ArrayList<>(plugin.getTrackManager().getAll().keySet()))); + return CommandResult.SUCCESS; } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/track/TrackMainCommand.java b/common/src/main/java/me/lucko/luckperms/commands/track/TrackMainCommand.java index 743251af1..8c212dabc 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/track/TrackMainCommand.java +++ b/common/src/main/java/me/lucko/luckperms/commands/track/TrackMainCommand.java @@ -22,10 +22,12 @@ package me.lucko.luckperms.commands.track; +import com.google.common.collect.ImmutableList; import me.lucko.luckperms.LuckPermsPlugin; -import me.lucko.luckperms.api.data.Callback; import me.lucko.luckperms.commands.MainCommand; import me.lucko.luckperms.commands.Sender; +import me.lucko.luckperms.commands.SubCommand; +import me.lucko.luckperms.commands.track.subcommands.*; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.tracks.Track; import me.lucko.luckperms.utils.ArgumentChecker; @@ -35,33 +37,44 @@ import java.util.List; public class TrackMainCommand extends MainCommand { public TrackMainCommand() { - super("Track", "/%s track ", 2); + super("Track", "/%s track ", 2, ImmutableList.>builder() + .add(new TrackInfo()) + .add(new TrackAppend()) + .add(new TrackInsert()) + .add(new TrackRemove()) + .add(new TrackClear()) + .build() + ); } @Override - protected void getTarget(String target, LuckPermsPlugin plugin, Sender sender, Callback onSuccess) { - if (!ArgumentChecker.checkName(target)) { + protected Track getTarget(String target, LuckPermsPlugin plugin, Sender sender) { + if (ArgumentChecker.checkName(target)) { Message.TRACK_INVALID_ENTRY.send(sender); - return; + return null; } - plugin.getDatastore().loadTrack(target, success -> { - if (!success) { - Message.TRACK_NOT_FOUND.send(sender); - return; - } - Track track = plugin.getTrackManager().getTrack(target); - if (track == null) { - Message.TRACK_NOT_FOUND.send(sender); - return; - } + if (!plugin.getDatastore().loadTrack(target)) { + Message.TRACK_NOT_FOUND.send(sender); + return null; + } + + Track track = plugin.getTrackManager().get(target); + if (track == null) { + Message.TRACK_NOT_FOUND.send(sender); + return null; + } + + return track; + } + + @Override + protected void cleanup(Track track, LuckPermsPlugin plugin) { - onSuccess.onComplete(track); - }); } @Override protected List getObjects(LuckPermsPlugin plugin) { - return new ArrayList<>(plugin.getTrackManager().getTracks().keySet()); + return new ArrayList<>(plugin.getTrackManager().getAll().keySet()); } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/track/subcommands/TrackAppend.java b/common/src/main/java/me/lucko/luckperms/commands/track/subcommands/TrackAppend.java index 036eb0d31..bb32c623c 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/track/subcommands/TrackAppend.java +++ b/common/src/main/java/me/lucko/luckperms/commands/track/subcommands/TrackAppend.java @@ -23,15 +23,14 @@ package me.lucko.luckperms.commands.track.subcommands; import me.lucko.luckperms.LuckPermsPlugin; -import me.lucko.luckperms.commands.Predicate; -import me.lucko.luckperms.commands.Sender; -import me.lucko.luckperms.commands.SubCommand; -import me.lucko.luckperms.commands.Util; +import me.lucko.luckperms.commands.*; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import me.lucko.luckperms.groups.Group; import me.lucko.luckperms.tracks.Track; +import me.lucko.luckperms.utils.ArgumentChecker; import java.util.List; @@ -42,33 +41,42 @@ public class TrackAppend extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, Track track, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Track track, List args, String label) { String groupName = args.get(0).toLowerCase(); - plugin.getDatastore().loadGroup(groupName, success -> { - if (!success) { - Message.GROUP_DOES_NOT_EXIST.send(sender); - } else { - Group group = plugin.getGroupManager().getGroup(groupName); - if (group == null) { - Message.GROUP_DOES_NOT_EXIST.send(sender); - return; - } + if (ArgumentChecker.checkNode(groupName)) { + sendUsage(sender, label); + return CommandResult.INVALID_ARGS; + } - try { - track.appendGroup(group); - Message.TRACK_APPEND_SUCCESS.send(sender, group.getName(), track.getName()); - Message.EMPTY.send(sender, Util.listToArrowSep(track.getGroups(), group.getName())); - saveTrack(track, sender, plugin); - } catch (ObjectAlreadyHasException e) { - Message.TRACK_ALREADY_CONTAINS.send(sender, track.getName(), group.getName()); - } - } - }); + if (!plugin.getDatastore().loadGroup(groupName)) { + Message.GROUP_DOES_NOT_EXIST.send(sender); + return CommandResult.INVALID_ARGS; + } + + Group group = plugin.getGroupManager().get(groupName); + if (group == null) { + Message.GROUP_DOES_NOT_EXIST.send(sender); + return CommandResult.LOADING_ERROR; + } + + try { + track.appendGroup(group); + Message.TRACK_APPEND_SUCCESS.send(sender, group.getName(), track.getName()); + Message.EMPTY.send(sender, Util.listToArrowSep(track.getGroups(), group.getName())); + LogEntryBuilder.get().actor(sender).acted(track) + .action("append " + group.getName()) + .submit(plugin); + save(track, sender, plugin); + return CommandResult.SUCCESS; + } catch (ObjectAlreadyHasException e) { + Message.TRACK_ALREADY_CONTAINS.send(sender, track.getName(), group.getName()); + return CommandResult.STATE_ERROR; + } } @Override - public List onTabComplete(Sender sender, List args, LuckPermsPlugin plugin) { + public List onTabComplete(LuckPermsPlugin plugin, Sender sender, List args) { return getGroupTabComplete(args, plugin); } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/track/subcommands/TrackClear.java b/common/src/main/java/me/lucko/luckperms/commands/track/subcommands/TrackClear.java index 10fffffae..d8634c9ed 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/track/subcommands/TrackClear.java +++ b/common/src/main/java/me/lucko/luckperms/commands/track/subcommands/TrackClear.java @@ -23,11 +23,13 @@ package me.lucko.luckperms.commands.track.subcommands; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Predicate; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SubCommand; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.tracks.Track; import java.util.List; @@ -39,9 +41,11 @@ public class TrackClear extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, Track track, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Track track, List args, String label) { track.clearGroups(); Message.TRACK_CLEAR.send(sender, track.getName()); - saveTrack(track, sender, plugin); + LogEntryBuilder.get().actor(sender).acted(track).action("clear").submit(plugin); + save(track, sender, plugin); + return CommandResult.SUCCESS; } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/track/subcommands/TrackInfo.java b/common/src/main/java/me/lucko/luckperms/commands/track/subcommands/TrackInfo.java index ff0dd956f..1b9cf07e3 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/track/subcommands/TrackInfo.java +++ b/common/src/main/java/me/lucko/luckperms/commands/track/subcommands/TrackInfo.java @@ -23,10 +23,7 @@ package me.lucko.luckperms.commands.track.subcommands; import me.lucko.luckperms.LuckPermsPlugin; -import me.lucko.luckperms.commands.Predicate; -import me.lucko.luckperms.commands.Sender; -import me.lucko.luckperms.commands.SubCommand; -import me.lucko.luckperms.commands.Util; +import me.lucko.luckperms.commands.*; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; import me.lucko.luckperms.tracks.Track; @@ -40,7 +37,8 @@ public class TrackInfo extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, Track track, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Track track, List args, String label) { Message.TRACK_INFO.send(sender, track.getName(), Util.listToArrowSep(track.getGroups())); + return CommandResult.SUCCESS; } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/track/subcommands/TrackInsert.java b/common/src/main/java/me/lucko/luckperms/commands/track/subcommands/TrackInsert.java index 54bf69fe5..4243c3c51 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/track/subcommands/TrackInsert.java +++ b/common/src/main/java/me/lucko/luckperms/commands/track/subcommands/TrackInsert.java @@ -23,15 +23,14 @@ package me.lucko.luckperms.commands.track.subcommands; import me.lucko.luckperms.LuckPermsPlugin; -import me.lucko.luckperms.commands.Predicate; -import me.lucko.luckperms.commands.Sender; -import me.lucko.luckperms.commands.SubCommand; -import me.lucko.luckperms.commands.Util; +import me.lucko.luckperms.commands.*; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import me.lucko.luckperms.groups.Group; import me.lucko.luckperms.tracks.Track; +import me.lucko.luckperms.utils.ArgumentChecker; import java.util.List; @@ -42,42 +41,53 @@ public class TrackInsert extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, Track track, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Track track, List args, String label) { String groupName = args.get(0).toLowerCase(); + + if (ArgumentChecker.checkNode(groupName)) { + sendUsage(sender, label); + return CommandResult.INVALID_ARGS; + } + int pos; try { pos = Integer.parseInt(args.get(1)); } catch (NumberFormatException e) { Message.TRACK_INSERT_ERROR_NUMBER.send(sender, args.get(1)); - return; + return CommandResult.INVALID_ARGS; } - plugin.getDatastore().loadGroup(groupName, success -> { - if (!success) { - Message.GROUP_DOES_NOT_EXIST.send(sender); - } else { - Group group = plugin.getGroupManager().getGroup(groupName); - if (group == null) { - Message.GROUP_DOES_NOT_EXIST.send(sender); - return; - } + if (!plugin.getDatastore().loadGroup(groupName)) { + Message.GROUP_DOES_NOT_EXIST.send(sender); + return CommandResult.INVALID_ARGS; + } - try { - track.insertGroup(group, pos - 1); - Message.TRACK_INSERT_SUCCESS.send(sender, group.getName(), track.getName(), pos); - Message.EMPTY.send(sender, Util.listToArrowSep(track.getGroups(), group.getName())); - saveTrack(track, sender, plugin); - } catch (ObjectAlreadyHasException e) { - Message.TRACK_ALREADY_CONTAINS.send(sender, track.getName(), group.getName()); - } catch (IndexOutOfBoundsException e) { - Message.TRACK_INSERT_ERROR_INVALID_POS.send(sender, pos); - } - } - }); + Group group = plugin.getGroupManager().get(groupName); + if (group == null) { + Message.GROUP_DOES_NOT_EXIST.send(sender); + return CommandResult.LOADING_ERROR; + } + + try { + track.insertGroup(group, pos - 1); + Message.TRACK_INSERT_SUCCESS.send(sender, group.getName(), track.getName(), pos); + Message.EMPTY.send(sender, Util.listToArrowSep(track.getGroups(), group.getName())); + LogEntryBuilder.get().actor(sender).acted(track) + .action("insert " + group.getName() + " " + pos) + .submit(plugin); + save(track, sender, plugin); + return CommandResult.SUCCESS; + } catch (ObjectAlreadyHasException e) { + Message.TRACK_ALREADY_CONTAINS.send(sender, track.getName(), group.getName()); + return CommandResult.STATE_ERROR; + } catch (IndexOutOfBoundsException e) { + Message.TRACK_INSERT_ERROR_INVALID_POS.send(sender, pos); + return CommandResult.INVALID_ARGS; + } } @Override - public List onTabComplete(Sender sender, List args, LuckPermsPlugin plugin) { + public List onTabComplete(LuckPermsPlugin plugin, Sender sender, List args) { return getGroupTabComplete(args, plugin); } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/track/subcommands/TrackRemove.java b/common/src/main/java/me/lucko/luckperms/commands/track/subcommands/TrackRemove.java index 37bb99a66..a228444af 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/track/subcommands/TrackRemove.java +++ b/common/src/main/java/me/lucko/luckperms/commands/track/subcommands/TrackRemove.java @@ -23,13 +23,13 @@ package me.lucko.luckperms.commands.track.subcommands; import me.lucko.luckperms.LuckPermsPlugin; -import me.lucko.luckperms.commands.Predicate; -import me.lucko.luckperms.commands.Sender; -import me.lucko.luckperms.commands.SubCommand; +import me.lucko.luckperms.commands.*; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.exceptions.ObjectLacksException; import me.lucko.luckperms.tracks.Track; +import me.lucko.luckperms.utils.ArgumentChecker; import java.util.List; @@ -40,19 +40,31 @@ public class TrackRemove extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, Track track, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Track track, List args, String label) { String groupName = args.get(0).toLowerCase(); + + if (ArgumentChecker.checkNode(groupName)) { + sendUsage(sender, label); + return CommandResult.INVALID_ARGS; + } + try { track.removeGroup(groupName); Message.TRACK_REMOVE_SUCCESS.send(sender, groupName, track.getName()); - saveTrack(track, sender, plugin); + Message.EMPTY.send(sender, Util.listToArrowSep(track.getGroups())); + LogEntryBuilder.get().actor(sender).acted(track) + .action("remove " + groupName) + .submit(plugin); + save(track, sender, plugin); + return CommandResult.SUCCESS; } catch (ObjectLacksException e) { Message.TRACK_DOES_NOT_CONTAIN.send(sender, track.getName(), groupName); + return CommandResult.STATE_ERROR; } } @Override - public List onTabComplete(Sender sender, List args, LuckPermsPlugin plugin) { + public List onTabComplete(LuckPermsPlugin plugin, Sender sender, List args) { return getGroupTabComplete(args, plugin); } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/user/UserMainCommand.java b/common/src/main/java/me/lucko/luckperms/commands/user/UserMainCommand.java index 75b5762be..406c21829 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/user/UserMainCommand.java +++ b/common/src/main/java/me/lucko/luckperms/commands/user/UserMainCommand.java @@ -22,69 +22,105 @@ package me.lucko.luckperms.commands.user; +import com.google.common.collect.ImmutableList; import me.lucko.luckperms.LuckPermsPlugin; -import me.lucko.luckperms.api.data.Callback; import me.lucko.luckperms.commands.MainCommand; import me.lucko.luckperms.commands.Sender; +import me.lucko.luckperms.commands.SubCommand; import me.lucko.luckperms.commands.Util; +import me.lucko.luckperms.commands.user.subcommands.*; import me.lucko.luckperms.constants.Message; +import me.lucko.luckperms.constants.Patterns; import me.lucko.luckperms.users.User; -import me.lucko.luckperms.utils.Patterns; import java.util.List; import java.util.UUID; public class UserMainCommand extends MainCommand { public UserMainCommand() { - super("User", "/%s user ", 2); + super("User", "/%s user ", 2, ImmutableList.>builder() + .add(new UserInfo()) + .add(new UserGetUUID()) + .add(new UserListNodes()) + .add(new UserHasPerm()) + .add(new UserInheritsPerm()) + .add(new UserSetPermission()) + .add(new UserUnSetPermission()) + .add(new UserAddGroup()) + .add(new UserRemoveGroup()) + .add(new UserSetTempPermission()) + .add(new UserUnsetTempPermission()) + .add(new UserAddTempGroup()) + .add(new UserRemoveTempGroup()) + .add(new UserSetPrimaryGroup()) + .add(new UserShowTracks()) + .add(new UserPromote()) + .add(new UserDemote()) + .add(new UserShowPos()) + .add(new UserClear()) + .build() + ); } @Override - protected void getTarget(String target, LuckPermsPlugin plugin, Sender sender, Callback onSuccess) { + protected User getTarget(String target, LuckPermsPlugin plugin, Sender sender) { UUID u = Util.parseUuid(target); if (u != null) { - runSub(plugin, sender, u, onSuccess); - return; + User user = getUser(plugin, u); + if (user == null) { + + Message.USER_NEVER_JOINED.send(sender); + if (!plugin.getDatastore().loadOrCreateUser(u, "null")) { + Message.USER_CREATE_FAIL.send(sender); + return null; + } + + user = getUser(plugin, u); + } + return user; } if (target.length() <= 16) { if (Patterns.NON_USERNAME.matcher(target).find()) { Message.USER_INVALID_ENTRY.send(sender, target); - return; + return null; } Message.USER_ATTEMPTING_LOOKUP.send(sender); - plugin.getDatastore().getUUID(target, uuid -> { - if (uuid == null) { - Message.USER_NOT_FOUND.send(sender); - return; - } + UUID uuid = plugin.getDatastore().getUUID(target); + if (uuid == null) { + Message.USER_NOT_FOUND.send(sender); + return null; + } - runSub(plugin, sender, uuid, onSuccess); - }); - return; + User user = getUser(plugin, uuid); + if (user == null) { + Message.USER_NOT_FOUND.send(sender); + } + return user; } Message.USER_INVALID_ENTRY.send(sender, target); + return null; } - private void runSub(LuckPermsPlugin plugin, Sender sender, UUID uuid, Callback onSuccess) { - plugin.getDatastore().loadUser(uuid, success -> { - if (!success) { - Message.USER_NOT_FOUND.send(sender); - return; - } + @Override + protected void cleanup(User user, LuckPermsPlugin plugin) { + plugin.getUserManager().cleanup(user); + } - User user = plugin.getUserManager().getUser(uuid); - if (user == null) { - Message.USER_NOT_FOUND.send(sender); - return; - } + private User getUser(LuckPermsPlugin plugin, UUID uuid) { + if (!plugin.getDatastore().loadUser(uuid)) { + return null; + } - onSuccess.onComplete(user); - plugin.getUserManager().cleanupUser(user); - }); + User user = plugin.getUserManager().get(uuid); + if (user == null) { + return null; + } + + return user; } @Override diff --git a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserAddGroup.java b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserAddGroup.java index 575bc4e56..3726914e0 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserAddGroup.java +++ b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserAddGroup.java @@ -23,11 +23,13 @@ package me.lucko.luckperms.commands.user.subcommands; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Predicate; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SubCommand; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import me.lucko.luckperms.groups.Group; import me.lucko.luckperms.users.User; @@ -42,56 +44,66 @@ public class UserAddGroup extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { String groupName = args.get(0).toLowerCase(); - if (!ArgumentChecker.checkNode(groupName)) { + if (ArgumentChecker.checkNode(groupName)) { sendUsage(sender, label); - return; + return CommandResult.INVALID_ARGS; } - plugin.getDatastore().loadGroup(groupName, success -> { - if (!success) { - Message.GROUP_DOES_NOT_EXIST.send(sender); + if (!plugin.getDatastore().loadGroup(groupName)) { + Message.GROUP_DOES_NOT_EXIST.send(sender); + return CommandResult.INVALID_ARGS; + } + + Group group = plugin.getGroupManager().get(groupName); + if (group == null) { + Message.GROUP_DOES_NOT_EXIST.send(sender); + return CommandResult.LOADING_ERROR; + } + + try { + if (args.size() >= 2) { + final String server = args.get(1).toLowerCase(); + if (ArgumentChecker.checkServer(server)) { + Message.SERVER_INVALID_ENTRY.send(sender); + return CommandResult.INVALID_ARGS; + } + + if (args.size() == 2) { + user.addGroup(group, server); + Message.USER_ADDGROUP_SERVER_SUCCESS.send(sender, user.getName(), groupName, server); + LogEntryBuilder.get().actor(sender).acted(user) + .action("addgroup " + group.getName() + " " + server) + .submit(plugin); + } else { + final String world = args.get(2).toLowerCase(); + user.addGroup(group, server, world); + Message.USER_ADDGROUP_SERVER_WORLD_SUCCESS.send(sender, user.getName(), groupName, server, world); + LogEntryBuilder.get().actor(sender).acted(user) + .action("addgroup " + group.getName() + " " + server + " " + world) + .submit(plugin); + } + } else { - Group group = plugin.getGroupManager().getGroup(groupName); - if (group == null) { - Message.GROUP_DOES_NOT_EXIST.send(sender); - return; - } - - try { - if (args.size() >= 2) { - final String server = args.get(1).toLowerCase(); - if (!ArgumentChecker.checkServer(server)) { - Message.SERVER_INVALID_ENTRY.send(sender); - return; - } - - if (args.size() == 2) { - user.addGroup(group, server); - Message.USER_ADDGROUP_SERVER_SUCCESS.send(sender, user.getName(), groupName, server); - } else { - final String world = args.get(2).toLowerCase(); - user.addGroup(group, server, world); - Message.USER_ADDGROUP_SERVER_WORLD_SUCCESS.send(sender, user.getName(), groupName, server, world); - } - - } else { - user.addGroup(group); - Message.USER_ADDGROUP_SUCCESS.send(sender, user.getName(), groupName); - } - - saveUser(user, sender, plugin); - } catch (ObjectAlreadyHasException e) { - Message.USER_ALREADY_MEMBER_OF.send(sender, user.getName(), group.getName()); - } + user.addGroup(group); + Message.USER_ADDGROUP_SUCCESS.send(sender, user.getName(), groupName); + LogEntryBuilder.get().actor(sender).acted(user) + .action("addgroup " + group.getName()) + .submit(plugin); } - }); + + save(user, sender, plugin); + return CommandResult.SUCCESS; + } catch (ObjectAlreadyHasException e) { + Message.USER_ALREADY_MEMBER_OF.send(sender, user.getName(), group.getName()); + return CommandResult.STATE_ERROR; + } } @Override - public List onTabComplete(Sender sender, List args, LuckPermsPlugin plugin) { + public List onTabComplete(LuckPermsPlugin plugin, Sender sender, List args) { return getGroupTabComplete(args, plugin); } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserAddTempGroup.java b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserAddTempGroup.java index cfda45fce..785cd6711 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserAddTempGroup.java +++ b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserAddTempGroup.java @@ -23,11 +23,13 @@ package me.lucko.luckperms.commands.user.subcommands; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Predicate; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SubCommand; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import me.lucko.luckperms.groups.Group; import me.lucko.luckperms.users.User; @@ -44,12 +46,12 @@ public class UserAddTempGroup extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { String groupName = args.get(0).toLowerCase(); - if (!ArgumentChecker.checkNode(groupName)) { + if (ArgumentChecker.checkNode(groupName)) { sendUsage(sender, label); - return; + return CommandResult.INVALID_ARGS; } long duration; @@ -57,58 +59,68 @@ public class UserAddTempGroup extends SubCommand { duration = DateUtil.parseDateDiff(args.get(1), true); } catch (DateUtil.IllegalDateException e) { Message.ILLEGAL_DATE_ERROR.send(sender, args.get(1)); - return; + return CommandResult.INVALID_ARGS; } if (DateUtil.shouldExpire(duration)) { Message.PAST_DATE_ERROR.send(sender); - return; + return CommandResult.INVALID_ARGS; } - plugin.getDatastore().loadGroup(groupName, success -> { - if (!success) { - Message.GROUP_DOES_NOT_EXIST.send(sender); + if (!plugin.getDatastore().loadGroup(groupName)) { + Message.GROUP_DOES_NOT_EXIST.send(sender); + return CommandResult.INVALID_ARGS; + } + + Group group = plugin.getGroupManager().get(groupName); + if (group == null) { + Message.GROUP_DOES_NOT_EXIST.send(sender); + return CommandResult.LOADING_ERROR; + } + + try { + if (args.size() >= 3) { + final String server = args.get(2).toLowerCase(); + if (ArgumentChecker.checkServer(server)) { + Message.SERVER_INVALID_ENTRY.send(sender); + return CommandResult.INVALID_ARGS; + } + + if (args.size() == 3) { + user.addGroup(group, server, duration); + Message.USER_ADDTEMPGROUP_SERVER_SUCCESS.send(sender, user.getName(), groupName, server, + DateUtil.formatDateDiff(duration)); + LogEntryBuilder.get().actor(sender).acted(user) + .action("addtempgroup " + group.getName() + " " + duration + " " + server) + .submit(plugin); + } else { + final String world = args.get(3).toLowerCase(); + user.addGroup(group, server, world, duration); + Message.USER_ADDTEMPGROUP_SERVER_WORLD_SUCCESS.send(sender, user.getName(), groupName, server, + world, DateUtil.formatDateDiff(duration)); + LogEntryBuilder.get().actor(sender).acted(user) + .action("addtempgroup " + group.getName() + " " + duration + " " + server + " " + world) + .submit(plugin); + } + } else { - Group group = plugin.getGroupManager().getGroup(groupName); - if (group == null) { - Message.GROUP_DOES_NOT_EXIST.send(sender); - return; - } - - try { - if (args.size() >= 3) { - final String server = args.get(2).toLowerCase(); - if (!ArgumentChecker.checkServer(server)) { - Message.SERVER_INVALID_ENTRY.send(sender); - return; - } - - if (args.size() == 3) { - user.addGroup(group, server, duration); - Message.USER_ADDTEMPGROUP_SERVER_SUCCESS.send(sender, user.getName(), groupName, server, - DateUtil.formatDateDiff(duration)); - } else { - final String world = args.get(3).toLowerCase(); - user.addGroup(group, server, world, duration); - Message.USER_ADDTEMPGROUP_SERVER_WORLD_SUCCESS.send(sender, user.getName(), groupName, server, - world, DateUtil.formatDateDiff(duration)); - } - - } else { - user.addGroup(group, duration); - Message.USER_ADDTEMPGROUP_SUCCESS.send(sender, user.getName(), groupName, DateUtil.formatDateDiff(duration)); - } - - saveUser(user, sender, plugin); - } catch (ObjectAlreadyHasException e) { - Message.USER_ALREADY_TEMP_MEMBER_OF.send(sender, user.getName(), group.getName()); - } + user.addGroup(group, duration); + Message.USER_ADDTEMPGROUP_SUCCESS.send(sender, user.getName(), groupName, DateUtil.formatDateDiff(duration)); + LogEntryBuilder.get().actor(sender).acted(user) + .action("addtempgroup " + group.getName() + " " + duration) + .submit(plugin); } - }); + + save(user, sender, plugin); + return CommandResult.SUCCESS; + } catch (ObjectAlreadyHasException e) { + Message.USER_ALREADY_TEMP_MEMBER_OF.send(sender, user.getName(), group.getName()); + return CommandResult.STATE_ERROR; + } } @Override - public List onTabComplete(Sender sender, List args, LuckPermsPlugin plugin) { + public List onTabComplete(LuckPermsPlugin plugin, Sender sender, List args) { return getGroupTabComplete(args, plugin); } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserClear.java b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserClear.java index e00250424..85f529366 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserClear.java +++ b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserClear.java @@ -23,11 +23,13 @@ package me.lucko.luckperms.commands.user.subcommands; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Predicate; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SubCommand; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.users.User; import java.util.List; @@ -39,11 +41,13 @@ public class UserClear extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { user.clearNodes(); plugin.getUserManager().giveDefaults(user); Message.CLEAR_SUCCESS.send(sender, user.getName()); + LogEntryBuilder.get().actor(sender).acted(user).action("clear").submit(plugin); - saveUser(user, sender, plugin); + save(user, sender, plugin); + return CommandResult.SUCCESS; } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserDemote.java b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserDemote.java index 55679b949..ab98fd818 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserDemote.java +++ b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserDemote.java @@ -23,12 +23,10 @@ package me.lucko.luckperms.commands.user.subcommands; import me.lucko.luckperms.LuckPermsPlugin; -import me.lucko.luckperms.commands.Predicate; -import me.lucko.luckperms.commands.Sender; -import me.lucko.luckperms.commands.SubCommand; -import me.lucko.luckperms.commands.Util; +import me.lucko.luckperms.commands.*; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import me.lucko.luckperms.exceptions.ObjectLacksException; import me.lucko.luckperms.groups.Group; @@ -45,73 +43,75 @@ public class UserDemote extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { final String trackName = args.get(0).toLowerCase(); - if (!ArgumentChecker.checkName(trackName)) { + if (ArgumentChecker.checkName(trackName)) { Message.TRACK_INVALID_ENTRY.send(sender); - return; + return CommandResult.INVALID_ARGS; } - plugin.getDatastore().loadTrack(trackName, success -> { - if (!success) { - Message.TRACK_DOES_NOT_EXIST.send(sender); - } else { - Track track = plugin.getTrackManager().getTrack(trackName); - if (track == null) { - Message.TRACK_DOES_NOT_EXIST.send(sender); - return; - } + if (!plugin.getDatastore().loadTrack(trackName)) { + Message.TRACK_DOES_NOT_EXIST.send(sender); + return CommandResult.INVALID_ARGS; + } - if (track.getSize() <= 1) { - Message.TRACK_EMPTY.send(sender); - return; - } + Track track = plugin.getTrackManager().get(trackName); + if (track == null) { + Message.TRACK_DOES_NOT_EXIST.send(sender); + return CommandResult.LOADING_ERROR; + } - final String old = user.getPrimaryGroup(); - final String previous; - try { - previous = track.getPrevious(old); - } catch (ObjectLacksException e) { - Message.TRACK_DOES_NOT_CONTAIN.send(sender, track.getName(), old); - Message.USER_DEMOTE_ERROR_NOT_CONTAIN_GROUP.send(sender); - return; - } + if (track.getSize() <= 1) { + Message.TRACK_EMPTY.send(sender); + return CommandResult.STATE_ERROR; + } - if (previous == null) { - Message.USER_DEMOTE_ERROR_ENDOFTRACK.send(sender, track.getName()); - return; - } + final String old = user.getPrimaryGroup(); + final String previous; + try { + previous = track.getPrevious(old); + } catch (ObjectLacksException e) { + Message.TRACK_DOES_NOT_CONTAIN.send(sender, track.getName(), old); + Message.USER_DEMOTE_ERROR_NOT_CONTAIN_GROUP.send(sender); + return CommandResult.STATE_ERROR; + } - plugin.getDatastore().loadGroup(previous, success1 -> { - if (!success1) { - Message.USER_DEMOTE_ERROR_MALFORMED.send(sender, previous); - } else { - Group previousGroup = plugin.getGroupManager().getGroup(previous); - if (previousGroup == null) { - Message.USER_DEMOTE_ERROR_MALFORMED.send(sender, previous); - return; - } + if (previous == null) { + Message.USER_DEMOTE_ERROR_ENDOFTRACK.send(sender, track.getName()); + return CommandResult.STATE_ERROR; + } - try { - user.unsetPermission("group." + old); - } catch (ObjectLacksException ignored) {} - try { - user.addGroup(previousGroup); - } catch (ObjectAlreadyHasException ignored) {} - user.setPrimaryGroup(previousGroup.getName()); + if (!plugin.getDatastore().loadGroup(previous)) { + Message.USER_DEMOTE_ERROR_MALFORMED.send(sender, previous); + return CommandResult.STATE_ERROR; + } - Message.USER_DEMOTE_SUCCESS_PROMOTE.send(sender, track.getName(), old, previousGroup.getName()); - Message.USER_DEMOTE_SUCCESS_REMOVE.send(sender, user.getName(), old, previousGroup.getName(), previousGroup.getName()); - Message.EMPTY.send(sender, Util.listToArrowSep(track.getGroups(), previousGroup.getName(), old, true)); - saveUser(user, sender, plugin); - } - }); - } - }); + Group previousGroup = plugin.getGroupManager().get(previous); + if (previousGroup == null) { + Message.USER_DEMOTE_ERROR_MALFORMED.send(sender, previous); + return CommandResult.LOADING_ERROR; + } + + try { + user.unsetPermission("group." + old); + } catch (ObjectLacksException ignored) {} + try { + user.addGroup(previousGroup); + } catch (ObjectAlreadyHasException ignored) {} + user.setPrimaryGroup(previousGroup.getName()); + + Message.USER_DEMOTE_SUCCESS_PROMOTE.send(sender, track.getName(), old, previousGroup.getName()); + Message.USER_DEMOTE_SUCCESS_REMOVE.send(sender, user.getName(), old, previousGroup.getName(), previousGroup.getName()); + Message.EMPTY.send(sender, Util.listToArrowSep(track.getGroups(), previousGroup.getName(), old, true)); + LogEntryBuilder.get().actor(sender).acted(user) + .action("demote " + track.getName() + "(from " + old + " to " + previousGroup.getName() + ")") + .submit(plugin); + save(user, sender, plugin); + return CommandResult.SUCCESS; } @Override - public List onTabComplete(Sender sender, List args, LuckPermsPlugin plugin) { + public List onTabComplete(LuckPermsPlugin plugin, Sender sender, List args) { return getTrackTabComplete(args, plugin); } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserGetUUID.java b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserGetUUID.java index bbc3a5c2c..76cc15c73 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserGetUUID.java +++ b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserGetUUID.java @@ -23,6 +23,7 @@ package me.lucko.luckperms.commands.user.subcommands; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Predicate; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SubCommand; @@ -39,7 +40,8 @@ public class UserGetUUID extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { Message.USER_GETUUID.send(sender, user.getName(), user.getUuid().toString()); + return CommandResult.SUCCESS; } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserHasPerm.java b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserHasPerm.java index c5e3c6463..8f7833427 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserHasPerm.java +++ b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserHasPerm.java @@ -23,10 +23,7 @@ package me.lucko.luckperms.commands.user.subcommands; import me.lucko.luckperms.LuckPermsPlugin; -import me.lucko.luckperms.commands.Predicate; -import me.lucko.luckperms.commands.Sender; -import me.lucko.luckperms.commands.SubCommand; -import me.lucko.luckperms.commands.Util; +import me.lucko.luckperms.commands.*; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; import me.lucko.luckperms.users.User; @@ -42,11 +39,11 @@ public class UserHasPerm extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { if (args.size() >= 2) { - if (!ArgumentChecker.checkServer(args.get(1))) { + if (ArgumentChecker.checkServer(args.get(1))) { Message.SERVER_INVALID_ENTRY.send(sender); - return; + return CommandResult.INVALID_ARGS; } if (args.size() == 2) { @@ -58,5 +55,6 @@ public class UserHasPerm extends SubCommand { } else { Util.sendBoolean(sender, args.get(0), user.hasPermission(args.get(0), true, "global")); } + return CommandResult.SUCCESS; } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserInfo.java b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserInfo.java index fa7962418..feb4b89fc 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserInfo.java +++ b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserInfo.java @@ -23,10 +23,7 @@ package me.lucko.luckperms.commands.user.subcommands; import me.lucko.luckperms.LuckPermsPlugin; -import me.lucko.luckperms.commands.Predicate; -import me.lucko.luckperms.commands.Sender; -import me.lucko.luckperms.commands.SubCommand; -import me.lucko.luckperms.commands.Util; +import me.lucko.luckperms.commands.*; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; import me.lucko.luckperms.users.User; @@ -39,10 +36,18 @@ public class UserInfo extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { - Message.USER_INFO.send(sender, user.getName(), user.getUuid(), plugin.getPlayerStatus(user.getUuid()), - Util.listToCommaSep(user.getGroupNames()), user.getPrimaryGroup(), - user.getPermanentNodes().keySet().size(), user.getTemporaryNodes().keySet().size(), label, user.getName() + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { + Message.USER_INFO.send(sender, + user.getName(), + user.getUuid(), + plugin.getPlayerStatus(user.getUuid()), + Util.listToCommaSep(user.getGroupNames()), + user.getPrimaryGroup(), + user.getPermanentNodes().keySet().size(), + user.getTemporaryNodes().keySet().size(), + label, + user.getName() ); + return CommandResult.SUCCESS; } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserInheritsPerm.java b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserInheritsPerm.java index 7858d71ac..c875e86d5 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserInheritsPerm.java +++ b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserInheritsPerm.java @@ -23,10 +23,7 @@ package me.lucko.luckperms.commands.user.subcommands; import me.lucko.luckperms.LuckPermsPlugin; -import me.lucko.luckperms.commands.Predicate; -import me.lucko.luckperms.commands.Sender; -import me.lucko.luckperms.commands.SubCommand; -import me.lucko.luckperms.commands.Util; +import me.lucko.luckperms.commands.*; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; import me.lucko.luckperms.users.User; @@ -42,11 +39,11 @@ public class UserInheritsPerm extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { if (args.size() >= 2) { - if (!ArgumentChecker.checkServer(args.get(1))) { + if (ArgumentChecker.checkServer(args.get(1))) { Message.SERVER_INVALID_ENTRY.send(sender); - return; + return CommandResult.INVALID_ARGS; } if (args.size() == 2) { @@ -58,5 +55,6 @@ public class UserInheritsPerm extends SubCommand { } else { Util.sendBoolean(sender, args.get(0), user.inheritsPermission(args.get(0), true)); } + return CommandResult.SUCCESS; } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserListNodes.java b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserListNodes.java index a3dd105f5..9d0176f9e 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserListNodes.java +++ b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserListNodes.java @@ -23,10 +23,7 @@ package me.lucko.luckperms.commands.user.subcommands; import me.lucko.luckperms.LuckPermsPlugin; -import me.lucko.luckperms.commands.Predicate; -import me.lucko.luckperms.commands.Sender; -import me.lucko.luckperms.commands.SubCommand; -import me.lucko.luckperms.commands.Util; +import me.lucko.luckperms.commands.*; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; import me.lucko.luckperms.users.User; @@ -40,8 +37,9 @@ public class UserListNodes extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { Message.LISTNODES.send(sender, user.getName(), Util.permNodesToString(user.getPermanentNodes())); Message.LISTNODES_TEMP.send(sender, user.getName(), Util.tempNodesToString(user.getTemporaryNodes())); + return CommandResult.SUCCESS; } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserPromote.java b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserPromote.java index 18d0203f1..a8929271c 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserPromote.java +++ b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserPromote.java @@ -23,12 +23,10 @@ package me.lucko.luckperms.commands.user.subcommands; import me.lucko.luckperms.LuckPermsPlugin; -import me.lucko.luckperms.commands.Predicate; -import me.lucko.luckperms.commands.Sender; -import me.lucko.luckperms.commands.SubCommand; -import me.lucko.luckperms.commands.Util; +import me.lucko.luckperms.commands.*; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import me.lucko.luckperms.exceptions.ObjectLacksException; import me.lucko.luckperms.groups.Group; @@ -45,73 +43,75 @@ public class UserPromote extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { final String trackName = args.get(0).toLowerCase(); - if (!ArgumentChecker.checkName(trackName)) { + if (ArgumentChecker.checkName(trackName)) { Message.TRACK_INVALID_ENTRY.send(sender); - return; + return CommandResult.INVALID_ARGS; } - plugin.getDatastore().loadTrack(trackName, success -> { - if (!success) { - Message.TRACK_DOES_NOT_EXIST.send(sender); - } else { - Track track = plugin.getTrackManager().getTrack(trackName); - if (track == null) { - Message.TRACK_DOES_NOT_EXIST.send(sender); - return; - } + if (!plugin.getDatastore().loadTrack(trackName)) { + Message.TRACK_DOES_NOT_EXIST.send(sender); + return CommandResult.INVALID_ARGS; + } - if (track.getSize() <= 1) { - Message.TRACK_EMPTY.send(sender); - return; - } + Track track = plugin.getTrackManager().get(trackName); + if (track == null) { + Message.TRACK_DOES_NOT_EXIST.send(sender); + return CommandResult.LOADING_ERROR; + } - final String old = user.getPrimaryGroup(); - final String next; - try { - next = track.getNext(old); - } catch (ObjectLacksException e) { - Message.TRACK_DOES_NOT_CONTAIN.send(sender, track.getName(), old); - Message.USER_PROMOTE_ERROR_NOT_CONTAIN_GROUP.send(sender); - return; - } + if (track.getSize() <= 1) { + Message.TRACK_EMPTY.send(sender); + return CommandResult.STATE_ERROR; + } - if (next == null) { - Message.USER_PROMOTE_ERROR_ENDOFTRACK.send(sender, track.getName()); - return; - } + final String old = user.getPrimaryGroup(); + final String next; + try { + next = track.getNext(old); + } catch (ObjectLacksException e) { + Message.TRACK_DOES_NOT_CONTAIN.send(sender, track.getName(), old); + Message.USER_PROMOTE_ERROR_NOT_CONTAIN_GROUP.send(sender); + return CommandResult.STATE_ERROR; + } - plugin.getDatastore().loadGroup(next, success1 -> { - if (!success1) { - Message.USER_PROMOTE_ERROR_MALFORMED.send(sender, next); - } else { - Group nextGroup = plugin.getGroupManager().getGroup(next); - if (nextGroup == null) { - Message.USER_PROMOTE_ERROR_MALFORMED.send(sender, next); - return; - } + if (next == null) { + Message.USER_PROMOTE_ERROR_ENDOFTRACK.send(sender, track.getName()); + return CommandResult.STATE_ERROR; + } - try { - user.unsetPermission("group." + old); - } catch (ObjectLacksException ignored) {} - try { - user.addGroup(nextGroup); - } catch (ObjectAlreadyHasException ignored) {} - user.setPrimaryGroup(nextGroup.getName()); + if (!plugin.getDatastore().loadGroup(next)) { + Message.USER_PROMOTE_ERROR_MALFORMED.send(sender, next); + return CommandResult.STATE_ERROR; + } - Message.USER_PROMOTE_SUCCESS_PROMOTE.send(sender, track.getName(), old, nextGroup.getName()); - Message.USER_PROMOTE_SUCCESS_REMOVE.send(sender, user.getName(), old, nextGroup.getName(), nextGroup.getName()); - Message.EMPTY.send(sender, Util.listToArrowSep(track.getGroups(), old, nextGroup.getName(), false)); - saveUser(user, sender, plugin); - } - }); - } - }); + Group nextGroup = plugin.getGroupManager().get(next); + if (nextGroup == null) { + Message.USER_PROMOTE_ERROR_MALFORMED.send(sender, next); + return CommandResult.LOADING_ERROR; + } + + try { + user.unsetPermission("group." + old); + } catch (ObjectLacksException ignored) {} + try { + user.addGroup(nextGroup); + } catch (ObjectAlreadyHasException ignored) {} + user.setPrimaryGroup(nextGroup.getName()); + + Message.USER_PROMOTE_SUCCESS_PROMOTE.send(sender, track.getName(), old, nextGroup.getName()); + Message.USER_PROMOTE_SUCCESS_REMOVE.send(sender, user.getName(), old, nextGroup.getName(), nextGroup.getName()); + Message.EMPTY.send(sender, Util.listToArrowSep(track.getGroups(), old, nextGroup.getName(), false)); + LogEntryBuilder.get().actor(sender).acted(user) + .action("promote " + track.getName() + "(from " + old + " to " + nextGroup.getName() + ")") + .submit(plugin); + save(user, sender, plugin); + return CommandResult.SUCCESS; } @Override - public List onTabComplete(Sender sender, List args, LuckPermsPlugin plugin) { + public List onTabComplete(LuckPermsPlugin plugin, Sender sender, List args) { return getTrackTabComplete(args, plugin); } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserRemoveGroup.java b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserRemoveGroup.java index 67183a343..9b35f8187 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserRemoveGroup.java +++ b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserRemoveGroup.java @@ -23,11 +23,13 @@ package me.lucko.luckperms.commands.user.subcommands; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Predicate; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SubCommand; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.exceptions.ObjectLacksException; import me.lucko.luckperms.users.User; import me.lucko.luckperms.utils.ArgumentChecker; @@ -41,50 +43,61 @@ public class UserRemoveGroup extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { String groupName = args.get(0).toLowerCase(); - if (!ArgumentChecker.checkNode(groupName)) { + if (ArgumentChecker.checkNode(groupName)) { sendUsage(sender, label); - return; + return CommandResult.INVALID_ARGS; } if ((args.size() == 1 || (args.size() == 2 && args.get(1).equalsIgnoreCase("global"))) && user.getPrimaryGroup().equalsIgnoreCase(groupName)) { Message.USER_REMOVEGROUP_ERROR_PRIMARY.send(sender); - return; + return CommandResult.STATE_ERROR; } try { if (args.size() >= 2) { final String server = args.get(1).toLowerCase(); - if (!ArgumentChecker.checkServer(server)) { + if (ArgumentChecker.checkServer(server)) { Message.SERVER_INVALID_ENTRY.send(sender); - return; + return CommandResult.INVALID_ARGS; } if (args.size() == 2) { user.unsetPermission("group." + groupName, server); Message.USER_REMOVEGROUP_SERVER_SUCCESS.send(sender, user.getName(), groupName, server); + LogEntryBuilder.get().actor(sender).acted(user) + .action("removegroup " + groupName + " " + server) + .submit(plugin); } else { final String world = args.get(2).toLowerCase(); user.unsetPermission("group." + groupName, server, world); Message.USER_REMOVEGROUP_SERVER_WORLD_SUCCESS.send(sender, user.getName(), groupName, server, world); + LogEntryBuilder.get().actor(sender).acted(user) + .action("removegroup " + groupName + " " + server + " " + world) + .submit(plugin); } } else { user.unsetPermission("group." + groupName); Message.USER_REMOVEGROUP_SUCCESS.send(sender, user.getName(), groupName); + LogEntryBuilder.get().actor(sender).acted(user) + .action("removegroup " + groupName) + .submit(plugin); } - saveUser(user, sender, plugin); + save(user, sender, plugin); + return CommandResult.SUCCESS; } catch (ObjectLacksException e) { Message.USER_NOT_MEMBER_OF.send(sender, user.getName(), groupName); + return CommandResult.STATE_ERROR; } } @Override - public List onTabComplete(Sender sender, List args, LuckPermsPlugin plugin) { + public List onTabComplete(LuckPermsPlugin plugin, Sender sender, List args) { return getGroupTabComplete(args, plugin); } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserRemoveTempGroup.java b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserRemoveTempGroup.java index 63389105f..8c239859f 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserRemoveTempGroup.java +++ b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserRemoveTempGroup.java @@ -23,11 +23,13 @@ package me.lucko.luckperms.commands.user.subcommands; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Predicate; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SubCommand; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.exceptions.ObjectLacksException; import me.lucko.luckperms.users.User; import me.lucko.luckperms.utils.ArgumentChecker; @@ -42,44 +44,55 @@ public class UserRemoveTempGroup extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { String groupName = args.get(0).toLowerCase(); - if (!ArgumentChecker.checkNode(groupName)) { + if (ArgumentChecker.checkNode(groupName)) { sendUsage(sender, label); - return; + return CommandResult.INVALID_ARGS; } try { if (args.size() >= 2) { final String server = args.get(1).toLowerCase(); - if (!ArgumentChecker.checkServer(server)) { + if (ArgumentChecker.checkServer(server)) { Message.SERVER_INVALID_ENTRY.send(sender); - return; + return CommandResult.INVALID_ARGS; } if (args.size() == 2) { user.unsetPermission("group." + groupName, server, true); Message.USER_REMOVETEMPGROUP_SERVER_SUCCESS.send(sender, user.getName(), groupName, server); + LogEntryBuilder.get().actor(sender).acted(user) + .action("removetempgroup " + groupName + " " + server) + .submit(plugin); } else { final String world = args.get(2).toLowerCase(); user.unsetPermission("group." + groupName, server, world, true); Message.USER_REMOVETEMPGROUP_SERVER_WORLD_SUCCESS.send(sender, user.getName(), groupName, server, world); + LogEntryBuilder.get().actor(sender).acted(user) + .action("removetempgroup " + groupName + " " + server + " " + world) + .submit(plugin); } } else { user.unsetPermission("group." + groupName, true); Message.USER_REMOVETEMPGROUP_SUCCESS.send(sender, user.getName(), groupName); + LogEntryBuilder.get().actor(sender).acted(user) + .action("removetempgroup " + groupName) + .submit(plugin); } - saveUser(user, sender, plugin); + save(user, sender, plugin); + return CommandResult.SUCCESS; } catch (ObjectLacksException e) { Message.USER_NOT_TEMP_MEMBER_OF.send(sender, user.getName(), groupName); + return CommandResult.STATE_ERROR; } } @Override - public List onTabComplete(Sender sender, List args, LuckPermsPlugin plugin) { + public List onTabComplete(LuckPermsPlugin plugin, Sender sender, List args) { return getGroupTabComplete(args, plugin); } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserSetPermission.java b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserSetPermission.java index 076e6d4b3..af12dddec 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserSetPermission.java +++ b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserSetPermission.java @@ -23,15 +23,17 @@ package me.lucko.luckperms.commands.user.subcommands; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Predicate; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SubCommand; import me.lucko.luckperms.constants.Message; +import me.lucko.luckperms.constants.Patterns; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import me.lucko.luckperms.users.User; import me.lucko.luckperms.utils.ArgumentChecker; -import me.lucko.luckperms.utils.Patterns; import java.util.List; @@ -43,23 +45,23 @@ public class UserSetPermission extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { String node = args.get(0); String bool = args.get(1).toLowerCase(); - if (!ArgumentChecker.checkNode(node)) { + if (ArgumentChecker.checkNode(node)) { sendUsage(sender, label); - return; + return CommandResult.INVALID_ARGS; } if (Patterns.GROUP_MATCH.matcher(node).matches()) { Message.USER_USE_ADDGROUP.send(sender); - return; + return CommandResult.INVALID_ARGS; } if (!bool.equalsIgnoreCase("true") && !bool.equalsIgnoreCase("false")) { sendUsage(sender, label); - return; + return CommandResult.INVALID_ARGS; } boolean b = Boolean.parseBoolean(bool); @@ -67,33 +69,44 @@ public class UserSetPermission extends SubCommand { try { if (args.size() >= 3) { final String server = args.get(2).toLowerCase(); - if (!ArgumentChecker.checkServer(server)) { + if (ArgumentChecker.checkServer(server)) { Message.SERVER_INVALID_ENTRY.send(sender); - return; + return CommandResult.INVALID_ARGS; } if (args.size() == 3) { user.setPermission(node, b, server); Message.SETPERMISSION_SERVER_SUCCESS.send(sender, node, bool, user.getName(), server); + LogEntryBuilder.get().actor(sender).acted(user) + .action("set " + node + " " + b + " " + server) + .submit(plugin); } else { final String world = args.get(3).toLowerCase(); user.setPermission(node, b, server, world); Message.SETPERMISSION_SERVER_WORLD_SUCCESS.send(sender, node, bool, user.getName(), server, world); + LogEntryBuilder.get().actor(sender).acted(user) + .action("set " + node + " " + b + " " + server + " " + world) + .submit(plugin); } } else { user.setPermission(node, b); Message.SETPERMISSION_SUCCESS.send(sender, node, bool, user.getName()); + LogEntryBuilder.get().actor(sender).acted(user) + .action("set " + node + " " + b) + .submit(plugin); } - saveUser(user, sender, plugin); + save(user, sender, plugin); + return CommandResult.SUCCESS; } catch (ObjectAlreadyHasException e) { Message.ALREADY_HASPERMISSION.send(sender, user.getName()); + return CommandResult.STATE_ERROR; } } @Override - public List onTabComplete(Sender sender, List args, LuckPermsPlugin plugin) { + public List onTabComplete(LuckPermsPlugin plugin, Sender sender, List args) { return getBoolTabComplete(args); } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserSetPrimaryGroup.java b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserSetPrimaryGroup.java index b848d845b..742fcfe11 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserSetPrimaryGroup.java +++ b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserSetPrimaryGroup.java @@ -23,11 +23,13 @@ package me.lucko.luckperms.commands.user.subcommands; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Predicate; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SubCommand; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.groups.Group; import me.lucko.luckperms.users.User; @@ -40,31 +42,35 @@ public class UserSetPrimaryGroup extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { - Group group = plugin.getGroupManager().getGroup(args.get(0).toLowerCase()); + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { + Group group = plugin.getGroupManager().get(args.get(0).toLowerCase()); if (group == null) { Message.GROUP_DOES_NOT_EXIST.send(sender); - return; + return CommandResult.INVALID_ARGS; } if (user.getPrimaryGroup().equalsIgnoreCase(group.getName())) { Message.USER_PRIMARYGROUP_ERROR_ALREADYHAS.send(sender); - return; + return CommandResult.STATE_ERROR; } if (!user.isInGroup(group)) { Message.USER_PRIMARYGROUP_ERROR_NOTMEMBER.send(sender, label); - return; + return CommandResult.STATE_ERROR; } user.setPrimaryGroup(group.getName()); Message.USER_PRIMARYGROUP_SUCCESS.send(sender, user.getName(), group.getName()); + LogEntryBuilder.get().actor(sender).acted(user) + .action("setprimarygroup " + group.getName()) + .submit(plugin); - saveUser(user, sender, plugin); + save(user, sender, plugin); + return CommandResult.SUCCESS; } @Override - public List onTabComplete(Sender sender, List args, LuckPermsPlugin plugin) { + public List onTabComplete(LuckPermsPlugin plugin, Sender sender, List args) { return getGroupTabComplete(args, plugin); } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserSetTempPermission.java b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserSetTempPermission.java index 24c02669c..f3c580a39 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserSetTempPermission.java +++ b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserSetTempPermission.java @@ -23,16 +23,18 @@ package me.lucko.luckperms.commands.user.subcommands; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Predicate; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SubCommand; import me.lucko.luckperms.constants.Message; +import me.lucko.luckperms.constants.Patterns; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import me.lucko.luckperms.users.User; import me.lucko.luckperms.utils.ArgumentChecker; import me.lucko.luckperms.utils.DateUtil; -import me.lucko.luckperms.utils.Patterns; import java.util.List; @@ -44,23 +46,23 @@ public class UserSetTempPermission extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { String node = args.get(0); String bool = args.get(1).toLowerCase(); - if (!ArgumentChecker.checkNode(node)) { + if (ArgumentChecker.checkNode(node)) { sendUsage(sender, label); - return; + return CommandResult.INVALID_ARGS; } if (Patterns.GROUP_MATCH.matcher(node).matches()) { Message.USER_USE_ADDGROUP.send(sender); - return; + return CommandResult.INVALID_ARGS; } if (!bool.equalsIgnoreCase("true") && !bool.equalsIgnoreCase("false")) { sendUsage(sender, label); - return; + return CommandResult.INVALID_ARGS; } boolean b = Boolean.parseBoolean(bool); @@ -70,44 +72,55 @@ public class UserSetTempPermission extends SubCommand { duration = DateUtil.parseDateDiff(args.get(2), true); } catch (DateUtil.IllegalDateException e) { Message.ILLEGAL_DATE_ERROR.send(sender, args.get(2)); - return; + return CommandResult.INVALID_ARGS; } if (DateUtil.shouldExpire(duration)) { Message.PAST_DATE_ERROR.send(sender); - return; + return CommandResult.INVALID_ARGS; } try { if (args.size() >= 4) { final String server = args.get(3).toLowerCase(); - if (!ArgumentChecker.checkServer(server)) { + if (ArgumentChecker.checkServer(server)) { Message.SERVER_INVALID_ENTRY.send(sender); - return; + return CommandResult.INVALID_ARGS; } if (args.size() == 4) { user.setPermission(node, b, server, duration); Message.SETPERMISSION_TEMP_SERVER_SUCCESS.send(sender, node, bool, user.getName(), server, DateUtil.formatDateDiff(duration)); + LogEntryBuilder.get().actor(sender).acted(user) + .action("settemp " + node + " " + b + " " + duration + " " + server) + .submit(plugin); } else { final String world = args.get(4).toLowerCase(); user.setPermission(node, b, server, world, duration); Message.SETPERMISSION_TEMP_SERVER_WORLD_SUCCESS.send(sender, node, bool, user.getName(), server, world, DateUtil.formatDateDiff(duration)); + LogEntryBuilder.get().actor(sender).acted(user) + .action("settemp " + node + " " + b + " " + duration + " " + server + " " + world) + .submit(plugin); } } else { user.setPermission(node, b, duration); Message.SETPERMISSION_TEMP_SUCCESS.send(sender, node, bool, user.getName(), DateUtil.formatDateDiff(duration)); + LogEntryBuilder.get().actor(sender).acted(user) + .action("settemp " + node + " " + b + " " + duration) + .submit(plugin); } - saveUser(user, sender, plugin); + save(user, sender, plugin); + return CommandResult.SUCCESS; } catch (ObjectAlreadyHasException e) { Message.ALREADY_HAS_TEMP_PERMISSION.send(sender, user.getName()); + return CommandResult.STATE_ERROR; } } @Override - public List onTabComplete(Sender sender, List args, LuckPermsPlugin plugin) { + public List onTabComplete(LuckPermsPlugin plugin, Sender sender, List args) { return getBoolTabComplete(args); } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserShowPos.java b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserShowPos.java index 438ac5d03..3e66507b4 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserShowPos.java +++ b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserShowPos.java @@ -23,10 +23,7 @@ package me.lucko.luckperms.commands.user.subcommands; import me.lucko.luckperms.LuckPermsPlugin; -import me.lucko.luckperms.commands.Predicate; -import me.lucko.luckperms.commands.Sender; -import me.lucko.luckperms.commands.SubCommand; -import me.lucko.luckperms.commands.Util; +import me.lucko.luckperms.commands.*; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; import me.lucko.luckperms.tracks.Track; @@ -42,40 +39,40 @@ public class UserShowPos extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { final String trackName = args.get(0).toLowerCase(); - if (!ArgumentChecker.checkName(trackName)) { + if (ArgumentChecker.checkName(trackName)) { Message.TRACK_INVALID_ENTRY.send(sender); - return; + return CommandResult.INVALID_ARGS; } - plugin.getDatastore().loadTrack(trackName, success -> { - if (!success) { - Message.TRACK_DOES_NOT_EXIST.send(sender); - } else { - Track track = plugin.getTrackManager().getTrack(trackName); - if (track == null) { - Message.TRACK_DOES_NOT_EXIST.send(sender); - return; - } + if (!plugin.getDatastore().loadTrack(trackName)) { + Message.TRACK_DOES_NOT_EXIST.send(sender); + return CommandResult.INVALID_ARGS; + } - if (track.getSize() <= 1) { - Message.TRACK_EMPTY.send(sender); - return; - } + Track track = plugin.getTrackManager().get(trackName); + if (track == null) { + Message.TRACK_DOES_NOT_EXIST.send(sender); + return CommandResult.LOADING_ERROR; + } - if (!track.containsGroup(user.getPrimaryGroup())) { - Message.TRACK_DOES_NOT_CONTAIN.send(sender, track.getName(), user.getPrimaryGroup()); - return; - } + if (track.getSize() <= 1) { + Message.TRACK_EMPTY.send(sender); + return CommandResult.STATE_ERROR; + } - Message.USER_SHOWPOS.send(sender, user.getName(), track.getName(), Util.listToArrowSep(track.getGroups(), user.getPrimaryGroup())); - } - }); + if (!track.containsGroup(user.getPrimaryGroup())) { + Message.TRACK_DOES_NOT_CONTAIN.send(sender, track.getName(), user.getPrimaryGroup()); + return CommandResult.STATE_ERROR; + } + + Message.USER_SHOWPOS.send(sender, user.getName(), track.getName(), Util.listToArrowSep(track.getGroups(), user.getPrimaryGroup())); + return CommandResult.SUCCESS; } @Override - public List onTabComplete(Sender sender, List args, LuckPermsPlugin plugin) { + public List onTabComplete(LuckPermsPlugin plugin, Sender sender, List args) { return getTrackTabComplete(args, plugin); } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserShowTracks.java b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserShowTracks.java index 64d489f4e..ec4aedc7c 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserShowTracks.java +++ b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserShowTracks.java @@ -23,10 +23,7 @@ package me.lucko.luckperms.commands.user.subcommands; import me.lucko.luckperms.LuckPermsPlugin; -import me.lucko.luckperms.commands.Predicate; -import me.lucko.luckperms.commands.Sender; -import me.lucko.luckperms.commands.SubCommand; -import me.lucko.luckperms.commands.Util; +import me.lucko.luckperms.commands.*; import me.lucko.luckperms.constants.Message; import me.lucko.luckperms.constants.Permission; import me.lucko.luckperms.tracks.Track; @@ -42,16 +39,20 @@ public class UserShowTracks extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { - plugin.getDatastore().loadAllTracks(success -> { - if (!success) { - Message.TRACKS_LOAD_ERROR.send(sender); - return; - } + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { + if (!plugin.getDatastore().loadAllTracks()) { + Message.TRACKS_LOAD_ERROR.send(sender); + return CommandResult.LOADING_ERROR; + } - Message.USER_SHOWTRACKS_INFO.send(sender, user.getPrimaryGroup(), user.getName()); - Message.TRACKS_LIST.send(sender, Util.listToCommaSep( - plugin.getTrackManager().getApplicableTracks(user.getPrimaryGroup()).stream().map(Track::getName).collect(Collectors.toList()))); - }); + Message.USER_SHOWTRACKS_INFO.send(sender, user.getPrimaryGroup(), user.getName()); + Message.TRACKS_LIST.send(sender, + Util.listToCommaSep(plugin.getTrackManager().getApplicableTracks(user.getPrimaryGroup()).stream() + .map(Track::getName) + .collect(Collectors.toList()) + ) + ); + + return CommandResult.SUCCESS; } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserUnSetPermission.java b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserUnSetPermission.java index 631def495..a9125d68d 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserUnSetPermission.java +++ b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserUnSetPermission.java @@ -23,15 +23,17 @@ package me.lucko.luckperms.commands.user.subcommands; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Predicate; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SubCommand; import me.lucko.luckperms.constants.Message; +import me.lucko.luckperms.constants.Patterns; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.exceptions.ObjectLacksException; import me.lucko.luckperms.users.User; import me.lucko.luckperms.utils.ArgumentChecker; -import me.lucko.luckperms.utils.Patterns; import java.util.List; @@ -42,44 +44,55 @@ public class UserUnSetPermission extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { String node = args.get(0); - if (!ArgumentChecker.checkNode(node)) { + if (ArgumentChecker.checkNode(node)) { sendUsage(sender, label); - return; + return CommandResult.INVALID_ARGS; } if (Patterns.GROUP_MATCH.matcher(node).matches()) { Message.USER_USE_REMOVEGROUP.send(sender); - return; + return CommandResult.INVALID_ARGS; } try { if (args.size() >= 2) { final String server = args.get(1).toLowerCase(); - if (!ArgumentChecker.checkServer(server)) { + if (ArgumentChecker.checkServer(server)) { Message.SERVER_INVALID_ENTRY.send(sender); - return; + return CommandResult.INVALID_ARGS; } if (args.size() == 2) { user.unsetPermission(node, server); Message.UNSETPERMISSION_SERVER_SUCCESS.send(sender, node, user.getName(), server); + LogEntryBuilder.get().actor(sender).acted(user) + .action("unset " + node + " " + server) + .submit(plugin); } else { final String world = args.get(2).toLowerCase(); user.unsetPermission(node, server, world); Message.UNSETPERMISSION_SERVER_WORLD_SUCCESS.send(sender, node, user.getName(), server, world); + LogEntryBuilder.get().actor(sender).acted(user) + .action("unset " + node + " " + server + " " + world) + .submit(plugin); } } else { user.unsetPermission(node); Message.UNSETPERMISSION_SUCCESS.send(sender, node, user.getName()); + LogEntryBuilder.get().actor(sender).acted(user) + .action("unset " + node) + .submit(plugin); } - saveUser(user, sender, plugin); + save(user, sender, plugin); + return CommandResult.SUCCESS; } catch (ObjectLacksException e) { Message.DOES_NOT_HAVEPERMISSION.send(sender, user.getName()); + return CommandResult.STATE_ERROR; } } } diff --git a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserUnsetTempPermission.java b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserUnsetTempPermission.java index 7dbdd2b08..2e5bc4ff1 100644 --- a/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserUnsetTempPermission.java +++ b/common/src/main/java/me/lucko/luckperms/commands/user/subcommands/UserUnsetTempPermission.java @@ -23,15 +23,17 @@ package me.lucko.luckperms.commands.user.subcommands; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.commands.CommandResult; import me.lucko.luckperms.commands.Predicate; import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.commands.SubCommand; import me.lucko.luckperms.constants.Message; +import me.lucko.luckperms.constants.Patterns; import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.data.LogEntryBuilder; import me.lucko.luckperms.exceptions.ObjectLacksException; import me.lucko.luckperms.users.User; import me.lucko.luckperms.utils.ArgumentChecker; -import me.lucko.luckperms.utils.Patterns; import java.util.List; @@ -43,44 +45,55 @@ public class UserUnsetTempPermission extends SubCommand { } @Override - public void execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { + public CommandResult execute(LuckPermsPlugin plugin, Sender sender, User user, List args, String label) { String node = args.get(0); - if (!ArgumentChecker.checkNode(node)) { + if (ArgumentChecker.checkNode(node)) { sendUsage(sender, label); - return; + return CommandResult.INVALID_ARGS; } if (Patterns.GROUP_MATCH.matcher(node).matches()) { Message.USER_USE_REMOVEGROUP.send(sender); - return; + return CommandResult.INVALID_ARGS; } try { if (args.size() >= 2) { final String server = args.get(1).toLowerCase(); - if (!ArgumentChecker.checkServer(server)) { + if (ArgumentChecker.checkServer(server)) { Message.SERVER_INVALID_ENTRY.send(sender); - return; + return CommandResult.INVALID_ARGS; } if (args.size() == 2) { user.unsetPermission(node, server, true); Message.UNSET_TEMP_PERMISSION_SERVER_SUCCESS.send(sender, node, user.getName(), server); + LogEntryBuilder.get().actor(sender).acted(user) + .action("unsettemp " + node + " " + server) + .submit(plugin); } else { final String world = args.get(2).toLowerCase(); user.unsetPermission(node, server, world, true); Message.UNSET_TEMP_PERMISSION_SERVER_WORLD_SUCCESS.send(sender, node, user.getName(), server, world); + LogEntryBuilder.get().actor(sender).acted(user) + .action("unsettemp " + node + " " + server + " " + world) + .submit(plugin); } } else { user.unsetPermission(node, true); Message.UNSET_TEMP_PERMISSION_SUCCESS.send(sender, node, user.getName()); + LogEntryBuilder.get().actor(sender).acted(user) + .action("unsettemp " + node) + .submit(plugin); } - saveUser(user, sender, plugin); + save(user, sender, plugin); + return CommandResult.SUCCESS; } catch (ObjectLacksException e) { Message.DOES_NOT_HAVE_TEMP_PERMISSION.send(sender, user.getName()); + return CommandResult.STATE_ERROR; } } } diff --git a/common/src/main/java/me/lucko/luckperms/constants/Constants.java b/common/src/main/java/me/lucko/luckperms/constants/Constants.java new file mode 100644 index 000000000..4e38f4f42 --- /dev/null +++ b/common/src/main/java/me/lucko/luckperms/constants/Constants.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2016 Lucko (Luck) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.luckperms.constants; + +import lombok.Getter; +import lombok.experimental.UtilityClass; + +import java.util.UUID; + +@UtilityClass +public class Constants { + + @Getter + private static final UUID consoleUUID = UUID.fromString("00000000-0000-0000-0000-000000000000"); + + @Getter + private static final String consoleName = "Console"; + + @Getter + private static final UUID importerUUID = UUID.fromString("11111111-1111-1111-1111-111111111111"); + + @Getter + private static final String importerName = "Import"; + + @Getter + private static final String logFormat = "&8(&e%s&8) [&a%s&8] (&b%s&8) &7--> &f%s"; + +} diff --git a/common/src/main/java/me/lucko/luckperms/constants/Message.java b/common/src/main/java/me/lucko/luckperms/constants/Message.java index d62245a96..e5859f388 100644 --- a/common/src/main/java/me/lucko/luckperms/constants/Message.java +++ b/common/src/main/java/me/lucko/luckperms/constants/Message.java @@ -38,6 +38,7 @@ public enum Message { PLAYER_ONLINE("&aOnline", false), PLAYER_OFFLINE("&cOffline", false), LOADING_ERROR("Permissions data could not be loaded. Please contact an administrator.", true), + LOG("&3LOG &3&l> %s", true), COMMAND_NOT_RECOGNISED("Command not recognised.", true), COMMAND_NO_PERMISSION("You do not have permission to use this command!", true), @@ -57,6 +58,8 @@ public enum Message { USER_SAVE_SUCCESS("&7(User data was saved to the datastore)", true), USER_SAVE_ERROR("There was an error whilst saving the user.", true), USER_ATTEMPTING_LOOKUP("&7(Attempting UUID lookup, since you specified a username)", true), + USER_NEVER_JOINED("&6(&e&lWARNING: &cA user with that UUID has not joined the server before.&6)", true), + USER_CREATE_FAIL("There was an error whilst creating a new user.", true), GROUP_NOT_FOUND("&eGroup could not be found.", true), GROUP_SAVE_SUCCESS("&7(Group data was saved to the datastore)", true), @@ -124,7 +127,9 @@ public enum Message { PREFIX + "&eSync Interval: &6%s minutes" + "\n" + PREFIX + "&eInclude Global Perms: &6%s" + "\n" + PREFIX + "&eOnline Mode: &6%s" + "\n" + - PREFIX + "&eApply Wildcards: &6%s", + PREFIX + "&eApply Wildcards: &6%s" + "\n" + + PREFIX + "&eApply Regex: &6%s" + "\n" + + PREFIX + "&eApply Shorthand: &6%s", false ), DEBUG( @@ -242,7 +247,45 @@ public enum Message { TRACK_INSERT_SUCCESS("&aGroup &b%s&a was successfully inserted into track &b%s&a at position &b%s&a.", true), TRACK_INSERT_ERROR_NUMBER("Expected number but instead received: %s", true), TRACK_INSERT_ERROR_INVALID_POS("Unable to insert at position %s. Index out of bounds.", true), - TRACK_REMOVE_SUCCESS("&aGroup &b%s&a was successfully removed from track &b%s&a.", true); + TRACK_REMOVE_SUCCESS("&aGroup &b%s&a was successfully removed from track &b%s&a.", true), + + LOG_LOAD_ERROR("The log could not be loaded.", true), + LOG_INVALID_PAGE("Invalid page number.", true), + LOG_INVALID_PAGE_RANGE("Invalid page number. Please enter a value between 1 and %s.", true), + LOG_NO_ENTRIES("&eNo log entries to show.", true), + LOG_ENTRY("&e#%s -> &8(&7%s ago&8) %s", true), + + LOG_NOTIFY_TOGGLE_ON("&aEnabled&b logging output.", true), + LOG_NOTIFY_TOGGLE_OFF("&cDisabled&b logging output.", true), + LOG_NOTIFY_ALREADY_ON("You are already receiving notifications.", true), + LOG_NOTIFY_ALREADY_OFF("You aren't currently receiving notifications.", true), + LOG_NOTIFY_UNKNOWN("State unknown. Expecting \"on\" or \"off\".", true), + + LOG_SEARCH_HEADER("&aShowing recent actions for query &b%s &a(page &f%s&a of &f%s&a)", true), + + LOG_RECENT_HEADER("&aShowing recent actions (page &f%s&a of &f%s&a)", true), + LOG_RECENT_BY_HEADER("&aShowing recent actions by &b%s &a(page &f%s&a of &f%s&a)", true), + + LOG_HISTORY_USER_HEADER("&aShowing history for user &b%s &a(page &f%s&a of &f%s&a)", true), + LOG_HISTORY_GROUP_HEADER("&aShowing history for group &b%s &a(page &f%s&a of &f%s&a)", true), + LOG_HISTORY_TRACK_HEADER("&aShowing history for track &b%s &a(page &f%s&a of &f%s&a)", true), + + IMPORT_PROGRESS("&e(Import) &d-> &6%s% complete &7- &e%s&6/&e%s &6operations complete with &c%s &6errors.", true), + IMPORT_PROGRESS_SIN("&e(Import) &d-> &6%s% complete &7- &e%s&6/&e%s &6operations complete with &c%s &6error.", true), + IMPORT_START("&e(Import) &d-> &6Starting import process.", true), + + IMPORT_END_COMPLETE("&e(Import) &a&lCOMPLETED &7- took &e%s &7seconds - &7No errors.", true), + IMPORT_END_COMPLETE_ERR("&e(Import) &a&lCOMPLETED &7- took &e%s &7seconds - &c%s errors.", true), + IMPORT_END_COMPLETE_ERR_SIN("&e(Import) &a&lCOMPLETED &7- took &e%s &7seconds - &c%s error.", true), + IMPORT_END_ERROR_HEADER( + PREFIX + "&e(Import) &7-----> &6Showing Error #&e%s &7<-----" + "\n" + + PREFIX + "&e(Import) &6Whilst executing: &fCommand #%s" + "\n" + + PREFIX + "&e(Import) &6Output:s", + false + ), + + IMPORT_END_ERROR_CONTENT("&e(Import) &7-> &c%s", true), + IMPORT_END_ERROR_FOOTER("&e(Import) &7<---------------------------->", true); private String message; private boolean showPrefix; diff --git a/common/src/main/java/me/lucko/luckperms/utils/Patterns.java b/common/src/main/java/me/lucko/luckperms/constants/Patterns.java similarity index 94% rename from common/src/main/java/me/lucko/luckperms/utils/Patterns.java rename to common/src/main/java/me/lucko/luckperms/constants/Patterns.java index df9ea7447..92bb4e911 100644 --- a/common/src/main/java/me/lucko/luckperms/utils/Patterns.java +++ b/common/src/main/java/me/lucko/luckperms/constants/Patterns.java @@ -20,7 +20,7 @@ * SOFTWARE. */ -package me.lucko.luckperms.utils; +package me.lucko.luckperms.constants; import lombok.experimental.UtilityClass; @@ -43,6 +43,7 @@ public class Patterns { public static final Pattern NON_ALPHA_NUMERIC = Pattern.compile("[^A-Za-z0-9]"); public static final Pattern NON_USERNAME = Pattern.compile("[^A-Za-z0-9_]"); public static final Pattern SHORTHAND_NODE = Pattern.compile("\\.\\([^.]+\\)"); + public static final Pattern STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + String.valueOf('§') + "[0-9A-FK-OR]"); public static Pattern compile(String regex) throws PatternSyntaxException { if (!CACHE.containsKey(regex)) { diff --git a/common/src/main/java/me/lucko/luckperms/constants/Permission.java b/common/src/main/java/me/lucko/luckperms/constants/Permission.java index a8506b2b9..24619e211 100644 --- a/common/src/main/java/me/lucko/luckperms/constants/Permission.java +++ b/common/src/main/java/me/lucko/luckperms/constants/Permission.java @@ -80,17 +80,29 @@ public enum Permission { TRACK_APPEND("append", "track"), TRACK_INSERT("insert", "track"), TRACK_REMOVE("remove", "track"), - TRACK_CLEAR("clear", "track"); + TRACK_CLEAR("clear", "track"), + + LOG_RECENT("recent", "log"), + LOG_USER_HISTORY("userhistory", "log"), + LOG_GROUP_HISTORY("grouphistory", "log"), + LOG_TRACK_HISTORY("trackhistory", "log"), + LOG_SEARCH("search", "log"), + LOG_NOTIFY("notify", "log"), + LOG_EXPORT("export", "log"); private String node; private String group; - public boolean isAuthorized(Sender sender) { + public String getNode() { if (group != null) { - return sender.hasPermission("luckperms." + group + "." + node); + return "luckperms." + group + "." + node; } - return sender.hasPermission("luckperms." + node); + return "luckperms." + node; + } + + public boolean isAuthorized(Sender sender) { + return sender.hasPermission(this); } } diff --git a/common/src/main/java/me/lucko/luckperms/utils/LPConfiguration.java b/common/src/main/java/me/lucko/luckperms/core/LPConfiguration.java similarity index 96% rename from common/src/main/java/me/lucko/luckperms/utils/LPConfiguration.java rename to common/src/main/java/me/lucko/luckperms/core/LPConfiguration.java index 77d954e66..5ab4a5868 100644 --- a/common/src/main/java/me/lucko/luckperms/utils/LPConfiguration.java +++ b/common/src/main/java/me/lucko/luckperms/core/LPConfiguration.java @@ -20,12 +20,13 @@ * SOFTWARE. */ -package me.lucko.luckperms.utils; +package me.lucko.luckperms.core; import lombok.AccessLevel; import lombok.Getter; import me.lucko.luckperms.LuckPermsPlugin; -import me.lucko.luckperms.data.MySQLConfiguration; +import me.lucko.luckperms.constants.Patterns; +import me.lucko.luckperms.storage.MySQLConfiguration; public abstract class LPConfiguration { diff --git a/common/src/main/java/me/lucko/luckperms/utils/PermissionHolder.java b/common/src/main/java/me/lucko/luckperms/core/PermissionHolder.java similarity index 99% rename from common/src/main/java/me/lucko/luckperms/utils/PermissionHolder.java rename to common/src/main/java/me/lucko/luckperms/core/PermissionHolder.java index 8c3c309bb..a66e9b740 100644 --- a/common/src/main/java/me/lucko/luckperms/utils/PermissionHolder.java +++ b/common/src/main/java/me/lucko/luckperms/core/PermissionHolder.java @@ -20,15 +20,17 @@ * SOFTWARE. */ -package me.lucko.luckperms.utils; +package me.lucko.luckperms.core; import lombok.AccessLevel; import lombok.Getter; import lombok.RequiredArgsConstructor; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.constants.Patterns; import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import me.lucko.luckperms.exceptions.ObjectLacksException; import me.lucko.luckperms.groups.Group; +import me.lucko.luckperms.utils.DateUtil; import java.util.*; import java.util.concurrent.ConcurrentHashMap; @@ -622,7 +624,7 @@ public abstract class PermissionHolder { String groupName = Patterns.DOT.split(groupNode.getKey(), 2)[1]; if (!excludedGroups.contains(groupName)) { - Group group = plugin.getGroupManager().getGroup(groupName); + Group group = plugin.getGroupManager().get(groupName); if (group != null) { perms.putAll(group.getLocalPermissions(server, excludedGroups)); } else { @@ -647,7 +649,7 @@ public abstract class PermissionHolder { String groupName = Patterns.DOT.split(rawNode, 2)[1]; if (!excludedGroups.contains(groupName)) { - Group group = plugin.getGroupManager().getGroup(groupName); + Group group = plugin.getGroupManager().get(groupName); if (group != null) { perms.putAll(group.getLocalPermissions(server, excludedGroups)); } else { diff --git a/common/src/main/java/me/lucko/luckperms/utils/UuidCache.java b/common/src/main/java/me/lucko/luckperms/core/UuidCache.java similarity index 77% rename from common/src/main/java/me/lucko/luckperms/utils/UuidCache.java rename to common/src/main/java/me/lucko/luckperms/core/UuidCache.java index 13c01a890..94c044bb1 100644 --- a/common/src/main/java/me/lucko/luckperms/utils/UuidCache.java +++ b/common/src/main/java/me/lucko/luckperms/core/UuidCache.java @@ -20,7 +20,7 @@ * SOFTWARE. */ -package me.lucko.luckperms.utils; +package me.lucko.luckperms.core; import lombok.Getter; @@ -30,13 +30,7 @@ import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; /** - * This UuidCache is a means of allowing users to have the same internal UUID across a network of offline mode servers - * or mixed offline mode and online mode servers. Platforms running in offline mode generate a random UUID for a user when - * they first join the server, but this UUID will then not be consistent across the network. LuckPerms will instead check - * the datastore cache, to get a UUID for a user that is consistent across an entire network. - * - * If you want to get a user object from the datastore using the api on a server in offline mode, you will need to use this cache, - * OR use Datastore#getUUID, for users that are not online. + * @see me.lucko.luckperms.api.UuidCache */ public class UuidCache { diff --git a/common/src/main/java/me/lucko/luckperms/data/Importer.java b/common/src/main/java/me/lucko/luckperms/data/Importer.java new file mode 100644 index 000000000..4d6d22d79 --- /dev/null +++ b/common/src/main/java/me/lucko/luckperms/data/Importer.java @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2016 Lucko (Luck) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.luckperms.data; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.Setter; +import me.lucko.luckperms.commands.CommandManager; +import me.lucko.luckperms.commands.CommandResult; +import me.lucko.luckperms.commands.Sender; +import me.lucko.luckperms.commands.Util; +import me.lucko.luckperms.constants.Constants; +import me.lucko.luckperms.constants.Message; +import me.lucko.luckperms.constants.Patterns; +import me.lucko.luckperms.constants.Permission; + +import java.util.*; +import java.util.stream.Collectors; + +/** + * Executes a list of commands sequentially in a single thread. + */ +@RequiredArgsConstructor +public class Importer { // TODO: implement this + + @Getter + private boolean running = false; + + private final CommandManager commandManager; + + private Sender executor = null; + private List commands = null; + private Map cmdResult = null; + + private long lastMsg = 0; + private int executing = -1; + + public synchronized void start(Sender executor, List commands) { + if (isRunning()) { + throw new IllegalStateException("Import already running."); + } + + running = true; + this.executor = executor; + this.commands = commands.stream() + .map(s -> s.startsWith("/") ? s.substring(1) : s) + .map(s -> s.startsWith("perms ") ? s.substring(5) : s) + .collect(Collectors.toList()); + + cmdResult = new HashMap<>(); + + run(); + } + + private void cleanup() { + executor = null; + commands = null; + cmdResult = null; + lastMsg = 0; + executing = -1; + running = false; + } + + public void run() { + long startTime = System.currentTimeMillis(); + Message.IMPORT_START.send(executor); + final Sender fake = new FakeSender(this); + + int index = 0; + for (String command : commands) { + if (lastMsg < (System.currentTimeMillis() / 1000) - 5) { + lastMsg = System.currentTimeMillis() / 1000; + + sendProgress(index); + } + + executing = index; + try { + CommandResult result = commandManager.onCommand(fake, "perms", Arrays.asList(Patterns.SPACE.split(command))); + getResult(index).setResult(result); + + } catch (Exception e) { + getResult(index).setResult(CommandResult.FAILURE); + e.printStackTrace(); + } + index++; + } + + long endTime = System.currentTimeMillis(); + double seconds = (endTime - startTime) / 1000.0; + + int errors = 0; + for (Map.Entry e : cmdResult.entrySet()) { + if (e.getValue().getResult() != null && !e.getValue().getResult().booleanValue()) { + errors++; + } + } + + if (errors == 0) { + Message.IMPORT_END_COMPLETE.send(executor, seconds); + } else if (errors == 1) { + Message.IMPORT_END_COMPLETE_ERR_SIN.send(executor, seconds, errors); + } else { + Message.IMPORT_END_COMPLETE_ERR.send(executor, seconds, errors); + } + + int errIndex = 1; + for (Map.Entry e : cmdResult.entrySet()) { + if (e.getValue().getResult() != null && !e.getValue().getResult().booleanValue()) { + Message.IMPORT_END_ERROR_HEADER.send(executor, errIndex, e.getKey()); + for (String s : e.getValue().getOutput()) { + Message.IMPORT_END_ERROR_CONTENT.send(executor, s); + } + Message.IMPORT_END_ERROR_FOOTER.send(executor); + errIndex++; + } + } + + cleanup(); + } + + private void sendProgress(int executing) { + int percent = (executing / commands.size()) * 100; + int errors = 0; + + for (Map.Entry e : cmdResult.entrySet()) { + if (e.getValue().getResult() != null && !e.getValue().getResult().booleanValue()) { + errors++; + } + } + + if (errors == 1) { + Message.IMPORT_PROGRESS_SIN.send(executor, percent, executing, commands.size(), errors); + } else { + Message.IMPORT_PROGRESS.send(executor, percent, executing, commands.size(), errors); + } + } + + private Result getResult(int executing) { + if (!cmdResult.containsKey(executing)) { + cmdResult.put(executing, new Result()); + } + + return cmdResult.get(executing); + } + + private void logMessage(String msg) { + getResult(executing).getOutput().add(Util.stripColor(msg)); + } + + private static class FakeSender implements Sender { + private final Importer instance; + + public FakeSender(Importer instance) { + this.instance = instance; + } + + @Override + public String getName() { + return Constants.getImporterName(); + } + + @Override + public UUID getUuid() { + return Constants.getImporterUUID(); + } + + @Override + public void sendMessage(String s) { + instance.logMessage(s); + } + + @Override + public boolean hasPermission(Permission permission) { + return true; + } + } + + private static class Result { + + @Getter + private final List output = new ArrayList<>(); + + @Getter + @Setter + private CommandResult result = CommandResult.FAILURE; + } + +} diff --git a/common/src/main/java/me/lucko/luckperms/data/Log.java b/common/src/main/java/me/lucko/luckperms/data/Log.java new file mode 100644 index 000000000..7126eae13 --- /dev/null +++ b/common/src/main/java/me/lucko/luckperms/data/Log.java @@ -0,0 +1,194 @@ +/* + * Copyright (c) 2016 Lucko (Luck) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.luckperms.data; + +import com.google.common.collect.ImmutableSortedSet; +import lombok.Getter; +import me.lucko.luckperms.api.LogEntry; + +import java.util.*; +import java.util.stream.Collectors; + +public class Log { + public static Builder builder() { + return new Builder(); + } + + private static final int PAGE_ENTRIES = 5; + + @Getter + private final SortedSet content; + + public Log(SortedSet content) { + this.content = ImmutableSortedSet.copyOf(content); + } + + public SortedSet getRecent() { + return content; + } + + public SortedMap getRecent(int pageNo) { + return getPage(content, pageNo, PAGE_ENTRIES); + } + + public int getRecentMaxPages() { + return getMaxPages(content.size(), PAGE_ENTRIES); + } + + public SortedSet getRecent(UUID actor) { + return content.stream() + .filter(e -> e.getActor().equals(actor)) + .collect(Collectors.toCollection(TreeSet::new)); + } + + public SortedMap getRecent(int pageNo, UUID actor) { + return getPage(getRecent(actor), pageNo, PAGE_ENTRIES); + } + + public int getRecentMaxPages(UUID actor) { + return getMaxPages(content.stream() + .filter(e -> e.getActor().equals(actor)) + .count(), PAGE_ENTRIES); + } + + public SortedSet getUserHistory(UUID uuid) { + return content.stream() + .filter(e -> e.getType() == 'U') + .filter(e -> e.getActed().equals(uuid)) + .collect(Collectors.toCollection(TreeSet::new)); + } + + public SortedMap getUserHistory(int pageNo, UUID uuid) { + return getPage(getUserHistory(uuid), pageNo, PAGE_ENTRIES); + } + + public int getUserHistoryMaxPages(UUID uuid) { + return getMaxPages(content.stream() + .filter(e -> e.getType() == 'U') + .filter(e -> e.getActed().equals(uuid)) + .count(), PAGE_ENTRIES); + } + + public SortedSet getGroupHistory(String name) { + return content.stream() + .filter(e -> e.getType() == 'G') + .filter(e -> e.getActedName().equals(name)) + .collect(Collectors.toCollection(TreeSet::new)); + } + + public SortedMap getGroupHistory(int pageNo, String name) { + return getPage(getGroupHistory(name), pageNo, PAGE_ENTRIES); + } + + public int getGroupHistoryMaxPages(String name) { + return getMaxPages(content.stream() + .filter(e -> e.getType() == 'G') + .filter(e -> e.getActedName().equals(name)) + .count(), PAGE_ENTRIES); + } + + public SortedSet getTrackHistory(String name) { + return content.stream() + .filter(e -> e.getType() == 'T') + .filter(e -> e.getActedName().equals(name)) + .collect(Collectors.toCollection(TreeSet::new)); + } + + public SortedMap getTrackHistory(int pageNo, String name) { + return getPage(getTrackHistory(name), pageNo, PAGE_ENTRIES); + } + + public int getTrackHistoryMaxPages(String name) { + return getMaxPages(content.stream() + .filter(e -> e.getType() == 'T') + .filter(e -> e.getActedName().equals(name)) + .count(), PAGE_ENTRIES); + } + + public SortedSet getSearch(String query) { + return content.stream() + .filter(e -> e.matchesSearch(query)) + .collect(Collectors.toCollection(TreeSet::new)); + } + + public SortedMap getSearch(int pageNo, String query) { + return getPage(getSearch(query), pageNo, PAGE_ENTRIES); + } + + public int getSearchMaxPages(String query) { + return getMaxPages(content.stream() + .filter(e -> e.matchesSearch(query)) + .count(), PAGE_ENTRIES); + } + + private static SortedMap getPage(Set set, int pageNo, int entries) { + if (pageNo < 1) { + throw new IllegalArgumentException("pageNo cannot be less than 1: " + pageNo); + } + + int minimumEntries = ((pageNo * 5) - entries) + 1; + if (set.size() < minimumEntries) { + throw new IllegalStateException("Log does not contain that many entries. " + + "Requested: " + minimumEntries + ", Log Count: " + set.size()); + } + + final SortedMap out = new TreeMap<>(); + + final int max = minimumEntries + entries - 1; + int index = 0; + for (LogEntry e : set) { + index++; + if (index >= minimumEntries) { + out.put(index, e); + } + if (index == max) { + break; + } + } + + return out; + } + + private static int getMaxPages(int size, int entries) { + return (int) Math.ceil((double) size / entries); + } + + private static int getMaxPages(long size, int entries) { + return (int) Math.ceil((double) size / entries); + } + + @SuppressWarnings("WeakerAccess") + public static class Builder { + private final SortedSet content = new TreeSet<>(); + + public Builder add(LogEntry e) { + content.add(e); + return this; + } + + public Log build() { + return new Log(content); + } + } + +} diff --git a/common/src/main/java/me/lucko/luckperms/data/LogEntryBuilder.java b/common/src/main/java/me/lucko/luckperms/data/LogEntryBuilder.java new file mode 100644 index 000000000..1d92c027e --- /dev/null +++ b/common/src/main/java/me/lucko/luckperms/data/LogEntryBuilder.java @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2016 Lucko (Luck) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.luckperms.data; + +import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.api.LogEntry; +import me.lucko.luckperms.api.data.Callback; +import me.lucko.luckperms.commands.Sender; +import me.lucko.luckperms.constants.Message; +import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.core.PermissionHolder; +import me.lucko.luckperms.groups.Group; +import me.lucko.luckperms.tracks.Track; +import me.lucko.luckperms.users.User; + +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + +public class LogEntryBuilder { + private long timestamp = 0L; + private UUID actor = null; + private String actorName = null; + private char type = Character.MIN_VALUE; + private UUID acted = null; + private String actedName = null; + private String action = null; + + public static LogEntryBuilder get() { + return new LogEntryBuilder(); + } + + public LogEntryBuilder timestamp(long timestamp) { + this.timestamp = timestamp; + return this; + } + + public LogEntryBuilder actor(UUID actor) { + this.actor = actor; + return this; + } + + public LogEntryBuilder actorName(String actorName) { + this.actorName = actorName; + return this; + } + + public LogEntryBuilder actor(Sender actor) { + this.actorName = actor.getName(); + this.actor = actor.getUuid(); + return this; + } + + public LogEntryBuilder type(char type) { + this.type = type; + return this; + } + + public LogEntryBuilder type(String type) { + this.type = type.toCharArray()[0]; + return this; + } + + public LogEntryBuilder type(Object object) { + if (object instanceof User) { + this.type = 'U'; + } else if (object instanceof Group) { + this.type = 'G'; + } else if (object instanceof Track) { + this.type = 'T'; + } else { + throw new IllegalArgumentException(); + } + return this; + } + + public LogEntryBuilder acted(UUID acted) { + this.acted = acted; + return this; + } + + public LogEntryBuilder actedName(String actedName) { + this.actedName = actedName; + return this; + } + + public LogEntryBuilder acted(PermissionHolder acted) { + if (acted instanceof User) { + this.actedName = ((User) acted).getName(); + this.acted = ((User) acted).getUuid(); + this.type = 'U'; + } else if (acted instanceof Group) { + this.actedName = ((Group) acted).getName(); + this.type = 'G'; + } + return this; + } + + public LogEntryBuilder acted(Track track) { + this.actedName = track.getName(); + this.type = 'T'; + return this; + } + + public LogEntryBuilder action(String action) { + this.action = action; + return this; + } + + private Set getEmpty() { + Set s = new HashSet<>(); + if (actor == null) { + s.add("actor"); + } + if (actorName == null) { + s.add("actorname"); + } + if (type == Character.MIN_VALUE) { + s.add("type"); + } + if (actedName == null) { + s.add("actedname"); + } + if (action == null) { + s.add("action"); + } + return s; + } + + public void submit(LuckPermsPlugin plugin) { + final LogEntry entry = build(); + plugin.getDatastore().logAction(entry, Callback.empty()); + + final String msg = entry.getFormatted(); + + plugin.getSenders().stream() + .filter(Permission.LOG_NOTIFY::isAuthorized) + .filter(s -> !plugin.getIgnoringLogs().contains(s.getUuid())) + .forEach(s -> Message.LOG.send(s, msg)); + } + + public LogEntry build() { + if (timestamp == 0L) { + timestamp = System.currentTimeMillis() / 1000; + } + + if (!getEmpty().isEmpty()) { + throw new IllegalStateException("Missing values: " + getEmpty().toString()); + } + + return new LogEntry(timestamp, actor, actorName, type, acted, actedName, action); + } +} diff --git a/common/src/main/java/me/lucko/luckperms/groups/Group.java b/common/src/main/java/me/lucko/luckperms/groups/Group.java index aa47a6597..d2cfc1e03 100644 --- a/common/src/main/java/me/lucko/luckperms/groups/Group.java +++ b/common/src/main/java/me/lucko/luckperms/groups/Group.java @@ -26,10 +26,11 @@ import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.constants.Patterns; +import me.lucko.luckperms.core.PermissionHolder; import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import me.lucko.luckperms.exceptions.ObjectLacksException; -import me.lucko.luckperms.utils.Patterns; -import me.lucko.luckperms.utils.PermissionHolder; +import me.lucko.luckperms.utils.Identifiable; import java.util.List; import java.util.Map; @@ -37,7 +38,7 @@ import java.util.stream.Collectors; @ToString(of = {"name"}) @EqualsAndHashCode(of = {"name"}, callSuper = false) -public class Group extends PermissionHolder { +public class Group extends PermissionHolder implements Identifiable { /** * The name of the group @@ -56,7 +57,7 @@ public class Group extends PermissionHolder { * @return true if the user is a member of the group */ public boolean inheritsGroup(Group group) { - return inheritsGroup(group, "global"); + return group.getName().equalsIgnoreCase(this.getName()) || inheritsGroup(group, "global"); } /** @@ -66,7 +67,7 @@ public class Group extends PermissionHolder { * @return true if the group inherits the group */ public boolean inheritsGroup(Group group, String server) { - return hasPermission("group." + group.getName(), true, server); + return group.getName().equalsIgnoreCase(this.getName()) || hasPermission("group." + group.getName(), true, server); } /** @@ -77,7 +78,7 @@ public class Group extends PermissionHolder { * @return true if the group inherits the group */ public boolean inheritsGroup(Group group, String server, String world) { - return hasPermission("group." + group.getName(), true, server, world); + return group.getName().equalsIgnoreCase(this.getName()) || hasPermission("group." + group.getName(), true, server, world); } /** @@ -96,6 +97,10 @@ public class Group extends PermissionHolder { * @throws ObjectAlreadyHasException if the group already inherits the group on that server */ public void setInheritGroup(Group group, String server) throws ObjectAlreadyHasException { + if (group.getName().equalsIgnoreCase(this.getName())) { + throw new ObjectAlreadyHasException(); + } + if (server == null) { server = "global"; } @@ -111,6 +116,10 @@ public class Group extends PermissionHolder { * @throws ObjectAlreadyHasException if the group already inherits the group on that server */ public void setInheritGroup(Group group, String server, String world) throws ObjectAlreadyHasException { + if (group.getName().equalsIgnoreCase(this.getName())) { + throw new ObjectAlreadyHasException(); + } + if (server == null) { server = "global"; } @@ -125,6 +134,10 @@ public class Group extends PermissionHolder { * @throws ObjectAlreadyHasException if the group already inherits the group on that server */ public void setInheritGroup(Group group, long expireAt) throws ObjectAlreadyHasException { + if (group.getName().equalsIgnoreCase(this.getName())) { + throw new ObjectAlreadyHasException(); + } + setPermission("group." + group.getName(), true, expireAt); } @@ -136,6 +149,10 @@ public class Group extends PermissionHolder { * @throws ObjectAlreadyHasException if the group already inherits the group on that server */ public void setInheritGroup(Group group, String server, long expireAt) throws ObjectAlreadyHasException { + if (group.getName().equalsIgnoreCase(this.getName())) { + throw new ObjectAlreadyHasException(); + } + if (server == null) { server = "global"; } @@ -152,6 +169,10 @@ public class Group extends PermissionHolder { * @throws ObjectAlreadyHasException if the group already inherits the group on that server */ public void setInheritGroup(Group group, String server, String world, long expireAt) throws ObjectAlreadyHasException { + if (group.getName().equalsIgnoreCase(this.getName())) { + throw new ObjectAlreadyHasException(); + } + if (server == null) { server = "global"; } @@ -288,4 +309,9 @@ public class Group extends PermissionHolder { .map(s -> Patterns.DOT.split(s, 2)[1]) .collect(Collectors.toList()); } + + @Override + public String getId() { + return name; + } } diff --git a/common/src/main/java/me/lucko/luckperms/groups/GroupManager.java b/common/src/main/java/me/lucko/luckperms/groups/GroupManager.java index 50a25c2a0..811fb01d5 100644 --- a/common/src/main/java/me/lucko/luckperms/groups/GroupManager.java +++ b/common/src/main/java/me/lucko/luckperms/groups/GroupManager.java @@ -22,77 +22,17 @@ package me.lucko.luckperms.groups; -import lombok.Getter; import lombok.RequiredArgsConstructor; import me.lucko.luckperms.LuckPermsPlugin; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; +import me.lucko.luckperms.utils.AbstractManager; @RequiredArgsConstructor -public class GroupManager { +public class GroupManager extends AbstractManager { private final LuckPermsPlugin plugin; - /** - * A {@link Map} containing all loaded groups - */ - @Getter - private final Map groups = new ConcurrentHashMap<>(); - - /** - * Get a group object by name - * @param name The name to search by - * @return a {@link Group} object if the group is loaded, returns null if the group is not loaded - */ - public Group getGroup(String name) { - return groups.get(name); - } - - /** - * Add a group to the loaded groups map - * @param group The group to add - */ - public void setGroup(Group group) { - groups.put(group.getName(), group); - } - - /** - * Updates (or sets if the group wasn't already loaded) a group in the groups map - * @param group The group to update or set - */ - public void updateOrSetGroup(Group group) { - if (!isLoaded(group.getName())) { - // The group isn't already loaded - groups.put(group.getName(), group); - } else { - groups.get(group.getName()).setNodes(group.getNodes()); - } - } - - /** - * Check to see if a group is loaded or not - * @param name The name of the group - * @return true if the group is loaded - */ - public boolean isLoaded(String name) { - return groups.containsKey(name); - } - - /** - * Removes and unloads the group from the plugins internal storage - * @param group The group to unload - */ - public void unloadGroup(Group group) { - if (group != null) { - groups.remove(group.getName()); - } - } - - /** - * Unloads all groups from the manager - */ - public void unloadAll() { - groups.clear(); + @Override + protected void copy(Group from, Group to) { + to.setNodes(from.getNodes()); } /** @@ -100,7 +40,8 @@ public class GroupManager { * @param name The name of the group * @return a new {@link Group} object */ - public Group makeGroup(String name) { + @Override + public Group make(String name) { return new Group(name, plugin); } } \ No newline at end of file diff --git a/common/src/main/java/me/lucko/luckperms/runnables/UpdateTask.java b/common/src/main/java/me/lucko/luckperms/runnables/UpdateTask.java index ad43a8fee..4b9247596 100644 --- a/common/src/main/java/me/lucko/luckperms/runnables/UpdateTask.java +++ b/common/src/main/java/me/lucko/luckperms/runnables/UpdateTask.java @@ -31,8 +31,6 @@ public class UpdateTask implements Runnable { @Override public void run() { - plugin.getLog().info("Running update task."); - // Reload all of the groups plugin.getDatastore().loadAllGroups(); String defaultGroup = plugin.getConfiguration().getDefaultGroupName(); diff --git a/common/src/main/java/me/lucko/luckperms/data/Datastore.java b/common/src/main/java/me/lucko/luckperms/storage/Datastore.java similarity index 62% rename from common/src/main/java/me/lucko/luckperms/data/Datastore.java rename to common/src/main/java/me/lucko/luckperms/storage/Datastore.java index 2e4e70fbc..6730db013 100644 --- a/common/src/main/java/me/lucko/luckperms/data/Datastore.java +++ b/common/src/main/java/me/lucko/luckperms/storage/Datastore.java @@ -20,14 +20,16 @@ * SOFTWARE. */ -package me.lucko.luckperms.data; +package me.lucko.luckperms.storage; import lombok.AccessLevel; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.api.LogEntry; import me.lucko.luckperms.api.data.Callback; +import me.lucko.luckperms.data.Log; import me.lucko.luckperms.groups.Group; import me.lucko.luckperms.tracks.Track; import me.lucko.luckperms.users.User; @@ -61,15 +63,13 @@ public abstract class Datastore { plugin.doSync(r); } - private void runCallback(T t, Callback callback) { - doSync(() -> callback.onComplete(t)); - } - /* These methods are called immediately and in the same thread as they are called in. */ public abstract void init(); public abstract void shutdown(); + public abstract boolean logAction(LogEntry entry); + public abstract Log getLog(); public abstract boolean loadOrCreateUser(UUID uuid, String username); public abstract boolean loadUser(UUID uuid); public abstract boolean saveUser(User user); @@ -92,63 +92,122 @@ public abstract class Datastore { These methods will schedule the operation to run async. The callback will be ran when the task is complete. Callbacks are ran on the main Bukkit server thread (if applicable) */ + public void logAction(LogEntry entry, Callback callback) { + doAsync(() -> { + boolean result = logAction(entry); + doSync(() -> callback.onComplete(result)); + }); + } + + public void getLog(Callback callback) { + doAsync(() -> { + Log result = getLog(); + doSync(() -> callback.onComplete(result)); + }); + } + public void loadOrCreateUser(UUID uuid, String username, Callback callback) { - doAsync(() -> runCallback(loadOrCreateUser(uuid, username), callback)); + doAsync(() -> { + boolean result = loadOrCreateUser(uuid, username); + doSync(() -> callback.onComplete(result)); + }); } public void loadUser(UUID uuid, Callback callback) { - doAsync(() -> runCallback(loadUser(uuid), callback)); + doAsync(() -> { + boolean result = loadUser(uuid); + doSync(() -> callback.onComplete(result)); + }); } public void saveUser(User user, Callback callback) { - doAsync(() -> runCallback(saveUser(user), callback)); + doAsync(() -> { + boolean result = saveUser(user); + doSync(() -> callback.onComplete(result)); + }); } public void createAndLoadGroup(String name, Callback callback) { - doAsync(() -> runCallback(createAndLoadGroup(name), callback)); + doAsync(() -> { + boolean result = createAndLoadGroup(name); + doSync(() -> callback.onComplete(result)); + }); } public void loadGroup(String name, Callback callback) { - doAsync(() -> runCallback(loadGroup(name), callback)); + doAsync(() -> { + boolean result = loadGroup(name); + doSync(() -> callback.onComplete(result)); + }); } public void loadAllGroups(Callback callback) { - doAsync(() -> runCallback(loadAllGroups(), callback)); + doAsync(() -> { + boolean result = loadAllGroups(); + doSync(() -> callback.onComplete(result)); + }); } public void saveGroup(Group group, Callback callback) { - doAsync(() -> runCallback(saveGroup(group), callback)); + doAsync(() -> { + boolean result = saveGroup(group); + doSync(() -> callback.onComplete(result)); + }); } public void deleteGroup(Group group, Callback callback) { - doAsync(() -> runCallback(deleteGroup(group), callback)); + doAsync(() -> { + boolean result = deleteGroup(group); + doSync(() -> callback.onComplete(result)); + }); } public void createAndLoadTrack(String name, Callback callback) { - doAsync(() -> runCallback(createAndLoadTrack(name), callback)); + doAsync(() -> { + boolean result = createAndLoadTrack(name); + doSync(() -> callback.onComplete(result)); + }); } public void loadTrack(String name, Callback callback) { - doAsync(() -> runCallback(loadTrack(name), callback)); + doAsync(() -> { + boolean result = loadTrack(name); + doSync(() -> callback.onComplete(result)); + }); } public void loadAllTracks(Callback callback) { - doAsync(() -> runCallback(loadAllTracks(), callback)); + doAsync(() -> { + boolean result = loadAllTracks(); + doSync(() -> callback.onComplete(result)); + }); } public void saveTrack(Track track, Callback callback) { - doAsync(() -> runCallback(saveTrack(track), callback)); + doAsync(() -> { + boolean result = saveTrack(track); + doSync(() -> callback.onComplete(result)); + }); } public void deleteTrack(Track track, Callback callback) { - doAsync(() -> runCallback(deleteTrack(track), callback)); + doAsync(() -> { + boolean result = deleteTrack(track); + doSync(() -> callback.onComplete(result)); + }); } public void saveUUIDData(String username, UUID uuid, Callback callback) { - doAsync(() -> runCallback(saveUUIDData(username, uuid), callback)); + doAsync(() -> { + boolean result = saveUUIDData(username, uuid); + doSync(() -> callback.onComplete(result)); + }); } public void getUUID(String username, Callback callback) { - doAsync(() -> runCallback(getUUID(username), callback)); + doAsync(() -> { + UUID result = getUUID(username); + doSync(() -> callback.onComplete(result)); + }); } } diff --git a/common/src/main/java/me/lucko/luckperms/data/MySQLConfiguration.java b/common/src/main/java/me/lucko/luckperms/storage/MySQLConfiguration.java similarity index 97% rename from common/src/main/java/me/lucko/luckperms/data/MySQLConfiguration.java rename to common/src/main/java/me/lucko/luckperms/storage/MySQLConfiguration.java index f99743ac3..09ed0a883 100644 --- a/common/src/main/java/me/lucko/luckperms/data/MySQLConfiguration.java +++ b/common/src/main/java/me/lucko/luckperms/storage/MySQLConfiguration.java @@ -20,7 +20,7 @@ * SOFTWARE. */ -package me.lucko.luckperms.data; +package me.lucko.luckperms.storage; import lombok.AllArgsConstructor; import lombok.Getter; diff --git a/common/src/main/java/me/lucko/luckperms/data/methods/FlatfileDatastore.java b/common/src/main/java/me/lucko/luckperms/storage/methods/FlatfileDatastore.java similarity index 83% rename from common/src/main/java/me/lucko/luckperms/data/methods/FlatfileDatastore.java rename to common/src/main/java/me/lucko/luckperms/storage/methods/FlatfileDatastore.java index 1be009b6e..8427be67e 100644 --- a/common/src/main/java/me/lucko/luckperms/data/methods/FlatfileDatastore.java +++ b/common/src/main/java/me/lucko/luckperms/storage/methods/FlatfileDatastore.java @@ -20,25 +20,32 @@ * SOFTWARE. */ -package me.lucko.luckperms.data.methods; +package me.lucko.luckperms.storage.methods; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import lombok.Cleanup; import me.lucko.luckperms.LuckPermsPlugin; -import me.lucko.luckperms.data.Datastore; +import me.lucko.luckperms.api.LogEntry; +import me.lucko.luckperms.constants.Constants; +import me.lucko.luckperms.data.Log; import me.lucko.luckperms.groups.Group; +import me.lucko.luckperms.storage.Datastore; import me.lucko.luckperms.tracks.Track; import me.lucko.luckperms.users.User; import java.io.*; import java.util.*; import java.util.concurrent.ConcurrentHashMap; +import java.util.logging.*; +import java.util.logging.Formatter; import java.util.stream.Collectors; @SuppressWarnings({"ResultOfMethodCallIgnored", "UnnecessaryLocalVariable"}) public class FlatfileDatastore extends Datastore { + private static final String LOG_FORMAT = "%s(%s): [%s] %s(%s) --> %s"; + private final Logger actionLogger = Logger.getLogger("lp_actions"); private Map uuidCache = new ConcurrentHashMap<>(); private final File pluginDir; @@ -46,6 +53,7 @@ public class FlatfileDatastore extends Datastore { private File groupsDir; private File tracksDir; private File uuidData; + private File actionLog; public FlatfileDatastore(LuckPermsPlugin plugin, File pluginDir) { super(plugin, "Flatfile - JSON"); @@ -90,6 +98,23 @@ public class FlatfileDatastore extends Datastore { } uuidCache.putAll(getUUIDCache()); + + try { + FileHandler fh = new FileHandler(actionLog.getAbsolutePath(), 0, 1, true); + fh.setFormatter(new Formatter() { + @Override + public String format(LogRecord record) { + return new Date(record.getMillis()).toString() + ": " + record.getMessage() + "\n"; + } + }); + actionLogger.addHandler(fh); + actionLogger.setUseParentHandlers(false); + actionLogger.setLevel(Level.ALL); + actionLogger.setFilter(record -> true); + } catch (Exception e) { + e.printStackTrace(); + } + setAcceptingLogins(true); } @@ -108,6 +133,9 @@ public class FlatfileDatastore extends Datastore { uuidData = new File(data, "uuidcache.txt"); uuidData.createNewFile(); + + actionLog = new File(data, "actions.log"); + actionLog.createNewFile(); } @Override @@ -115,9 +143,28 @@ public class FlatfileDatastore extends Datastore { saveUUIDCache(uuidCache); } + @Override + public boolean logAction(LogEntry entry) { + actionLogger.info(String.format(LOG_FORMAT, + (entry.getActor().equals(Constants.getConsoleUUID()) ? "" : entry.getActor() + " "), + entry.getActorName(), + Character.toString(entry.getType()), + (entry.getActed() == null ? "" : entry.getActed().toString() + " "), + entry.getActedName(), + entry.getAction()) + ); + return true; + } + + @Override + public Log getLog() { + // TODO Add log viewing support for flatfile D: + return Log.builder().build(); + } + @Override public boolean loadOrCreateUser(UUID uuid, String username) { - User user = plugin.getUserManager().makeUser(uuid, username); + User user = plugin.getUserManager().make(uuid, username); File userFile = new File(usersDir, uuid.toString() + ".json"); if (!userFile.exists()) { @@ -148,12 +195,13 @@ public class FlatfileDatastore extends Datastore { if (!success) return false; } + final String[] name = new String[1]; boolean success = doRead(userFile, reader -> { reader.beginObject(); reader.nextName(); // uuid record reader.nextString(); // uuid reader.nextName(); // name record - reader.nextString(); // name + name[0] = reader.nextString(); // name reader.nextName(); // primaryGroup record user.setPrimaryGroup(reader.nextString()); // primaryGroup reader.nextName(); //perms @@ -169,13 +217,30 @@ public class FlatfileDatastore extends Datastore { return true; }); - if (success) plugin.getUserManager().updateOrSetUser(user); + if (!name[0].equals(user.getName())) { + doWrite(userFile, writer -> { + writer.beginObject(); + writer.name("uuid").value(user.getUuid().toString()); + writer.name("name").value(user.getName()); + writer.name("primaryGroup").value(user.getPrimaryGroup()); + writer.name("perms"); + writer.beginObject(); + for (Map.Entry e : user.getNodes().entrySet()) { + writer.name(e.getKey()).value(e.getValue().booleanValue()); + } + writer.endObject(); + writer.endObject(); + return true; + }); + } + + if (success) plugin.getUserManager().updateOrSet(user); return success; } @Override public boolean loadUser(UUID uuid) { - User user = plugin.getUserManager().makeUser(uuid); + User user = plugin.getUserManager().make(uuid); File userFile = new File(usersDir, uuid.toString() + ".json"); if (!userFile.exists()) { @@ -203,7 +268,7 @@ public class FlatfileDatastore extends Datastore { return true; }); - if (success) plugin.getUserManager().updateOrSetUser(user); + if (success) plugin.getUserManager().updateOrSet(user); return success; } @@ -238,7 +303,7 @@ public class FlatfileDatastore extends Datastore { @Override public boolean createAndLoadGroup(String name) { - Group group = plugin.getGroupManager().makeGroup(name); + Group group = plugin.getGroupManager().make(name); File groupFile = new File(groupsDir, name + ".json"); if (!groupFile.exists()) { @@ -282,13 +347,13 @@ public class FlatfileDatastore extends Datastore { return true; }); - if (success) plugin.getGroupManager().updateOrSetGroup(group); + if (success) plugin.getGroupManager().updateOrSet(group); return success; } @Override public boolean loadGroup(String name) { - Group group = plugin.getGroupManager().makeGroup(name); + Group group = plugin.getGroupManager().make(name); File groupFile = new File(groupsDir, name + ".json"); if (!groupFile.exists()) { @@ -312,7 +377,7 @@ public class FlatfileDatastore extends Datastore { return true; }); - if (success) plugin.getGroupManager().updateOrSetGroup(group); + if (success) plugin.getGroupManager().updateOrSet(group); return success; } @@ -366,7 +431,7 @@ public class FlatfileDatastore extends Datastore { @Override public boolean createAndLoadTrack(String name) { - Track track = plugin.getTrackManager().makeTrack(name); + Track track = plugin.getTrackManager().make(name); List groups = new ArrayList<>(); File trackFile = new File(tracksDir, name + ".json"); @@ -409,13 +474,13 @@ public class FlatfileDatastore extends Datastore { }); track.setGroups(groups); - if (success) plugin.getTrackManager().updateOrSetTrack(track); + if (success) plugin.getTrackManager().updateOrSet(track); return success; } @Override public boolean loadTrack(String name) { - Track track = plugin.getTrackManager().makeTrack(name); + Track track = plugin.getTrackManager().make(name); List groups = new ArrayList<>(); File trackFile = new File(tracksDir, name + ".json"); @@ -438,7 +503,7 @@ public class FlatfileDatastore extends Datastore { }); track.setGroups(groups); - if (success) plugin.getTrackManager().updateOrSetTrack(track); + if (success) plugin.getTrackManager().updateOrSet(track); return success; } diff --git a/common/src/main/java/me/lucko/luckperms/data/methods/MySQLDatastore.java b/common/src/main/java/me/lucko/luckperms/storage/methods/MySQLDatastore.java similarity index 90% rename from common/src/main/java/me/lucko/luckperms/data/methods/MySQLDatastore.java rename to common/src/main/java/me/lucko/luckperms/storage/methods/MySQLDatastore.java index b0df416e9..3e9a24565 100644 --- a/common/src/main/java/me/lucko/luckperms/data/methods/MySQLDatastore.java +++ b/common/src/main/java/me/lucko/luckperms/storage/methods/MySQLDatastore.java @@ -20,12 +20,12 @@ * SOFTWARE. */ -package me.lucko.luckperms.data.methods; +package me.lucko.luckperms.storage.methods; import com.zaxxer.hikari.HikariDataSource; import lombok.Cleanup; import me.lucko.luckperms.LuckPermsPlugin; -import me.lucko.luckperms.data.MySQLConfiguration; +import me.lucko.luckperms.storage.MySQLConfiguration; import java.sql.Connection; import java.sql.PreparedStatement; @@ -38,6 +38,7 @@ public class MySQLDatastore extends SQLDatastore { private static final String CREATETABLE_USERS = "CREATE TABLE IF NOT EXISTS `lp_users` (`uuid` VARCHAR(36) NOT NULL, `name` VARCHAR(16) NOT NULL, `primary_group` VARCHAR(36) NOT NULL, `perms` TEXT NOT NULL, PRIMARY KEY (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;"; private static final String CREATETABLE_GROUPS = "CREATE TABLE IF NOT EXISTS `lp_groups` (`name` VARCHAR(36) NOT NULL, `perms` TEXT NULL, PRIMARY KEY (`name`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;"; private static final String CREATETABLE_TRACKS = "CREATE TABLE IF NOT EXISTS `lp_tracks` (`name` VARCHAR(36) NOT NULL, `groups` TEXT NULL, PRIMARY KEY (`name`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;"; + private static final String CREATETABLE_ACTION = "CREATE TABLE IF NOT EXISTS `lp_actions` (`id` INT AUTO_INCREMENT NOT NULL, `time` BIG INT NOT NULL, `actor_uuid` VARCHAR(36) NOT NULL, `actor_name` VARCHAR(16) NOT NULL, `type` CHAR(1) NOT NULL, `acted_uuid` VARCHAR(36) NOT NULL, `acted_name` VARCHAR(36) NOT NULL, `action` VARCHAR(256) NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;"; private final MySQLConfiguration configuration; private HikariDataSource hikari; @@ -64,7 +65,7 @@ public class MySQLDatastore extends SQLDatastore { hikari.addDataSourceProperty("user", username); hikari.addDataSourceProperty("password", password); - if (!setupTables(CREATETABLE_UUID, CREATETABLE_USERS, CREATETABLE_GROUPS, CREATETABLE_TRACKS)) { + if (!setupTables(CREATETABLE_UUID, CREATETABLE_USERS, CREATETABLE_GROUPS, CREATETABLE_TRACKS, CREATETABLE_ACTION)) { plugin.getLog().severe("Error occurred whilst initialising the database. All connections are disallowed."); shutdown(); } else { diff --git a/common/src/main/java/me/lucko/luckperms/data/methods/SQLDatastore.java b/common/src/main/java/me/lucko/luckperms/storage/methods/SQLDatastore.java similarity index 79% rename from common/src/main/java/me/lucko/luckperms/data/methods/SQLDatastore.java rename to common/src/main/java/me/lucko/luckperms/storage/methods/SQLDatastore.java index f3b24ca2b..c6547e3b1 100644 --- a/common/src/main/java/me/lucko/luckperms/data/methods/SQLDatastore.java +++ b/common/src/main/java/me/lucko/luckperms/storage/methods/SQLDatastore.java @@ -20,16 +20,18 @@ * SOFTWARE. */ -package me.lucko.luckperms.data.methods; +package me.lucko.luckperms.storage.methods; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import lombok.AllArgsConstructor; import lombok.Getter; import me.lucko.luckperms.LuckPermsPlugin; -import me.lucko.luckperms.data.Datastore; +import me.lucko.luckperms.api.LogEntry; +import me.lucko.luckperms.data.Log; import me.lucko.luckperms.groups.Group; import me.lucko.luckperms.groups.GroupManager; +import me.lucko.luckperms.storage.Datastore; import me.lucko.luckperms.tracks.Track; import me.lucko.luckperms.tracks.TrackManager; import me.lucko.luckperms.users.User; @@ -70,6 +72,9 @@ abstract class SQLDatastore extends Datastore { private static final String UUIDCACHE_SELECT = "SELECT uuid FROM lp_uuid WHERE name=?"; private static final String UUIDCACHE_UPDATE = "UPDATE lp_uuid SET uuid=? WHERE name=?"; + private static final String ACTION_INSERT = "INSERT INTO lp_actions(`time`, `actor_uuid`, `actor_name`, `type`, `acted_uuid`, `acted_name`, `action`) VALUES(?, ?, ?, ?, ?, ?, ?)"; + private static final String ACTION_SELECT_ALL = "SELECT * FROM lp_actions"; + private final Gson gson; SQLDatastore(LuckPermsPlugin plugin, String name) { @@ -93,7 +98,7 @@ abstract class SQLDatastore extends Datastore { @Override public boolean loadUser(UUID uuid) { - User user = plugin.getUserManager().makeUser(uuid); + User user = plugin.getUserManager().make(uuid); boolean success = runQuery(new QueryRS(USER_SELECT) { @Override void onRun(PreparedStatement preparedStatement) throws SQLException { @@ -112,13 +117,60 @@ abstract class SQLDatastore extends Datastore { } }); - if (success) plugin.getUserManager().updateOrSetUser(user); + if (success) plugin.getUserManager().updateOrSet(user); return success; } + @Override + public boolean logAction(LogEntry entry) { + boolean success = runQuery(new QueryPS(ACTION_INSERT) { + @Override + void onRun(PreparedStatement preparedStatement) throws SQLException { + preparedStatement.setLong(1, entry.getTimestamp()); + preparedStatement.setString(2, entry.getActor().toString()); + preparedStatement.setString(3, entry.getActorName()); + preparedStatement.setString(4, Character.toString(entry.getType())); + preparedStatement.setString(5, entry.getActed() == null ? "null" : entry.getActed().toString()); + preparedStatement.setString(6, entry.getActedName()); + preparedStatement.setString(7, entry.getAction()); + } + }); + return success; + } + + @Override + public Log getLog() { + final Log.Builder log = Log.builder(); + boolean success = runQuery(new QueryRS(ACTION_SELECT_ALL) { + @Override + void onRun(PreparedStatement preparedStatement) throws SQLException { + + } + + @Override + boolean onResult(ResultSet resultSet) throws SQLException { + while (resultSet.next()) { + final String actedUuid = resultSet.getString("acted_uuid"); + LogEntry e = new LogEntry( + resultSet.getLong("time"), + UUID.fromString(resultSet.getString("actor_uuid")), + resultSet.getString("actor_name"), + resultSet.getString("type").toCharArray()[0], + actedUuid.equals("null") ? null : UUID.fromString(actedUuid), + resultSet.getString("acted_name"), + resultSet.getString("action") + ); + log.add(e); + } + return true; + } + }); + return success ? log.build() : null; + } + @Override public boolean loadOrCreateUser(UUID uuid, String username) { - User user = plugin.getUserManager().makeUser(uuid, username); + User user = plugin.getUserManager().make(uuid, username); boolean success = runQuery(new QueryRS(USER_SELECT) { @Override void onRun(PreparedStatement preparedStatement) throws SQLException { @@ -143,12 +195,24 @@ abstract class SQLDatastore extends Datastore { } else { user.getNodes().putAll(gson.fromJson(resultSet.getString("perms"), NM_TYPE)); user.setPrimaryGroup(resultSet.getString("primary_group")); + + if (!resultSet.getString("name").equals(user.getName())) { + runQuery(new QueryPS(USER_UPDATE) { + @Override + void onRun(PreparedStatement preparedStatement) throws SQLException { + preparedStatement.setString(1, user.getName()); + preparedStatement.setString(2, user.getPrimaryGroup()); + preparedStatement.setString(3, gson.toJson(user.getNodes())); + preparedStatement.setString(4, user.getUuid().toString()); + } + }); + } } return success; } }); - if (success) plugin.getUserManager().updateOrSetUser(user); + if (success) plugin.getUserManager().updateOrSet(user); return success; } @@ -168,7 +232,7 @@ abstract class SQLDatastore extends Datastore { @Override public boolean createAndLoadGroup(String name) { - Group group = plugin.getGroupManager().makeGroup(name); + Group group = plugin.getGroupManager().make(name); boolean success = runQuery(new QueryRS(GROUP_SELECT) { @Override void onRun(PreparedStatement preparedStatement) throws SQLException { @@ -193,13 +257,13 @@ abstract class SQLDatastore extends Datastore { } }); - if (success) plugin.getGroupManager().updateOrSetGroup(group); + if (success) plugin.getGroupManager().updateOrSet(group); return success; } @Override public boolean loadGroup(String name) { - Group group = plugin.getGroupManager().makeGroup(name); + Group group = plugin.getGroupManager().make(name); boolean success = runQuery(new QueryRS(GROUP_SELECT) { @Override void onRun(PreparedStatement preparedStatement) throws SQLException { @@ -216,7 +280,7 @@ abstract class SQLDatastore extends Datastore { } }); - if (success) plugin.getGroupManager().updateOrSetGroup(group); + if (success) plugin.getGroupManager().updateOrSet(group); return success; } @@ -232,7 +296,7 @@ abstract class SQLDatastore extends Datastore { @Override boolean onResult(ResultSet resultSet) throws SQLException { while (resultSet.next()) { - Group group = plugin.getGroupManager().makeGroup(resultSet.getString("name")); + Group group = plugin.getGroupManager().make(resultSet.getString("name")); group.getNodes().putAll(gson.fromJson(resultSet.getString("perms"), NM_TYPE)); groups.add(group); } @@ -243,7 +307,7 @@ abstract class SQLDatastore extends Datastore { if (success) { GroupManager gm = plugin.getGroupManager(); gm.unloadAll(); - groups.forEach(gm::setGroup); + groups.forEach(gm::set); } return success; } @@ -269,13 +333,13 @@ abstract class SQLDatastore extends Datastore { } }); - if (success) plugin.getGroupManager().unloadGroup(group); + if (success) plugin.getGroupManager().unload(group); return success; } @Override public boolean createAndLoadTrack(String name) { - Track track = plugin.getTrackManager().makeTrack(name); + Track track = plugin.getTrackManager().make(name); boolean success = runQuery(new QueryRS(TRACK_SELECT) { @Override void onRun(PreparedStatement preparedStatement) throws SQLException { @@ -300,13 +364,13 @@ abstract class SQLDatastore extends Datastore { } }); - if (success) plugin.getTrackManager().updateOrSetTrack(track); + if (success) plugin.getTrackManager().updateOrSet(track); return success; } @Override public boolean loadTrack(String name) { - Track track = plugin.getTrackManager().makeTrack(name); + Track track = plugin.getTrackManager().make(name); boolean success = runQuery(new QueryRS(TRACK_SELECT) { @Override void onRun(PreparedStatement preparedStatement) throws SQLException { @@ -323,7 +387,7 @@ abstract class SQLDatastore extends Datastore { } }); - if (success) plugin.getTrackManager().updateOrSetTrack(track); + if (success) plugin.getTrackManager().updateOrSet(track); return success; } @@ -339,7 +403,7 @@ abstract class SQLDatastore extends Datastore { @Override boolean onResult(ResultSet resultSet) throws SQLException { while (resultSet.next()) { - Track track = plugin.getTrackManager().makeTrack(resultSet.getString("name")); + Track track = plugin.getTrackManager().make(resultSet.getString("name")); track.setGroups(gson.fromJson(resultSet.getString("groups"), T_TYPE)); tracks.add(track); } @@ -350,7 +414,7 @@ abstract class SQLDatastore extends Datastore { if (success) { TrackManager tm = plugin.getTrackManager(); tm.unloadAll(); - tracks.forEach(tm::setTrack); + tracks.forEach(tm::set); } return success; } @@ -376,7 +440,7 @@ abstract class SQLDatastore extends Datastore { } }); - if (success) plugin.getTrackManager().unloadTrack(track); + if (success) plugin.getTrackManager().unload(track); return success; } diff --git a/common/src/main/java/me/lucko/luckperms/data/methods/SQLiteDatastore.java b/common/src/main/java/me/lucko/luckperms/storage/methods/SQLiteDatastore.java similarity index 90% rename from common/src/main/java/me/lucko/luckperms/data/methods/SQLiteDatastore.java rename to common/src/main/java/me/lucko/luckperms/storage/methods/SQLiteDatastore.java index 50786334c..1642ebc7d 100644 --- a/common/src/main/java/me/lucko/luckperms/data/methods/SQLiteDatastore.java +++ b/common/src/main/java/me/lucko/luckperms/storage/methods/SQLiteDatastore.java @@ -20,7 +20,7 @@ * SOFTWARE. */ -package me.lucko.luckperms.data.methods; +package me.lucko.luckperms.storage.methods; import lombok.Cleanup; import me.lucko.luckperms.LuckPermsPlugin; @@ -34,6 +34,7 @@ public class SQLiteDatastore extends SQLDatastore { private static final String CREATETABLE_USERS = "CREATE TABLE IF NOT EXISTS `lp_users` (`uuid` VARCHAR(36) NOT NULL, `name` VARCHAR(16) NOT NULL, `primary_group` VARCHAR(36) NOT NULL, `perms` TEXT NOT NULL, PRIMARY KEY (`uuid`));"; private static final String CREATETABLE_GROUPS = "CREATE TABLE IF NOT EXISTS `lp_groups` (`name` VARCHAR(36) NOT NULL, `perms` TEXT NULL, PRIMARY KEY (`name`));"; private static final String CREATETABLE_TRACKS = "CREATE TABLE IF NOT EXISTS `lp_tracks` (`name` VARCHAR(36) NOT NULL, `groups` TEXT NULL, PRIMARY KEY (`name`));"; + private static final String CREATETABLE_ACTION = "CREATE TABLE IF NOT EXISTS `lp_actions` (`id` INTEGER PRIMARY KEY NOT NULL, `time` BIG INT NOT NULL, `actor_uuid` VARCHAR(36) NOT NULL, `actor_name` VARCHAR(16) NOT NULL, `type` CHAR(1) NOT NULL, `acted_uuid` VARCHAR(36) NOT NULL, `acted_name` VARCHAR(36) NOT NULL, `action` VARCHAR(256) NOT NULL);"; private final File file; private Connection connection = null; @@ -45,7 +46,7 @@ public class SQLiteDatastore extends SQLDatastore { @Override public void init() { - if (!setupTables(CREATETABLE_UUID, CREATETABLE_USERS, CREATETABLE_GROUPS, CREATETABLE_TRACKS)) { + if (!setupTables(CREATETABLE_UUID, CREATETABLE_USERS, CREATETABLE_GROUPS, CREATETABLE_TRACKS, CREATETABLE_ACTION)) { plugin.getLog().severe("Error occurred whilst initialising the database. All connections are disallowed."); shutdown(); } else { diff --git a/common/src/main/java/me/lucko/luckperms/tracks/Track.java b/common/src/main/java/me/lucko/luckperms/tracks/Track.java index a773d76bb..f167cb932 100644 --- a/common/src/main/java/me/lucko/luckperms/tracks/Track.java +++ b/common/src/main/java/me/lucko/luckperms/tracks/Track.java @@ -29,15 +29,16 @@ import lombok.ToString; import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import me.lucko.luckperms.exceptions.ObjectLacksException; import me.lucko.luckperms.groups.Group; +import me.lucko.luckperms.utils.Identifiable; import java.util.ArrayList; import java.util.Collections; import java.util.List; -@ToString(of = {"name"}) -@EqualsAndHashCode(of = {"name"}, callSuper = false) +@ToString +@EqualsAndHashCode(of = {"name"}) @RequiredArgsConstructor -public class Track { +public class Track implements Identifiable { /** * The name of the track @@ -200,4 +201,9 @@ public class Track { throw new ObjectLacksException(); } } + + @Override + public String getId() { + return name; + } } diff --git a/common/src/main/java/me/lucko/luckperms/tracks/TrackManager.java b/common/src/main/java/me/lucko/luckperms/tracks/TrackManager.java index e9c4dfd51..525a98d56 100644 --- a/common/src/main/java/me/lucko/luckperms/tracks/TrackManager.java +++ b/common/src/main/java/me/lucko/luckperms/tracks/TrackManager.java @@ -22,29 +22,12 @@ package me.lucko.luckperms.tracks; -import lombok.Getter; +import me.lucko.luckperms.utils.AbstractManager; -import java.util.Map; import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; -public class TrackManager { - - /** - * A {@link Map} containing all loaded tracks - */ - @Getter - private final Map tracks = new ConcurrentHashMap<>(); - - /** - * Get a track object by name - * @param name the name to search by - * @return a {@link Track} object if the track is loaded, else returns null - */ - public Track getTrack(String name) { - return tracks.get(name); - } +public class TrackManager extends AbstractManager { /** * Returns a set of tracks that contain at least one of the groups from the Set provided @@ -52,54 +35,12 @@ public class TrackManager { * @return a set of tracks that the groups could be a member of */ public Set getApplicableTracks(String group) { - return tracks.values().stream().filter(t -> t.containsGroup(group)).collect(Collectors.toSet()); + return objects.values().stream().filter(t -> t.containsGroup(group)).collect(Collectors.toSet()); } - /** - * Add a track to the loaded tracks map - * @param track The track to add - */ - public void setTrack(Track track) { - tracks.put(track.getName(), track); - } - - /** - * Updates (or sets if the track wasn't already loaded) a track in the tracks map - * @param track The track to update or set - */ - public void updateOrSetTrack(Track track) { - if (!isLoaded(track.getName())) { - // The track isn't already loaded - tracks.put(track.getName(), track); - } else { - tracks.get(track.getName()).setGroups(track.getGroups()); - } - } - - /** - * Check to see if a track is loaded or not - * @param name The name of the track - * @return true if the track is loaded - */ - public boolean isLoaded(String name) { - return tracks.containsKey(name); - } - - /** - * Removes and unloads the track from the plugins internal storage - * @param track The track to unload - */ - public void unloadTrack(Track track) { - if (track != null) { - tracks.remove(track.getName()); - } - } - - /** - * Unloads all tracks from the manager - */ - public void unloadAll() { - tracks.clear(); + @Override + protected void copy(Track from, Track to) { + to.setGroups(from.getGroups()); } /** @@ -107,7 +48,8 @@ public class TrackManager { * @param name The name of the track * @return a new {@link Track} object */ - public Track makeTrack(String name) { + @Override + public Track make(String name) { return new Track(name); } } diff --git a/common/src/main/java/me/lucko/luckperms/users/User.java b/common/src/main/java/me/lucko/luckperms/users/User.java index fb225df5e..5fd8c4eea 100644 --- a/common/src/main/java/me/lucko/luckperms/users/User.java +++ b/common/src/main/java/me/lucko/luckperms/users/User.java @@ -27,11 +27,12 @@ import lombok.Getter; import lombok.Setter; import lombok.ToString; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.constants.Patterns; +import me.lucko.luckperms.core.PermissionHolder; import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; import me.lucko.luckperms.exceptions.ObjectLacksException; import me.lucko.luckperms.groups.Group; -import me.lucko.luckperms.utils.Patterns; -import me.lucko.luckperms.utils.PermissionHolder; +import me.lucko.luckperms.utils.Identifiable; import java.util.List; import java.util.Map; @@ -40,7 +41,7 @@ import java.util.stream.Collectors; @ToString(of = {"uuid"}) @EqualsAndHashCode(of = {"uuid"}, callSuper = false) -public abstract class User extends PermissionHolder { +public abstract class User extends PermissionHolder implements Identifiable { /** * The users Mojang UUID @@ -319,4 +320,9 @@ public abstract class User extends PermissionHolder { .map(s -> Patterns.DOT.split(s, 2)[1]) .collect(Collectors.toList()); } + + @Override + public UUID getId() { + return uuid; + } } diff --git a/common/src/main/java/me/lucko/luckperms/users/UserManager.java b/common/src/main/java/me/lucko/luckperms/users/UserManager.java index d7c8e2247..a7031a672 100644 --- a/common/src/main/java/me/lucko/luckperms/users/UserManager.java +++ b/common/src/main/java/me/lucko/luckperms/users/UserManager.java @@ -22,77 +22,38 @@ package me.lucko.luckperms.users; -import lombok.Getter; import lombok.RequiredArgsConstructor; import me.lucko.luckperms.LuckPermsPlugin; import me.lucko.luckperms.exceptions.ObjectAlreadyHasException; +import me.lucko.luckperms.utils.AbstractManager; +import me.lucko.luckperms.utils.Identifiable; -import java.util.Map; import java.util.NoSuchElementException; import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; @RequiredArgsConstructor -public abstract class UserManager { - - /** - * A {@link Map} containing all online/loaded users - */ - @Getter - private final Map users = new ConcurrentHashMap<>(); - - /** - * Reference to main plugin instance - */ +public abstract class UserManager extends AbstractManager { private final LuckPermsPlugin plugin; - /** - * Get a user object by UUID - * @param uuid The uuid to search by - * @return a {@link User} object if the user is loaded, returns null if the user is not loaded - */ - public User getUser(UUID uuid) { - return users.get(uuid); - } - /** * Get a user object by name * @param name The name to search by * @return a {@link User} object if the user is loaded, returns null if the user is not loaded */ @SuppressWarnings("OptionalGetWithoutIsPresent") - public User getUser(String name) { + public User get(String name) { try { - return users.values().stream().filter(u -> u.getName().equalsIgnoreCase(name)).limit(1).findAny().get(); + return objects.values().stream().filter(u -> u.getName().equalsIgnoreCase(name)).limit(1).findAny().get(); } catch (NoSuchElementException e) { return null; } } - /** - * Add a user to the users map - * @param user the user to add - */ - public void setUser(User user) { - users.put(user.getUuid(), user); - } - - /** - * Updates (or sets if the user wasn't already loaded) a user in the users map - * @param user The user to update or set - */ - public void updateOrSetUser(User user) { - if (!isLoaded(user.getUuid())) { - // The user isn't already loaded, so we can just add - users.put(user.getUuid(), user); - // They're probably not online, but in case they are... - user.refreshPermissions(); - } else { - // Override the user's current loaded nodes, and force a refresh - users.get(user.getUuid()).setNodes(user.getNodes()); - users.get(user.getUuid()).setPrimaryGroup(user.getPrimaryGroup()); - users.get(user.getUuid()).refreshPermissions(); - } + @Override + protected void copy(User from, User to) { + to.setNodes(from.getNodes()); + to.setPrimaryGroup(from.getPrimaryGroup()); + to.refreshPermissions(); } /** @@ -108,32 +69,10 @@ public abstract class UserManager { } /** - * Check to see if a user is loaded or not - * @param uuid the UUID of the user - * @return true if the user is loaded - */ - public boolean isLoaded(UUID uuid) { - return users.containsKey(uuid); - } - - /** - * Removes and unloads any permission links of the user from the internal storage - * @param user The user to unload - */ - public abstract void unloadUser(User user); - - /** - * Checks to see if the user is online, and if they are not, runs {@link #unloadUser(User)} + * Checks to see if the user is online, and if they are not, runs {@link #unload(Identifiable)} * @param user The user to be cleaned up */ - public abstract void cleanupUser(User user); - - /** - * Makes a new {@link User} object - * @param uuid The UUID of the user - * @return a new {@link User} object - */ - public abstract User makeUser(UUID uuid); + public abstract void cleanup(User user); /** * Makes a new {@link User} object @@ -141,7 +80,7 @@ public abstract class UserManager { * @param username The username of the user * @return a new {@link User} object */ - public abstract User makeUser(UUID uuid, String username); + public abstract User make(UUID uuid, String username); /** * Reloads the data of all online users diff --git a/common/src/main/java/me/lucko/luckperms/utils/AbstractListener.java b/common/src/main/java/me/lucko/luckperms/utils/AbstractListener.java index eb9856968..8776892c3 100644 --- a/common/src/main/java/me/lucko/luckperms/utils/AbstractListener.java +++ b/common/src/main/java/me/lucko/luckperms/utils/AbstractListener.java @@ -24,6 +24,8 @@ package me.lucko.luckperms.utils; import lombok.AllArgsConstructor; import me.lucko.luckperms.LuckPermsPlugin; +import me.lucko.luckperms.api.data.Callback; +import me.lucko.luckperms.core.UuidCache; import me.lucko.luckperms.users.User; import java.util.UUID; @@ -43,11 +45,11 @@ public class AbstractListener { } else { // No previous data for this player cache.addToCache(u, u); - plugin.getDatastore().saveUUIDData(username, u, b -> {}); + plugin.getDatastore().saveUUIDData(username, u, Callback.empty()); } } else { // Online mode, no cache needed. This is just for name -> uuid lookup. - plugin.getDatastore().saveUUIDData(username, u, b -> {}); + plugin.getDatastore().saveUUIDData(username, u, Callback.empty()); } plugin.getDatastore().loadOrCreateUser(cache.getUUID(u), username); @@ -63,12 +65,12 @@ public class AbstractListener { // Unload the user from memory when they disconnect; cache.clearCache(uuid); - final User user = plugin.getUserManager().getUser(cache.getUUID(uuid)); - plugin.getUserManager().unloadUser(user); + final User user = plugin.getUserManager().get(cache.getUUID(uuid)); + plugin.getUserManager().unload(user); } protected void refreshPlayer(UUID uuid) { - final User user = plugin.getUserManager().getUser(plugin.getUuidCache().getUUID(uuid)); + final User user = plugin.getUserManager().get(plugin.getUuidCache().getUUID(uuid)); if (user != null) { user.refreshPermissions(); } diff --git a/common/src/main/java/me/lucko/luckperms/utils/AbstractManager.java b/common/src/main/java/me/lucko/luckperms/utils/AbstractManager.java new file mode 100644 index 000000000..8cd335ef4 --- /dev/null +++ b/common/src/main/java/me/lucko/luckperms/utils/AbstractManager.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2016 Lucko (Luck) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.luckperms.utils; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * An abstract manager class + * @param the class used to identify each object held in this manager + * @param the class this manager is "managing" + */ +public abstract class AbstractManager> { + protected final Map objects = new ConcurrentHashMap<>(); + + public Map getAll() { + return objects; + } + + /** + * Get an object by id + * @param id The id to search by + * @return a {@link T} object if the object is loaded, returns null if the object is not loaded + */ + public T get(I id) { + return objects.get(id); + } + + /** + * Add a object to the loaded objects map + * @param t The object to add + */ + public void set(T t) { + objects.put(t.getId(), t); + } + + /** + * Updates (or sets if the object wasn't already loaded) an object in the objects map + * @param t The object to update or set + */ + public void updateOrSet(T t) { + if (!isLoaded(t.getId())) { + // The object isn't already loaded + objects.put(t.getId(), t); + } else { + copy(t, objects.get(t.getId())); + } + } + + protected abstract void copy(T from, T to); + + /** + * Check to see if a object is loaded or not + * @param id The id of the object + * @return true if the object is loaded + */ + public boolean isLoaded(I id) { + return objects.containsKey(id); + } + + /** + * Removes and unloads the object from the manager + * @param t The object to unload + */ + public void unload(T t) { + if (t != null) { + objects.remove(t.getId()); + } + } + + /** + * Unloads all objects from the manager + */ + public void unloadAll() { + objects.clear(); + } + + /** + * Makes a new object + * @param id the id of the object + * @return a new {@link T} object + */ + public abstract T make(I id); + +} diff --git a/common/src/main/java/me/lucko/luckperms/utils/ArgumentChecker.java b/common/src/main/java/me/lucko/luckperms/utils/ArgumentChecker.java index bbed6fc1d..d1949adfa 100644 --- a/common/src/main/java/me/lucko/luckperms/utils/ArgumentChecker.java +++ b/common/src/main/java/me/lucko/luckperms/utils/ArgumentChecker.java @@ -23,29 +23,29 @@ package me.lucko.luckperms.utils; import lombok.experimental.UtilityClass; +import me.lucko.luckperms.constants.Patterns; @UtilityClass public class ArgumentChecker { public static boolean checkUsername(String s) { - return !(s.length() > 16 || Patterns.NON_USERNAME.matcher(s).find()); + return (s.length() > 16 || Patterns.NON_USERNAME.matcher(s).find()); } public static boolean checkName(String s) { - return !(s.length() > 36 || Patterns.NON_ALPHA_NUMERIC.matcher(s).find()); + return (s.length() > 36 || Patterns.NON_ALPHA_NUMERIC.matcher(s).find()); } public static boolean checkServer(String s) { - return !s.toLowerCase().startsWith("r=") && !Patterns.NON_ALPHA_NUMERIC.matcher(s).find(); + return s.toLowerCase().startsWith("r=") || Patterns.NON_ALPHA_NUMERIC.matcher(s).find(); } public static boolean checkNode(String s) { - return !(s.contains("/") || s.contains("$")); + return (s.contains("/") || s.contains("$")); } public static boolean checkTime(long l) { - return !DateUtil.shouldExpire(l); + return DateUtil.shouldExpire(l); } - } diff --git a/common/src/main/java/me/lucko/luckperms/utils/Identifiable.java b/common/src/main/java/me/lucko/luckperms/utils/Identifiable.java new file mode 100644 index 000000000..a13e0e626 --- /dev/null +++ b/common/src/main/java/me/lucko/luckperms/utils/Identifiable.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2016 Lucko (Luck) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.luckperms.utils; + +public interface Identifiable { + + T getId(); + +} diff --git a/common/src/main/java/me/lucko/luckperms/utils/LogUtil.java b/common/src/main/java/me/lucko/luckperms/utils/LogFactory.java similarity index 98% rename from common/src/main/java/me/lucko/luckperms/utils/LogUtil.java rename to common/src/main/java/me/lucko/luckperms/utils/LogFactory.java index 4b55e50c5..9b834307b 100644 --- a/common/src/main/java/me/lucko/luckperms/utils/LogUtil.java +++ b/common/src/main/java/me/lucko/luckperms/utils/LogFactory.java @@ -26,7 +26,7 @@ import lombok.experimental.UtilityClass; import me.lucko.luckperms.api.Logger; @UtilityClass -public class LogUtil { +public class LogFactory { public static Logger wrap(org.slf4j.Logger l) { return new Logger() { private final org.slf4j.Logger logger = l; diff --git a/pom.xml b/pom.xml index 84d895ed0..59795305a 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ me.lucko.luckperms luckperms - 2.2 + 2.3 common api diff --git a/sponge/pom.xml b/sponge/pom.xml index 1ac8be7c8..0f3c08090 100644 --- a/sponge/pom.xml +++ b/sponge/pom.xml @@ -5,7 +5,7 @@ luckperms me.lucko.luckperms - 2.2 + 2.3 4.0.0 diff --git a/sponge/src/main/java/me/lucko/luckperms/LPSpongePlugin.java b/sponge/src/main/java/me/lucko/luckperms/LPSpongePlugin.java index 1a4cabae8..2caf98d5c 100644 --- a/sponge/src/main/java/me/lucko/luckperms/LPSpongePlugin.java +++ b/sponge/src/main/java/me/lucko/luckperms/LPSpongePlugin.java @@ -26,19 +26,21 @@ import com.google.inject.Inject; import lombok.Getter; import me.lucko.luckperms.api.LuckPermsApi; import me.lucko.luckperms.api.implementation.ApiProvider; +import me.lucko.luckperms.commands.Sender; import me.lucko.luckperms.constants.Message; -import me.lucko.luckperms.data.Datastore; -import me.lucko.luckperms.data.methods.FlatfileDatastore; -import me.lucko.luckperms.data.methods.MySQLDatastore; -import me.lucko.luckperms.data.methods.SQLiteDatastore; +import me.lucko.luckperms.constants.Permission; +import me.lucko.luckperms.core.LPConfiguration; +import me.lucko.luckperms.core.UuidCache; import me.lucko.luckperms.groups.GroupManager; import me.lucko.luckperms.runnables.UpdateTask; +import me.lucko.luckperms.storage.Datastore; +import me.lucko.luckperms.storage.methods.FlatfileDatastore; +import me.lucko.luckperms.storage.methods.MySQLDatastore; +import me.lucko.luckperms.storage.methods.SQLiteDatastore; import me.lucko.luckperms.tracks.TrackManager; import me.lucko.luckperms.users.SpongeUserManager; import me.lucko.luckperms.users.UserManager; -import me.lucko.luckperms.utils.LPConfiguration; -import me.lucko.luckperms.utils.LogUtil; -import me.lucko.luckperms.utils.UuidCache; +import me.lucko.luckperms.utils.LogFactory; import org.slf4j.Logger; import org.spongepowered.api.Game; import org.spongepowered.api.Sponge; @@ -57,10 +59,7 @@ import org.spongepowered.api.text.Text; import java.io.File; import java.nio.file.Path; -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.UUID; +import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @@ -80,6 +79,7 @@ public class LPSpongePlugin implements LuckPermsPlugin { private Scheduler scheduler = Sponge.getScheduler(); + private final Set ignoringLogs = new HashSet<>(); private LPConfiguration configuration; private UserManager userManager; private GroupManager groupManager; @@ -90,7 +90,7 @@ public class LPSpongePlugin implements LuckPermsPlugin { @Listener public void onEnable(GamePreInitializationEvent event) { - log = LogUtil.wrap(logger); + log = LogFactory.wrap(logger); getLog().info("Loading configuration..."); configuration = new SpongeConfig(this); @@ -102,7 +102,6 @@ public class LPSpongePlugin implements LuckPermsPlugin { getLog().info("Registering commands..."); CommandManager cmdService = Sponge.getCommandManager(); cmdService.register(this, new SpongeCommand(this), "luckperms", "perms", "lp", "permissions", "p", "perm"); - registerPermissions(); getLog().info("Detecting storage method..."); final String storageMethod = configuration.getStorageMethod(); @@ -143,6 +142,8 @@ public class LPSpongePlugin implements LuckPermsPlugin { .submit(LPSpongePlugin.this); } + scheduler.createTaskBuilder().intervalTicks(1L).execute(SpongeSenderFactory.get()).submit(this); + getLog().info("Registering API..."); final ApiProvider provider = new ApiProvider(this); LuckPerms.registerProvider(provider); @@ -162,7 +163,24 @@ public class LPSpongePlugin implements LuckPermsPlugin { @Listener public void onPostInit(GamePostInitializationEvent event) { - registerPermissions(); + // register permissions + Optional ps = game.getServiceManager().provide(PermissionService.class); + if (!ps.isPresent()) { + getLog().warn("Unable to register all LuckPerms permissions. PermissionService not available."); + return; + } + + final PermissionService p = ps.get(); + + Optional builder = p.newDescriptionBuilder(this); + if (!builder.isPresent()) { + getLog().warn("Unable to register all LuckPerms permissions. Description Builder not available."); + return; + } + + for (Permission perm : Permission.values()) { + registerPermission(p, perm.getNode()); + } } @SuppressWarnings("ResultOfMethodCallIgnored") @@ -193,6 +211,11 @@ public class LPSpongePlugin implements LuckPermsPlugin { return game.getServer().getOnlinePlayers().stream().map(Player::getName).collect(Collectors.toList()); } + @Override + public List getSenders() { + return game.getServer().getOnlinePlayers().stream().map(s -> SpongeSenderFactory.get().wrap(s)).collect(Collectors.toList()); + } + @Override public List getPossiblePermissions() { Optional p = game.getServiceManager().provide(PermissionService.class); @@ -217,70 +240,6 @@ public class LPSpongePlugin implements LuckPermsPlugin { scheduler.createTaskBuilder().execute(r).submit(LPSpongePlugin.this); } - private void registerPermissions() { - Optional ps = game.getServiceManager().provide(PermissionService.class); - if (!ps.isPresent()) { - getLog().warn("Unable to register all LuckPerms permissions. PermissionService not available."); - return; - } - - final PermissionService p = ps.get(); - - Optional builder = p.newDescriptionBuilder(this); - if (!builder.isPresent()) { - getLog().warn("Unable to register all LuckPerms permissions. Description Builder not available."); - return; - } - - registerPermission(p, "luckperms.sync"); - registerPermission(p, "luckperms.info"); - registerPermission(p, "luckperms.debug"); - registerPermission(p, "luckperms.creategroup"); - registerPermission(p, "luckperms.deletegroup"); - registerPermission(p, "luckperms.listgroups"); - registerPermission(p, "luckperms.createtrack"); - registerPermission(p, "luckperms.deletetrack"); - registerPermission(p, "luckperms.listtracks"); - registerPermission(p, "luckperms.user.info"); - registerPermission(p, "luckperms.user.getuuid"); - registerPermission(p, "luckperms.user.listnodes"); - registerPermission(p, "luckperms.user.haspermission"); - registerPermission(p, "luckperms.user.inheritspermission"); - registerPermission(p, "luckperms.user.setpermission"); - registerPermission(p, "luckperms.user.unsetpermission"); - registerPermission(p, "luckperms.user.addgroup"); - registerPermission(p, "luckperms.user.removegroup"); - registerPermission(p, "luckperms.user.settemppermission"); - registerPermission(p, "luckperms.user.unsettemppermission"); - registerPermission(p, "luckperms.user.addtempgroup"); - registerPermission(p, "luckperms.user.removetempgroup"); - registerPermission(p, "luckperms.user.setprimarygroup"); - registerPermission(p, "luckperms.user.showtracks"); - registerPermission(p, "luckperms.user.promote"); - registerPermission(p, "luckperms.user.demote"); - registerPermission(p, "luckperms.user.showpos"); - registerPermission(p, "luckperms.user.clear"); - registerPermission(p, "luckperms.group.info"); - registerPermission(p, "luckperms.group.listnodes"); - registerPermission(p, "luckperms.group.haspermission"); - registerPermission(p, "luckperms.group.inheritspermission"); - registerPermission(p, "luckperms.group.setpermission"); - registerPermission(p, "luckperms.group.unsetpermission"); - registerPermission(p, "luckperms.group.setinherit"); - registerPermission(p, "luckperms.group.unsetinherit"); - registerPermission(p, "luckperms.group.settemppermission"); - registerPermission(p, "luckperms.group.unsettemppermission"); - registerPermission(p, "luckperms.group.settempinherit"); - registerPermission(p, "luckperms.group.unsettempinherit"); - registerPermission(p, "luckperms.group.showtracks"); - registerPermission(p, "luckperms.group.clear"); - registerPermission(p, "luckperms.track.info"); - registerPermission(p, "luckperms.track.append"); - registerPermission(p, "luckperms.track.insert"); - registerPermission(p, "luckperms.track.remove"); - registerPermission(p, "luckperms.track.clear"); - } - private void registerPermission(PermissionService p, String node) { Optional builder = p.newDescriptionBuilder(this); if (!builder.isPresent()) return; diff --git a/sponge/src/main/java/me/lucko/luckperms/SpongeCommand.java b/sponge/src/main/java/me/lucko/luckperms/SpongeCommand.java index ee31f19dc..7bfc2ef7f 100644 --- a/sponge/src/main/java/me/lucko/luckperms/SpongeCommand.java +++ b/sponge/src/main/java/me/lucko/luckperms/SpongeCommand.java @@ -22,37 +22,35 @@ package me.lucko.luckperms; +import me.lucko.luckperms.api.data.Callback; import me.lucko.luckperms.commands.CommandManager; -import me.lucko.luckperms.commands.SenderFactory; -import me.lucko.luckperms.utils.Patterns; +import me.lucko.luckperms.constants.Patterns; import org.spongepowered.api.command.CommandCallable; import org.spongepowered.api.command.CommandException; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.text.Text; -import org.spongepowered.api.text.serializer.TextSerializers; import java.util.Arrays; import java.util.List; import java.util.Optional; +@SuppressWarnings("NullableProblems") class SpongeCommand extends CommandManager implements CommandCallable { - private static final Factory FACTORY = new Factory(); - SpongeCommand(LuckPermsPlugin plugin) { super(plugin); } @Override public CommandResult process(CommandSource source, String s) throws CommandException { - onCommand(FACTORY.wrap(source), "perms", Arrays.asList(Patterns.SPACE.split(s))); + onCommand(SpongeSenderFactory.get().wrap(source), "perms", Arrays.asList(Patterns.SPACE.split(s)), Callback.empty()); return CommandResult.success(); } @Override public List getSuggestions(CommandSource source, String s) throws CommandException { // TODO: fix this so it actually works - return onTabComplete(FACTORY.wrap(source), Arrays.asList(Patterns.SPACE.split(s))); + return onTabComplete(SpongeSenderFactory.get().wrap(source), Arrays.asList(Patterns.SPACE.split(s))); } @Override @@ -74,18 +72,4 @@ class SpongeCommand extends CommandManager implements CommandCallable { public Text getUsage(CommandSource source) { return Text.of("/perms"); } - - private static class Factory extends SenderFactory { - - @SuppressWarnings("deprecation") - @Override - protected void sendMessage(CommandSource source, String s) { - source.sendMessage(TextSerializers.LEGACY_FORMATTING_CODE.deserialize(s)); - } - - @Override - protected boolean hasPermission(CommandSource source, String node) { - return source.hasPermission(node); - } - } } diff --git a/sponge/src/main/java/me/lucko/luckperms/SpongeConfig.java b/sponge/src/main/java/me/lucko/luckperms/SpongeConfig.java index 3b8375a1d..b3e49aaf5 100644 --- a/sponge/src/main/java/me/lucko/luckperms/SpongeConfig.java +++ b/sponge/src/main/java/me/lucko/luckperms/SpongeConfig.java @@ -22,8 +22,8 @@ package me.lucko.luckperms; -import me.lucko.luckperms.utils.LPConfiguration; -import me.lucko.luckperms.utils.Patterns; +import me.lucko.luckperms.constants.Patterns; +import me.lucko.luckperms.core.LPConfiguration; import ninja.leaping.configurate.ConfigurationNode; import ninja.leaping.configurate.commented.CommentedConfigurationNode; import ninja.leaping.configurate.hocon.HoconConfigurationLoader; diff --git a/sponge/src/main/java/me/lucko/luckperms/SpongeListener.java b/sponge/src/main/java/me/lucko/luckperms/SpongeListener.java index 7e6c9dfb9..3cdee7f9e 100644 --- a/sponge/src/main/java/me/lucko/luckperms/SpongeListener.java +++ b/sponge/src/main/java/me/lucko/luckperms/SpongeListener.java @@ -58,7 +58,7 @@ public class SpongeListener extends AbstractListener { @Listener public void onClientLogin(ClientConnectionEvent.Login e) { final GameProfile player = e.getProfile(); - final User user = plugin.getUserManager().getUser(plugin.getUuidCache().getUUID(player.getUniqueId())); + final User user = plugin.getUserManager().get(plugin.getUuidCache().getUUID(player.getUniqueId())); if (user == null) { e.setCancelled(true); diff --git a/sponge/src/main/java/me/lucko/luckperms/SpongeSenderFactory.java b/sponge/src/main/java/me/lucko/luckperms/SpongeSenderFactory.java new file mode 100644 index 000000000..2bf7dccd2 --- /dev/null +++ b/sponge/src/main/java/me/lucko/luckperms/SpongeSenderFactory.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2016 Lucko (Luck) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package me.lucko.luckperms; + +import lombok.AccessLevel; +import lombok.NoArgsConstructor; +import me.lucko.luckperms.commands.SenderFactory; +import me.lucko.luckperms.constants.Constants; +import org.spongepowered.api.command.CommandSource; +import org.spongepowered.api.entity.living.player.Player; +import org.spongepowered.api.text.serializer.TextSerializers; + +import java.util.UUID; + +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class SpongeSenderFactory extends SenderFactory { + private static SpongeSenderFactory instance = null; + public static SpongeSenderFactory get() { + if (instance == null){ + instance = new SpongeSenderFactory(); + } + return instance; + } + + @Override + protected String getName(CommandSource source) { + if (source instanceof Player) { + return source.getName(); + } + return Constants.getConsoleName(); + } + + @Override + protected UUID getUuid(CommandSource source) { + if (source instanceof Player) { + return ((Player) source).getUniqueId(); + } + return Constants.getConsoleUUID(); + } + + @SuppressWarnings("deprecation") + @Override + protected void sendMessage(CommandSource source, String s) { + source.sendMessage(TextSerializers.LEGACY_FORMATTING_CODE.deserialize(s)); + } + + @Override + protected boolean hasPermission(CommandSource source, String node) { + return source.hasPermission(node); + } +} diff --git a/sponge/src/main/java/me/lucko/luckperms/users/SpongeUserManager.java b/sponge/src/main/java/me/lucko/luckperms/users/SpongeUserManager.java index 78aa84a66..d787b036c 100644 --- a/sponge/src/main/java/me/lucko/luckperms/users/SpongeUserManager.java +++ b/sponge/src/main/java/me/lucko/luckperms/users/SpongeUserManager.java @@ -37,31 +37,31 @@ public class SpongeUserManager extends UserManager { } @Override - public void unloadUser(User user) { + public void unload(User user) { if (user != null) { Optional p = plugin.getGame().getServer().getPlayer(plugin.getUuidCache().getExternalUUID(user.getUuid())); if (p.isPresent()) { p.get().getSubjectData().clearParents(); p.get().getSubjectData().clearPermissions(); } - getUsers().remove(user.getUuid()); + getAll().remove(user.getUuid()); } } @Override - public void cleanupUser(User user) { + public void cleanup(User user) { if (plugin.getGame().getServer().getPlayer(plugin.getUuidCache().getExternalUUID(user.getUuid())).isPresent()) { - unloadUser(user); + unload(user); } } @Override - public User makeUser(UUID uuid) { + public User make(UUID uuid) { return new SpongeUser(uuid, plugin); } @Override - public User makeUser(UUID uuid, String username) { + public User make(UUID uuid, String username) { return new SpongeUser(uuid, username, plugin); } diff --git a/sponge/src/main/java/me/lucko/luckperms/utils/VersionUtil.java b/sponge/src/main/java/me/lucko/luckperms/utils/VersionUtil.java index 61aae8733..aa1bf4d15 100644 --- a/sponge/src/main/java/me/lucko/luckperms/utils/VersionUtil.java +++ b/sponge/src/main/java/me/lucko/luckperms/utils/VersionUtil.java @@ -54,7 +54,7 @@ public class VersionUtil extends ClassTransformer { attribute.setAnnotation(annotation); CtMethod getVersionMethod = clazz.getDeclaredMethod("getVersion"); - CtMethod hackedVersionMethod = CtNewMethod.make("public String getVersion() { return \"" + this.version + "\"; }", clazz); + CtMethod hackedVersionMethod = CtNewMethod.make("public String getVersion() { return \"" + version + "\"; }", clazz); clazz.removeMethod(getVersionMethod); clazz.addMethod(hackedVersionMethod); }