mirror of
https://github.com/LuckPerms/LuckPerms.git
synced 2026-11-25 08:44:21 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3006e58209 |
No files matched your search
+2
-2
@@ -10,7 +10,7 @@ subprojects {
|
||||
apply plugin: 'org.cadixdev.licenser'
|
||||
|
||||
group = 'me.lucko.luckperms'
|
||||
version = '5.4-SNAPSHOT'
|
||||
version = '5.3-SNAPSHOT'
|
||||
|
||||
sourceCompatibility = 1.8
|
||||
targetCompatibility = 1.8
|
||||
@@ -39,7 +39,7 @@ subprojects {
|
||||
}
|
||||
|
||||
project.ext.majorVersion = '5'
|
||||
project.ext.minorVersion = '4'
|
||||
project.ext.minorVersion = '3'
|
||||
project.ext.patchVersion = determinePatchVersion()
|
||||
project.ext.apiVersion = project.ext.majorVersion + '.' + project.ext.minorVersion
|
||||
project.ext.fullVersion = project.ext.apiVersion + '.' + project.ext.patchVersion
|
||||
|
||||
+1
-1
@@ -17,7 +17,7 @@ dependencies {
|
||||
exclude(module: 'adventure-api')
|
||||
exclude(module: 'adventure-nbt')
|
||||
}
|
||||
compileOnly 'me.lucko:commodore:1.12'
|
||||
compileOnly 'me.lucko:commodore:1.11'
|
||||
compileOnly('net.milkbowl.vault:VaultAPI:1.7') {
|
||||
exclude(module: 'bukkit')
|
||||
}
|
||||
|
||||
@@ -27,7 +27,6 @@ package me.lucko.luckperms.bukkit;
|
||||
|
||||
import me.lucko.luckperms.bukkit.util.NullSafeConsoleCommandSender;
|
||||
import me.lucko.luckperms.common.loader.LoaderBootstrap;
|
||||
import me.lucko.luckperms.common.plugin.bootstrap.BootstrappedWithLoader;
|
||||
import me.lucko.luckperms.common.plugin.bootstrap.LuckPermsBootstrap;
|
||||
import me.lucko.luckperms.common.plugin.classpath.ClassPathAppender;
|
||||
import me.lucko.luckperms.common.plugin.classpath.JarInJarClassPathAppender;
|
||||
@@ -57,7 +56,7 @@ import java.util.logging.Logger;
|
||||
/**
|
||||
* Bootstrap plugin for LuckPerms running on Bukkit.
|
||||
*/
|
||||
public class LPBukkitBootstrap implements LuckPermsBootstrap, LoaderBootstrap, BootstrappedWithLoader {
|
||||
public class LPBukkitBootstrap implements LuckPermsBootstrap, LoaderBootstrap {
|
||||
private final JavaPlugin loader;
|
||||
|
||||
/**
|
||||
@@ -112,7 +111,6 @@ public class LPBukkitBootstrap implements LuckPermsBootstrap, LoaderBootstrap, B
|
||||
|
||||
// provide adapters
|
||||
|
||||
@Override
|
||||
public JavaPlugin getLoader() {
|
||||
return this.loader;
|
||||
}
|
||||
|
||||
@@ -57,9 +57,6 @@ luckperms {
|
||||
applyedits {
|
||||
code brigadier:string single_word;
|
||||
}
|
||||
trusteditor {
|
||||
id brigadier:string single_word;
|
||||
}
|
||||
creategroup {
|
||||
name brigadier:string single_word {
|
||||
weight brigadier:integer {
|
||||
|
||||
@@ -27,7 +27,6 @@ package me.lucko.luckperms.bungee;
|
||||
|
||||
import me.lucko.luckperms.bungee.util.RedisBungeeUtil;
|
||||
import me.lucko.luckperms.common.loader.LoaderBootstrap;
|
||||
import me.lucko.luckperms.common.plugin.bootstrap.BootstrappedWithLoader;
|
||||
import me.lucko.luckperms.common.plugin.bootstrap.LuckPermsBootstrap;
|
||||
import me.lucko.luckperms.common.plugin.classpath.ClassPathAppender;
|
||||
import me.lucko.luckperms.common.plugin.classpath.JarInJarClassPathAppender;
|
||||
@@ -57,7 +56,7 @@ import java.util.logging.Logger;
|
||||
/**
|
||||
* Bootstrap plugin for LuckPerms running on BungeeCord.
|
||||
*/
|
||||
public class LPBungeeBootstrap implements LuckPermsBootstrap, LoaderBootstrap, BootstrappedWithLoader {
|
||||
public class LPBungeeBootstrap implements LuckPermsBootstrap, LoaderBootstrap {
|
||||
private final Plugin loader;
|
||||
|
||||
/**
|
||||
@@ -102,7 +101,6 @@ public class LPBungeeBootstrap implements LuckPermsBootstrap, LoaderBootstrap, B
|
||||
|
||||
// provide adapters
|
||||
|
||||
@Override
|
||||
public Plugin getLoader() {
|
||||
return this.loader;
|
||||
}
|
||||
|
||||
@@ -29,7 +29,6 @@ import com.github.benmanes.caffeine.cache.LoadingCache;
|
||||
|
||||
import me.lucko.luckperms.bungee.LPBungeePlugin;
|
||||
import me.lucko.luckperms.common.context.manager.ContextManager;
|
||||
import me.lucko.luckperms.common.context.manager.InlineQueryOptionsSupplier;
|
||||
import me.lucko.luckperms.common.context.manager.QueryOptionsSupplier;
|
||||
import me.lucko.luckperms.common.util.CaffeineFactory;
|
||||
|
||||
@@ -61,10 +60,9 @@ public class BungeeContextManager extends ContextManager<ProxiedPlayer, ProxiedP
|
||||
throw new NullPointerException("subject");
|
||||
}
|
||||
|
||||
return new InlineQueryOptionsSupplier<>(subject, this.contextsCache);
|
||||
return new InlineQueryOptionsSupplier(subject, this.contextsCache);
|
||||
}
|
||||
|
||||
// override getContext, getQueryOptions and invalidateCache to skip the QueryOptionsSupplier
|
||||
@Override
|
||||
public ImmutableContextSet getContext(ProxiedPlayer subject) {
|
||||
return getQueryOptions(subject).context();
|
||||
@@ -85,4 +83,18 @@ public class BungeeContextManager extends ContextManager<ProxiedPlayer, ProxiedP
|
||||
return formQueryOptions(contextSet);
|
||||
}
|
||||
|
||||
private static final class InlineQueryOptionsSupplier implements QueryOptionsSupplier {
|
||||
private final ProxiedPlayer key;
|
||||
private final LoadingCache<ProxiedPlayer, QueryOptions> cache;
|
||||
|
||||
private InlineQueryOptionsSupplier(ProxiedPlayer key, LoadingCache<ProxiedPlayer, QueryOptions> cache) {
|
||||
this.key = key;
|
||||
this.cache = cache;
|
||||
}
|
||||
|
||||
@Override
|
||||
public QueryOptions getQueryOptions() {
|
||||
return this.cache.get(this.key);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,12 +41,8 @@ import me.lucko.luckperms.common.config.ConfigKeys;
|
||||
import me.lucko.luckperms.common.event.AbstractEventBus;
|
||||
import me.lucko.luckperms.common.messaging.LuckPermsMessagingService;
|
||||
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
|
||||
import me.lucko.luckperms.common.plugin.bootstrap.BootstrappedWithLoader;
|
||||
import me.lucko.luckperms.common.plugin.bootstrap.LuckPermsBootstrap;
|
||||
import me.lucko.luckperms.common.plugin.logging.PluginLogger;
|
||||
|
||||
import net.luckperms.api.LuckPerms;
|
||||
import net.luckperms.api.LuckPermsProvider;
|
||||
import net.luckperms.api.actionlog.ActionLogger;
|
||||
import net.luckperms.api.context.ContextManager;
|
||||
import net.luckperms.api.messaging.MessagingService;
|
||||
@@ -97,37 +93,6 @@ public class LuckPermsApiProvider implements LuckPerms {
|
||||
this.metaStackFactory = new ApiMetaStackFactory(plugin);
|
||||
}
|
||||
|
||||
public void ensureApiWasLoadedByPlugin() {
|
||||
LuckPermsBootstrap bootstrap = this.plugin.getBootstrap();
|
||||
ClassLoader pluginClassLoader;
|
||||
if (bootstrap instanceof BootstrappedWithLoader) {
|
||||
pluginClassLoader = ((BootstrappedWithLoader) bootstrap).getLoader().getClass().getClassLoader();
|
||||
} else {
|
||||
pluginClassLoader = bootstrap.getClass().getClassLoader();
|
||||
}
|
||||
|
||||
for (Class<?> apiClass : new Class[]{LuckPerms.class, LuckPermsProvider.class}) {
|
||||
ClassLoader apiClassLoader = apiClass.getClassLoader();
|
||||
|
||||
if (!apiClassLoader.equals(pluginClassLoader)) {
|
||||
String guilty = "unknown";
|
||||
try {
|
||||
guilty = bootstrap.identifyClassLoader(apiClassLoader);
|
||||
} catch (Exception e) {
|
||||
// ignore
|
||||
}
|
||||
|
||||
PluginLogger logger = this.plugin.getLogger();
|
||||
logger.warn("It seems that the LuckPerms API has been (class)loaded by a plugin other than LuckPerms!");
|
||||
logger.warn("The API was loaded by " + apiClassLoader + " (" + guilty + ") and the " +
|
||||
"LuckPerms plugin was loaded by " + pluginClassLoader.toString() + ".");
|
||||
logger.warn("This indicates that the other plugin has incorrectly \"shaded\" the " +
|
||||
"LuckPerms API into its jar file. This can cause errors at runtime and should be fixed.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull String getServerName() {
|
||||
return this.plugin.getConfiguration().get(ConfigKeys.SERVER);
|
||||
|
||||
@@ -38,7 +38,6 @@ import me.lucko.luckperms.common.node.utils.NodeJsonSerializer;
|
||||
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
|
||||
import me.lucko.luckperms.common.sender.Sender;
|
||||
import me.lucko.luckperms.common.storage.Storage;
|
||||
import me.lucko.luckperms.common.util.CompletableFutures;
|
||||
import me.lucko.luckperms.common.util.gson.GsonProvider;
|
||||
import me.lucko.luckperms.common.util.gson.JArray;
|
||||
import me.lucko.luckperms.common.util.gson.JObject;
|
||||
@@ -194,7 +193,7 @@ public abstract class Exporter implements Runnable {
|
||||
}
|
||||
|
||||
// all of the threads have been scheduled now and are running. we just need to wait for them all to complete
|
||||
CompletableFuture<Void> overallFuture = CompletableFutures.allOf(futures);
|
||||
CompletableFuture<Void> overallFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
|
||||
@@ -39,7 +39,6 @@ import me.lucko.luckperms.common.model.User;
|
||||
import me.lucko.luckperms.common.node.utils.NodeJsonSerializer;
|
||||
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
|
||||
import me.lucko.luckperms.common.sender.Sender;
|
||||
import me.lucko.luckperms.common.util.CompletableFutures;
|
||||
import me.lucko.luckperms.common.util.Uuids;
|
||||
|
||||
import net.luckperms.api.event.cause.CreationCause;
|
||||
@@ -261,7 +260,7 @@ public class Importer implements Runnable {
|
||||
}
|
||||
|
||||
// all of the threads have been scheduled now and are running. we just need to wait for them all to complete
|
||||
CompletableFuture<Void> overallFuture = CompletableFutures.allOf(futures);
|
||||
CompletableFuture<Void> overallFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
|
||||
|
||||
this.notify.forEach(s -> Message.IMPORT_INFO.send(s, "All data entries have been processed and scheduled for import - now waiting for the execution to complete."));
|
||||
|
||||
|
||||
+1
-2
@@ -33,7 +33,6 @@ import me.lucko.luckperms.common.calculator.CalculatorFactory;
|
||||
import me.lucko.luckperms.common.calculator.PermissionCalculator;
|
||||
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
|
||||
import me.lucko.luckperms.common.util.CaffeineFactory;
|
||||
import me.lucko.luckperms.common.util.CompletableFutures;
|
||||
|
||||
import net.luckperms.api.cacheddata.CachedData;
|
||||
import net.luckperms.api.cacheddata.CachedDataManager;
|
||||
@@ -242,7 +241,7 @@ public abstract class AbstractCachedDataManager implements CachedDataManager {
|
||||
@Override
|
||||
public @NonNull CompletableFuture<Void> reload() {
|
||||
Set<QueryOptions> keys = this.cache.keySet();
|
||||
return CompletableFutures.allOf(keys.stream().map(this::reload));
|
||||
return CompletableFuture.allOf(keys.stream().map(this::reload).toArray(CompletableFuture[]::new));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+7
-31
@@ -26,14 +26,13 @@
|
||||
package me.lucko.luckperms.common.cacheddata.type;
|
||||
|
||||
import me.lucko.luckperms.common.cacheddata.result.StringResult;
|
||||
import me.lucko.luckperms.common.metastacking.ElementAccumulator;
|
||||
|
||||
import net.luckperms.api.metastacking.MetaStackDefinition;
|
||||
import net.luckperms.api.metastacking.MetaStackElement;
|
||||
import net.luckperms.api.node.ChatMetaType;
|
||||
import net.luckperms.api.node.types.ChatMetaNode;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedList;
|
||||
@@ -43,7 +42,7 @@ import java.util.stream.Collectors;
|
||||
|
||||
public class MetaStackAccumulator<N extends ChatMetaNode<N, ?>> {
|
||||
private final MetaStackDefinition definition;
|
||||
private final List<Entry<N>> entries;
|
||||
private final List<ElementAccumulator<N>> entries;
|
||||
|
||||
public MetaStackAccumulator(MetaStackDefinition definition, ChatMetaType targetType) {
|
||||
this.definition = definition;
|
||||
@@ -51,27 +50,27 @@ public class MetaStackAccumulator<N extends ChatMetaNode<N, ?>> {
|
||||
List<MetaStackElement> elements = definition.getElements();
|
||||
this.entries = new ArrayList<>(elements.size());
|
||||
for (MetaStackElement element : elements) {
|
||||
this.entries.add(new Entry<>(element, targetType));
|
||||
this.entries.add(ElementAccumulator.create(element, targetType));
|
||||
}
|
||||
}
|
||||
|
||||
public void offer(N node) {
|
||||
for (Entry<N> entry : this.entries) {
|
||||
for (ElementAccumulator<N> entry : this.entries) {
|
||||
entry.offer(node);
|
||||
}
|
||||
}
|
||||
|
||||
public List<N> getElements() {
|
||||
return this.entries.stream()
|
||||
.map(Entry::getNode)
|
||||
.map(ElementAccumulator::result)
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public String toFormattedString() {
|
||||
List<String> elements = new LinkedList<>();
|
||||
for (Entry<N> entry : this.entries) {
|
||||
N node = entry.getNode();
|
||||
for (ElementAccumulator<N> entry : this.entries) {
|
||||
N node = entry.result();
|
||||
if (node != null) {
|
||||
elements.add(node.getMetaValue());
|
||||
}
|
||||
@@ -134,27 +133,4 @@ public class MetaStackAccumulator<N extends ChatMetaNode<N, ?>> {
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Entry<N extends ChatMetaNode<?, ?>> {
|
||||
private final MetaStackElement element;
|
||||
private final ChatMetaType type;
|
||||
|
||||
private @Nullable N current = null;
|
||||
|
||||
Entry(MetaStackElement element, ChatMetaType type) {
|
||||
this.element = element;
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public N getNode() {
|
||||
return this.current;
|
||||
}
|
||||
|
||||
public boolean offer(N node) {
|
||||
if (this.element.shouldAccumulate(this.type, node, this.current)) {
|
||||
this.current = node;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -51,7 +51,6 @@ import me.lucko.luckperms.common.commands.misc.SearchCommand;
|
||||
import me.lucko.luckperms.common.commands.misc.SyncCommand;
|
||||
import me.lucko.luckperms.common.commands.misc.TranslationsCommand;
|
||||
import me.lucko.luckperms.common.commands.misc.TreeCommand;
|
||||
import me.lucko.luckperms.common.commands.misc.TrustEditorCommand;
|
||||
import me.lucko.luckperms.common.commands.misc.VerboseCommand;
|
||||
import me.lucko.luckperms.common.commands.track.CreateTrack;
|
||||
import me.lucko.luckperms.common.commands.track.DeleteTrack;
|
||||
@@ -124,7 +123,6 @@ public class CommandManager {
|
||||
.add(new BulkUpdateCommand())
|
||||
.add(new TranslationsCommand())
|
||||
.add(new ApplyEditsCommand())
|
||||
.add(new TrustEditorCommand())
|
||||
.add(new CreateGroup())
|
||||
.add(new DeleteGroup())
|
||||
.add(new ListGroups())
|
||||
|
||||
@@ -44,7 +44,6 @@ public enum CommandPermission {
|
||||
RELOAD_CONFIG("reloadconfig", Type.NONE),
|
||||
BULK_UPDATE("bulkupdate", Type.NONE),
|
||||
APPLY_EDITS("applyedits", Type.NONE),
|
||||
TRUST_EDITOR("trusteditor", Type.NONE),
|
||||
TRANSLATIONS("translations", Type.NONE),
|
||||
|
||||
CREATE_GROUP("creategroup", Type.NONE),
|
||||
|
||||
@@ -86,11 +86,9 @@ public enum CommandSpec {
|
||||
TRANSLATIONS("/%s translations",
|
||||
arg("install", false)
|
||||
),
|
||||
APPLY_EDITS("/%s applyedits <code>",
|
||||
arg("code", true)
|
||||
),
|
||||
TRUST_EDITOR("/%s trusteditor <id>",
|
||||
arg("id", true)
|
||||
APPLY_EDITS("/%s applyedits <code> [target]",
|
||||
arg("code", true),
|
||||
arg("target", false)
|
||||
),
|
||||
|
||||
CREATE_GROUP("/%s creategroup <group>",
|
||||
|
||||
+2
-2
@@ -42,7 +42,6 @@ import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
|
||||
import me.lucko.luckperms.common.sender.Sender;
|
||||
import me.lucko.luckperms.common.util.Predicates;
|
||||
import me.lucko.luckperms.common.webeditor.WebEditorRequest;
|
||||
import me.lucko.luckperms.common.webeditor.WebEditorSession;
|
||||
|
||||
import net.luckperms.api.node.Node;
|
||||
|
||||
@@ -85,7 +84,8 @@ public class HolderEditor<T extends PermissionHolder> extends ChildCommand<T> {
|
||||
|
||||
Message.EDITOR_START.send(sender);
|
||||
|
||||
WebEditorSession.createAndOpen(holders, Collections.emptyList(), sender, label, plugin);
|
||||
WebEditorRequest.generate(holders, Collections.emptyList(), sender, label, plugin)
|
||||
.createSession(plugin, sender);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -42,7 +42,6 @@ import net.luckperms.api.node.Node;
|
||||
import net.luckperms.api.node.types.InheritanceNode;
|
||||
import net.luckperms.api.query.QueryOptions;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -61,23 +60,26 @@ public class GroupInfo extends ChildCommand<Group> {
|
||||
|
||||
Message.GROUP_INFO_GENERAL.send(sender, target.getName(), target.getPlainDisplayName(), target.getWeight());
|
||||
|
||||
Map<Boolean, List<InheritanceNode>> parents = target.normalData().inheritanceAsSortedSet().stream()
|
||||
List<InheritanceNode> parents = target.normalData().inheritanceAsSortedSet().stream()
|
||||
.filter(Node::getValue)
|
||||
.collect(Collectors.groupingBy(Node::hasExpiry, Collectors.toList()));
|
||||
.filter(n -> !n.hasExpiry())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
List<InheritanceNode> temporaryParents = parents.getOrDefault(true, Collections.emptyList());
|
||||
List<InheritanceNode> permanentParents = parents.getOrDefault(false, Collections.emptyList());
|
||||
List<InheritanceNode> tempParents = target.normalData().inheritanceAsSortedSet().stream()
|
||||
.filter(Node::getValue)
|
||||
.filter(Node::hasExpiry)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
if (!permanentParents.isEmpty()) {
|
||||
if (!parents.isEmpty()) {
|
||||
Message.INFO_PARENT_HEADER.send(sender);
|
||||
for (InheritanceNode node : permanentParents) {
|
||||
for (InheritanceNode node : parents) {
|
||||
Message.INFO_PARENT_NODE_ENTRY.send(sender, node);
|
||||
}
|
||||
}
|
||||
|
||||
if (!temporaryParents.isEmpty()) {
|
||||
if (!tempParents.isEmpty()) {
|
||||
Message.INFO_TEMP_PARENT_HEADER.send(sender);
|
||||
for (InheritanceNode node : temporaryParents) {
|
||||
for (InheritanceNode node : tempParents) {
|
||||
Message.INFO_PARENT_TEMPORARY_NODE_ENTRY.send(sender, node);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ public class ApplyEditsCommand extends SingleCommand {
|
||||
return;
|
||||
}
|
||||
|
||||
new WebEditorResponse(code, data).apply(plugin, sender, null, label, ignoreSessionWarning);
|
||||
new WebEditorResponse(code, data).apply(plugin, sender, label, ignoreSessionWarning);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -40,7 +40,6 @@ import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
|
||||
import me.lucko.luckperms.common.sender.Sender;
|
||||
import me.lucko.luckperms.common.util.Predicates;
|
||||
import me.lucko.luckperms.common.webeditor.WebEditorRequest;
|
||||
import me.lucko.luckperms.common.webeditor.WebEditorSession;
|
||||
|
||||
import net.luckperms.api.node.Node;
|
||||
|
||||
@@ -108,7 +107,8 @@ public class EditorCommand extends SingleCommand {
|
||||
|
||||
Message.EDITOR_START.send(sender);
|
||||
|
||||
WebEditorSession.createAndOpen(holders, tracks, sender, label, plugin);
|
||||
WebEditorRequest.generate(holders, tracks, sender, label, plugin)
|
||||
.createSession(plugin, sender);
|
||||
}
|
||||
|
||||
private enum Type {
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
/*
|
||||
* This file is part of LuckPerms, licensed under the MIT License.
|
||||
*
|
||||
* Copyright (c) lucko (Luck) <[email protected]>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* 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.common.commands.misc;
|
||||
|
||||
import me.lucko.luckperms.common.command.abstraction.SingleCommand;
|
||||
import me.lucko.luckperms.common.command.access.CommandPermission;
|
||||
import me.lucko.luckperms.common.command.spec.CommandSpec;
|
||||
import me.lucko.luckperms.common.command.utils.ArgumentList;
|
||||
import me.lucko.luckperms.common.locale.Message;
|
||||
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
|
||||
import me.lucko.luckperms.common.sender.Sender;
|
||||
import me.lucko.luckperms.common.util.Predicates;
|
||||
import me.lucko.luckperms.common.webeditor.socket.WebEditorSocket;
|
||||
|
||||
public class TrustEditorCommand extends SingleCommand {
|
||||
public TrustEditorCommand() {
|
||||
super(CommandSpec.TRUST_EDITOR, "TrustEditor", CommandPermission.TRUST_EDITOR, Predicates.not(1));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(LuckPermsPlugin plugin, Sender sender, ArgumentList args, String label) {
|
||||
String id = args.get(0);
|
||||
|
||||
if (id.isEmpty()) {
|
||||
Message.APPLY_EDITS_INVALID_CODE.send(sender, id);
|
||||
return;
|
||||
}
|
||||
|
||||
WebEditorSocket socket = plugin.getWebEditorStore().sockets().getSocket(sender);
|
||||
if (socket == null) {
|
||||
Message.EDITOR_SOCKET_TRUST_FAILURE.send(sender);
|
||||
return;
|
||||
}
|
||||
|
||||
if (socket.trustConnection(id)) {
|
||||
Message.EDITOR_SOCKET_TRUST_SUCCESS.send(sender);
|
||||
} else {
|
||||
Message.EDITOR_SOCKET_TRUST_FAILURE.send(sender);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shouldDisplay() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,6 @@ import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
|
||||
import me.lucko.luckperms.common.sender.Sender;
|
||||
import me.lucko.luckperms.common.util.Predicates;
|
||||
import me.lucko.luckperms.common.webeditor.WebEditorRequest;
|
||||
import me.lucko.luckperms.common.webeditor.WebEditorSession;
|
||||
|
||||
import net.luckperms.api.node.Node;
|
||||
|
||||
@@ -98,7 +97,8 @@ public class TrackEditor extends ChildCommand<Track> {
|
||||
|
||||
Message.EDITOR_START.send(sender);
|
||||
|
||||
WebEditorSession.createAndOpen(holders, Collections.singletonList(target), sender, label, plugin);
|
||||
WebEditorRequest.generate(holders, Collections.singletonList(target), sender, label, plugin)
|
||||
.createSession(plugin, sender);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -44,7 +44,6 @@ import net.luckperms.api.node.Node;
|
||||
import net.luckperms.api.node.types.InheritanceNode;
|
||||
import net.luckperms.api.query.QueryOptions;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -68,23 +67,26 @@ public class UserInfo extends ChildCommand<User> {
|
||||
plugin.getBootstrap().isPlayerOnline(target.getUniqueId())
|
||||
);
|
||||
|
||||
Map<Boolean, List<InheritanceNode>> parents = target.normalData().inheritanceAsSortedSet().stream()
|
||||
List<InheritanceNode> parents = target.normalData().inheritanceAsSortedSet().stream()
|
||||
.filter(Node::getValue)
|
||||
.collect(Collectors.groupingBy(Node::hasExpiry, Collectors.toList()));
|
||||
.filter(n -> !n.hasExpiry())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
List<InheritanceNode> temporaryParents = parents.getOrDefault(true, Collections.emptyList());
|
||||
List<InheritanceNode> permanentParents = parents.getOrDefault(false, Collections.emptyList());
|
||||
List<InheritanceNode> tempParents = target.normalData().inheritanceAsSortedSet().stream()
|
||||
.filter(Node::getValue)
|
||||
.filter(Node::hasExpiry)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
if (!permanentParents.isEmpty()) {
|
||||
if (!parents.isEmpty()) {
|
||||
Message.INFO_PARENT_HEADER.send(sender);
|
||||
for (InheritanceNode node : permanentParents) {
|
||||
for (InheritanceNode node : parents) {
|
||||
Message.INFO_PARENT_NODE_ENTRY.send(sender, node);
|
||||
}
|
||||
}
|
||||
|
||||
if (!temporaryParents.isEmpty()) {
|
||||
if (!tempParents.isEmpty()) {
|
||||
Message.INFO_TEMP_PARENT_HEADER.send(sender);
|
||||
for (InheritanceNode node : temporaryParents) {
|
||||
for (InheritanceNode node : tempParents) {
|
||||
Message.INFO_PARENT_TEMPORARY_NODE_ENTRY.send(sender, node);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -692,12 +692,7 @@ public final class ConfigKeys {
|
||||
/**
|
||||
* The URL of the bytebin instance used to upload data
|
||||
*/
|
||||
public static final ConfigKey<String> BYTEBIN_URL = stringKey("bytebin-url", "https://usercontent.luckperms.net/");
|
||||
|
||||
/**
|
||||
* The host of the bytesocks instance used to communicate with
|
||||
*/
|
||||
public static final ConfigKey<String> BYTESOCKS_HOST = stringKey("bytesocks-host", "usersockets.luckperms.net");
|
||||
public static final ConfigKey<String> BYTEBIN_URL = stringKey("bytebin-url", "https://bytebin.lucko.me/");
|
||||
|
||||
/**
|
||||
* The URL of the web editor
|
||||
|
||||
+10
-18
@@ -135,28 +135,16 @@ public abstract class ContextManager<S, P extends S> {
|
||||
this.calculators.remove(calculator);
|
||||
}
|
||||
|
||||
protected void callContextCalculator(ContextCalculator<? super S> calculator, S subject, ContextConsumer consumer) {
|
||||
try {
|
||||
calculator.calculate(subject, consumer);
|
||||
} catch (Throwable e) {
|
||||
this.plugin.getLogger().warn("An exception was thrown by " + getCalculatorClass(calculator) + " whilst calculating the context of subject " + subject, e);
|
||||
}
|
||||
}
|
||||
|
||||
protected void callStaticContextCalculator(StaticContextCalculator calculator, ContextConsumer consumer) {
|
||||
try {
|
||||
calculator.calculate(consumer);
|
||||
} catch (Throwable e) {
|
||||
this.plugin.getLogger().warn("An exception was thrown by " + getCalculatorClass(calculator) + " whilst calculating static contexts", e);
|
||||
}
|
||||
}
|
||||
|
||||
protected QueryOptions calculate(S subject) {
|
||||
ImmutableContextSet.Builder accumulator = new ImmutableContextSetImpl.BuilderImpl();
|
||||
ContextConsumer consumer = accumulator::add;
|
||||
|
||||
for (ContextCalculator<? super S> calculator : this.calculators.calculators()) {
|
||||
callContextCalculator(calculator, subject, consumer);
|
||||
try {
|
||||
calculator.calculate(subject, consumer);
|
||||
} catch (Throwable e) {
|
||||
this.plugin.getLogger().warn("An exception was thrown by " + getCalculatorClass(calculator) + " whilst calculating the context of subject " + subject, e);
|
||||
}
|
||||
}
|
||||
|
||||
return formQueryOptions(subject, accumulator.build());
|
||||
@@ -167,7 +155,11 @@ public abstract class ContextManager<S, P extends S> {
|
||||
ContextConsumer consumer = accumulator::add;
|
||||
|
||||
for (StaticContextCalculator calculator : this.calculators.staticCalculators()) {
|
||||
callStaticContextCalculator(calculator, consumer);
|
||||
try {
|
||||
calculator.calculate(consumer);
|
||||
} catch (Throwable e) {
|
||||
this.plugin.getLogger().warn("An exception was thrown by " + getCalculatorClass(calculator) + " whilst calculating static contexts", e);
|
||||
}
|
||||
}
|
||||
|
||||
return formQueryOptions(accumulator.build());
|
||||
|
||||
@@ -128,8 +128,8 @@ public enum Dependency {
|
||||
COMMODORE(
|
||||
"me{}lucko",
|
||||
"commodore",
|
||||
"1.12",
|
||||
"rLpLs20OG9TETCx1QzA+I+LY8P+p6Q9fUjLSmJcl2Kk=",
|
||||
"1.11",
|
||||
"TxlkwmLE04ipLfI4HSyC0mzYt/8gTSDBpfCSk+kiaZI=",
|
||||
Relocation.of("commodore", "me{}lucko{}commodore")
|
||||
),
|
||||
COMMODORE_FILE(
|
||||
|
||||
@@ -40,8 +40,8 @@ import me.lucko.luckperms.common.model.HolderType;
|
||||
import me.lucko.luckperms.common.model.PermissionHolder;
|
||||
import me.lucko.luckperms.common.model.Track;
|
||||
import me.lucko.luckperms.common.model.User;
|
||||
import me.lucko.luckperms.common.model.nodemap.MutateResult;
|
||||
import me.lucko.luckperms.common.sender.Sender;
|
||||
import me.lucko.luckperms.common.util.Difference;
|
||||
|
||||
import net.luckperms.api.actionlog.Action;
|
||||
import net.luckperms.api.event.LuckPermsEvent;
|
||||
@@ -226,7 +226,7 @@ public final class EventDispatcher {
|
||||
postAsync(LogReceiveEvent.class, id, entry);
|
||||
}
|
||||
|
||||
public void dispatchNodeChanges(PermissionHolder target, DataType dataType, Difference<Node> changes) {
|
||||
public void dispatchNodeChanges(PermissionHolder target, DataType dataType, MutateResult changes) {
|
||||
if (!this.eventBus.shouldPost(NodeAddEvent.class) && !this.eventBus.shouldPost(NodeRemoveEvent.class)) {
|
||||
return;
|
||||
}
|
||||
@@ -239,15 +239,15 @@ public final class EventDispatcher {
|
||||
ImmutableSet<Node> state = target.getData(dataType).asImmutableSet();
|
||||
|
||||
// call an event for each recorded change
|
||||
for (Difference.Change<Node> change : changes.getChanges()) {
|
||||
Class<? extends NodeMutateEvent> type = change.type() == Difference.ChangeType.ADD ?
|
||||
for (MutateResult.Change change : changes.getChanges()) {
|
||||
Class<? extends NodeMutateEvent> type = change.getType() == MutateResult.ChangeType.ADD ?
|
||||
NodeAddEvent.class : NodeRemoveEvent.class;
|
||||
|
||||
postAsync(type, proxy, dataType, state, change.value());
|
||||
postAsync(type, proxy, dataType, state, change.getNode());
|
||||
}
|
||||
}
|
||||
|
||||
public void dispatchNodeClear(PermissionHolder target, DataType dataType, Difference<Node> changes) {
|
||||
public void dispatchNodeClear(PermissionHolder target, DataType dataType, MutateResult changes) {
|
||||
if (!this.eventBus.shouldPost(NodeClearEvent.class)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -83,21 +83,15 @@ public class BytebinClient extends AbstractHttpClient {
|
||||
*
|
||||
* @param buf the compressed content
|
||||
* @param contentType the type of the content
|
||||
* @param userAgentExtra extra string to append to the user agent
|
||||
* @return the key of the resultant content
|
||||
* @throws IOException if an error occurs
|
||||
*/
|
||||
public Content postContent(byte[] buf, MediaType contentType, String userAgentExtra) throws IOException, UnsuccessfulRequestException {
|
||||
public Content postContent(byte[] buf, MediaType contentType) throws IOException, UnsuccessfulRequestException {
|
||||
RequestBody body = RequestBody.create(contentType, buf);
|
||||
|
||||
String userAgent = this.userAgent;
|
||||
if (userAgentExtra != null) {
|
||||
userAgent += "/" + userAgentExtra;
|
||||
}
|
||||
|
||||
Request.Builder requestBuilder = new Request.Builder()
|
||||
.url(this.url + "post")
|
||||
.header("User-Agent", userAgent)
|
||||
.header("User-Agent", this.userAgent)
|
||||
.header("Content-Encoding", "gzip");
|
||||
|
||||
Request request = requestBuilder.post(body).build();
|
||||
@@ -110,10 +104,6 @@ public class BytebinClient extends AbstractHttpClient {
|
||||
}
|
||||
}
|
||||
|
||||
public Content postContent(byte[] buf, MediaType contentType) throws IOException, UnsuccessfulRequestException {
|
||||
return postContent(buf, contentType, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* GETs json content from bytebin
|
||||
*
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
/*
|
||||
* This file is part of LuckPerms, licensed under the MIT License.
|
||||
*
|
||||
* Copyright (c) lucko (Luck) <[email protected]>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* 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.common.http;
|
||||
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
import okhttp3.WebSocket;
|
||||
import okhttp3.WebSocketListener;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Objects;
|
||||
|
||||
public class BytesocksClient extends AbstractHttpClient {
|
||||
|
||||
/* The bytesocks urls */
|
||||
private final String httpUrl;
|
||||
private final String wsUrl;
|
||||
|
||||
/** The client user agent */
|
||||
private final String userAgent;
|
||||
|
||||
/**
|
||||
* Creates a new bytesocks instance
|
||||
*
|
||||
* @param host the bytesocks host
|
||||
* @param userAgent the client user agent string
|
||||
*/
|
||||
public BytesocksClient(OkHttpClient okHttpClient, String host, String userAgent) {
|
||||
super(okHttpClient);
|
||||
|
||||
this.httpUrl = "https://" + host + "/";
|
||||
this.wsUrl = "wss://" + host + "/";
|
||||
this.userAgent = userAgent;
|
||||
}
|
||||
|
||||
public Socket createSocket(WebSocketListener listener) throws IOException, UnsuccessfulRequestException {
|
||||
Request createRequest = new Request.Builder()
|
||||
.url(this.httpUrl + "create")
|
||||
.header("User-Agent", this.userAgent)
|
||||
.build();
|
||||
|
||||
String id;
|
||||
try (Response response = makeHttpRequest(createRequest)) {
|
||||
if (response.code() != 201) {
|
||||
throw new UnsuccessfulRequestException(response);
|
||||
}
|
||||
|
||||
id = Objects.requireNonNull(response.header("Location"));
|
||||
}
|
||||
|
||||
Request socketRequest = new Request.Builder()
|
||||
.url(this.wsUrl + id)
|
||||
.header("User-Agent", this.userAgent)
|
||||
.build();
|
||||
|
||||
return new Socket(id, this.okHttp.newWebSocket(socketRequest, listener));
|
||||
}
|
||||
|
||||
public static final class Socket {
|
||||
private final String channelId;
|
||||
private final WebSocket socket;
|
||||
|
||||
public Socket(String channelId, WebSocket socket) {
|
||||
this.channelId = channelId;
|
||||
this.socket = socket;
|
||||
}
|
||||
|
||||
public String channelId() {
|
||||
return this.channelId;
|
||||
}
|
||||
|
||||
public WebSocket socket() {
|
||||
return this.socket;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1159,97 +1159,6 @@ public interface Message {
|
||||
.clickEvent(ClickEvent.openUrl(url))
|
||||
);
|
||||
|
||||
Args0 EDITOR_SOCKET_CONNECTED = () -> prefixed(translatable()
|
||||
// "&bEditor window connected successfully."
|
||||
.color(AQUA)
|
||||
.key("luckperms.command.editor.socket.connected")
|
||||
.append(FULL_STOP)
|
||||
);
|
||||
|
||||
Args0 EDITOR_SOCKET_RECONNECTED = () -> prefixed(translatable()
|
||||
// "&7Editor window reconnected successfully."
|
||||
.color(GRAY)
|
||||
.key("luckperms.command.editor.socket.reconnected")
|
||||
.append(FULL_STOP)
|
||||
);
|
||||
|
||||
Args0 EDITOR_SOCKET_CHANGES_RECEIVED = () -> prefixed(translatable()
|
||||
// "&7Changes have been received from the connected web editor session."
|
||||
.color(GRAY)
|
||||
.key("luckperms.command.editor.socket.changes-received")
|
||||
.append(FULL_STOP)
|
||||
);
|
||||
|
||||
Args4<String, String, String, Boolean> EDITOR_SOCKET_UNTRUSTED = (nonce, browser, cmdLabel, console) -> join(newline(),
|
||||
// "&bAn editor window has connected, but it is not yet trusted."
|
||||
// "&8(&7session id = &faaaaa&7, browser = &fChrome on Windows 10&8)"
|
||||
// "&7If it was you, &aclick here&7 to trust the session!"
|
||||
// "&7If it was you, run &a/lp trusteditor aaaaa&7 to trust the session!"
|
||||
prefixed(translatable()
|
||||
.key("luckperms.command.editor.socket.untrusted")
|
||||
.color(AQUA)
|
||||
.append(FULL_STOP)),
|
||||
prefixed(text()
|
||||
.color(DARK_GRAY)
|
||||
.append(OPEN_BRACKET)
|
||||
.append(translatable()
|
||||
.key("luckperms.command.editor.socket.untrusted.sessioninfo")
|
||||
.color(GRAY)
|
||||
.args(
|
||||
text(nonce, WHITE),
|
||||
text(browser, WHITE)
|
||||
)
|
||||
)
|
||||
.append(CLOSE_BRACKET)
|
||||
),
|
||||
prefixed(text()
|
||||
.color(GRAY)
|
||||
.apply(builder -> {
|
||||
String command = "/" + cmdLabel + " trusteditor " + nonce;
|
||||
if (console) {
|
||||
builder.append(translatable()
|
||||
.key("luckperms.command.editor.socket.untrusted.prompt.runcommand")
|
||||
.args(text(command, GREEN))
|
||||
.build()
|
||||
);
|
||||
} else {
|
||||
builder.append(translatable()
|
||||
.key("luckperms.command.editor.socket.untrusted.prompt.click")
|
||||
.args(translatable()
|
||||
.key("luckperms.command.editor.socket.untrusted.prompt.click.action")
|
||||
.color(GREEN)
|
||||
.clickEvent(ClickEvent.runCommand(command))
|
||||
)
|
||||
.build()
|
||||
);
|
||||
}
|
||||
}))
|
||||
);
|
||||
|
||||
Args0 EDITOR_SOCKET_TRUST_SUCCESS = () -> join(newline(),
|
||||
// "&aThe editor session has been marked as trusted."
|
||||
// "&7In the future, connections from the same browser will be trusted automatically."
|
||||
// "&7The plugin will now attempt to establish a connection with the editor..."
|
||||
prefixed(translatable()
|
||||
.key("luckperms.command.editor.socket.trust.success")
|
||||
.color(GREEN)
|
||||
.append(FULL_STOP)),
|
||||
prefixed(translatable()
|
||||
.key("luckperms.command.editor.socket.trust.futureinfo")
|
||||
.color(GRAY)
|
||||
.append(FULL_STOP)),
|
||||
prefixed(translatable()
|
||||
.key("luckperms.command.editor.socket.trust.connecting")
|
||||
.color(GRAY))
|
||||
);
|
||||
|
||||
Args0 EDITOR_SOCKET_TRUST_FAILURE = () -> prefixed(translatable()
|
||||
// "&cUnable to trust the given session because the socket is closed, or because a different connection was established instead."
|
||||
.color(RED)
|
||||
.key("luckperms.command.editor.socket.trust.failure")
|
||||
.append(FULL_STOP)
|
||||
);
|
||||
|
||||
Args2<Integer, String> EDITOR_HTTP_REQUEST_FAILURE = (code, message) -> prefixed(text()
|
||||
// "&cUnable to communicate with the editor. (response code &4{}&c, message='{}')"
|
||||
.color(RED)
|
||||
|
||||
+22
-26
@@ -23,38 +23,34 @@
|
||||
* SOFTWARE.
|
||||
*/
|
||||
|
||||
package me.lucko.luckperms.common.webeditor.socket.listener;
|
||||
package me.lucko.luckperms.common.metastacking;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import net.luckperms.api.metastacking.MetaStackElement;
|
||||
import net.luckperms.api.node.ChatMetaType;
|
||||
import net.luckperms.api.node.types.ChatMetaNode;
|
||||
|
||||
import me.lucko.luckperms.common.webeditor.socket.SocketMessageType;
|
||||
import me.lucko.luckperms.common.webeditor.socket.WebEditorSocket;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
|
||||
/**
|
||||
* Handler for {@link SocketMessageType#PING}
|
||||
* Special extension of {@link MetaStackElement} that provides its own {@link ElementAccumulator}
|
||||
* instead of using the {@link #shouldAccumulate(ChatMetaType, ChatMetaNode, ChatMetaNode)} method.
|
||||
*/
|
||||
public class HandlerPing implements Handler {
|
||||
|
||||
/** The socket */
|
||||
private final WebEditorSocket socket;
|
||||
|
||||
/** The time a ping was last received */
|
||||
private long lastPing = 0;
|
||||
|
||||
public HandlerPing(WebEditorSocket socket) {
|
||||
this.socket = socket;
|
||||
}
|
||||
|
||||
public long getLastPing() {
|
||||
return this.lastPing;
|
||||
}
|
||||
public interface DynamicMetaStackElement extends MetaStackElement {
|
||||
|
||||
@Deprecated
|
||||
@Override
|
||||
public void handle(JsonObject msg) {
|
||||
this.lastPing = System.currentTimeMillis();
|
||||
this.socket.send(SocketMessageType.PONG.builder()
|
||||
.add("ok", true)
|
||||
.toJson()
|
||||
);
|
||||
default boolean shouldAccumulate(@NonNull ChatMetaType type, @NonNull ChatMetaNode<?, ?> node, @Nullable ChatMetaNode<?, ?> current) {
|
||||
throw new UnsupportedOperationException("DynamicMetaStackElements do not support this method.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new {@link ElementAccumulator} for this element.
|
||||
*
|
||||
* @param type the type
|
||||
* @param <N> the node type
|
||||
* @return a new element accumulator
|
||||
*/
|
||||
<N extends ChatMetaNode<?, ?>> ElementAccumulator<N> newAccumulator(ChatMetaType type);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
/*
|
||||
* This file is part of LuckPerms, licensed under the MIT License.
|
||||
*
|
||||
* Copyright (c) lucko (Luck) <luck@lucko.me>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* 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.common.metastacking;
|
||||
|
||||
import net.luckperms.api.metastacking.MetaStackElement;
|
||||
import net.luckperms.api.node.ChatMetaType;
|
||||
import net.luckperms.api.node.types.ChatMetaNode;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
|
||||
/**
|
||||
* Accumulates {@link ChatMetaNode}s for a {@link MetaStackElement}
|
||||
* to provide the stack resolution.
|
||||
*
|
||||
* @param <N> the node type
|
||||
*/
|
||||
public interface ElementAccumulator<N extends ChatMetaNode<?, ?>> {
|
||||
|
||||
/**
|
||||
* Creates a {@link ElementAccumulator} for the given {@link MetaStackElement}.
|
||||
*
|
||||
* @param element the element
|
||||
* @param type the type
|
||||
* @param <N> the node type
|
||||
* @return the new accumulator
|
||||
*/
|
||||
static <N extends ChatMetaNode<?, ?>> ElementAccumulator<N> create(MetaStackElement element, ChatMetaType type) {
|
||||
// if the element is dynamic, use its provided impl
|
||||
if (element instanceof DynamicMetaStackElement) {
|
||||
return ((DynamicMetaStackElement) element).newAccumulator(type);
|
||||
}
|
||||
|
||||
// otherwise, just use the standard accumulator
|
||||
return new Standard<>(element, type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Offers a node to the accumulator.
|
||||
*
|
||||
* @param node the node
|
||||
*/
|
||||
void offer(@NonNull N node);
|
||||
|
||||
/**
|
||||
* Exports the final result from the accumulator.
|
||||
*
|
||||
* @return the result node
|
||||
*/
|
||||
@Nullable N result();
|
||||
|
||||
final class Standard<N extends ChatMetaNode<?, ?>> implements ElementAccumulator<N> {
|
||||
private final MetaStackElement element;
|
||||
private final ChatMetaType type;
|
||||
|
||||
private @Nullable N current = null;
|
||||
|
||||
Standard(MetaStackElement element, ChatMetaType type) {
|
||||
this.element = element;
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void offer(@NonNull N node) {
|
||||
if (this.element.shouldAccumulate(this.type, node, this.current)) {
|
||||
this.current = node;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable N result() {
|
||||
return this.current;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+91
-9
@@ -38,9 +38,13 @@ import net.luckperms.api.node.types.ChatMetaNode;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Contains the standard {@link MetaStackElement}s provided by LuckPerms.
|
||||
@@ -48,6 +52,9 @@ import java.util.Objects;
|
||||
public final class StandardStackElements {
|
||||
private StandardStackElements() {}
|
||||
|
||||
private static final Pattern HIGHEST_N_PATTERN = Pattern.compile("highest\\[([1-9]\\d*)]");
|
||||
private static final Pattern LOWEST_N_PATTERN = Pattern.compile("lowest\\[([1-9]\\d*)]");
|
||||
|
||||
public static MetaStackElement parseFromString(LuckPermsPlugin plugin, String s) {
|
||||
s = s.toLowerCase(Locale.ROOT);
|
||||
|
||||
@@ -61,25 +68,35 @@ public final class StandardStackElements {
|
||||
|
||||
// dynamic
|
||||
String p;
|
||||
if ((p = parseParam(s, "highest_on_track_")) != null) return highestFromGroupOnTrack(plugin, p);
|
||||
if ((p = parseParam(s, "lowest_on_track_")) != null) return lowestFromGroupOnTrack(plugin, p);
|
||||
if ((p = parseParam(s, "highest_not_on_track_")) != null) return highestNotFromGroupOnTrack(plugin, p);
|
||||
if ((p = parseParam(s, "lowest_not_on_track_")) != null) return lowestNotFromGroupOnTrack(plugin, p);
|
||||
if ((p = parseParam(s, "highest_from_group_")) != null) return highestFromGroup(p);
|
||||
if ((p = parseParam(s, "lowest_from_group_")) != null) return lowestFromGroup(p);
|
||||
if ((p = parseParam(s, "highest_not_from_group_")) != null) return highestNotFromGroup(p);
|
||||
if ((p = parseParam(s, "lowest_not_from_group_")) != null) return lowestNotFromGroup(p);
|
||||
if ((p = parseSuffixParam(s, "highest_on_track_")) != null) return highestFromGroupOnTrack(plugin, p);
|
||||
if ((p = parseSuffixParam(s, "lowest_on_track_")) != null) return lowestFromGroupOnTrack(plugin, p);
|
||||
if ((p = parseSuffixParam(s, "highest_not_on_track_")) != null) return highestNotFromGroupOnTrack(plugin, p);
|
||||
if ((p = parseSuffixParam(s, "lowest_not_on_track_")) != null) return lowestNotFromGroupOnTrack(plugin, p);
|
||||
if ((p = parseSuffixParam(s, "highest_from_group_")) != null) return highestFromGroup(p);
|
||||
if ((p = parseSuffixParam(s, "lowest_from_group_")) != null) return lowestFromGroup(p);
|
||||
if ((p = parseSuffixParam(s, "highest_not_from_group_")) != null) return highestNotFromGroup(p);
|
||||
if ((p = parseSuffixParam(s, "lowest_not_from_group_")) != null) return lowestNotFromGroup(p);
|
||||
if ((p = parseRegexParam(s, HIGHEST_N_PATTERN)) != null) return highestN(p);
|
||||
if ((p = parseRegexParam(s, LOWEST_N_PATTERN)) != null) return lowestN(p);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String parseParam(String s, String prefix) {
|
||||
private static String parseSuffixParam(String s, String prefix) {
|
||||
if (s.startsWith(prefix) && s.length() > prefix.length()) {
|
||||
return s.substring(prefix.length());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String parseRegexParam(String s, Pattern pattern) {
|
||||
Matcher matcher = pattern.matcher(s);
|
||||
if (!matcher.matches()) {
|
||||
return null;
|
||||
}
|
||||
return matcher.group(1);
|
||||
}
|
||||
|
||||
public static List<MetaStackElement> parseList(LuckPermsPlugin plugin, List<String> strings) {
|
||||
return strings.stream()
|
||||
.map(s -> {
|
||||
@@ -157,6 +174,15 @@ public final class StandardStackElements {
|
||||
.build();
|
||||
}
|
||||
|
||||
public static MetaStackElement highestN(String nString) {
|
||||
int n = Integer.parseInt(nString);
|
||||
return FluentMetaStackElement.builder("HighestN")
|
||||
.param("n", Integer.toString(n))
|
||||
.with(TYPE_CHECK)
|
||||
.with(CompareTakeNCheck.highest(n))
|
||||
.build();
|
||||
}
|
||||
|
||||
public static final MetaStackElement LOWEST = FluentMetaStackElement.builder("LowestPriority")
|
||||
.with(TYPE_CHECK)
|
||||
.with(LOWEST_CHECK)
|
||||
@@ -210,6 +236,62 @@ public final class StandardStackElements {
|
||||
.build();
|
||||
}
|
||||
|
||||
public static MetaStackElement lowestN(String nString) {
|
||||
int n = Integer.parseInt(nString);
|
||||
return FluentMetaStackElement.builder("LowestN")
|
||||
.param("n", Integer.toString(n))
|
||||
.with(TYPE_CHECK)
|
||||
.with(CompareTakeNCheck.lowest(n))
|
||||
.build();
|
||||
}
|
||||
|
||||
private static final class CompareTakeNCheck implements DynamicMetaStackElement {
|
||||
private static final Comparator<? super ChatMetaNode<?, ?>> LOWEST = Comparator.comparingInt(ChatMetaNode::getPriority);
|
||||
private static final Comparator<? super ChatMetaNode<?, ?>> HIGHEST = LOWEST.reversed();
|
||||
|
||||
static CompareTakeNCheck lowest(int n) {
|
||||
return new CompareTakeNCheck(n, LOWEST);
|
||||
}
|
||||
|
||||
static CompareTakeNCheck highest(int n) {
|
||||
return new CompareTakeNCheck(n, HIGHEST);
|
||||
}
|
||||
|
||||
private final int n;
|
||||
private final Comparator<? super ChatMetaNode<?, ?>> comparator;
|
||||
|
||||
CompareTakeNCheck(int n, Comparator<? super ChatMetaNode<?, ?>> comparator) {
|
||||
this.n = n - 1; // n is 1-indexed, convert it to zero-indexed
|
||||
this.comparator = comparator;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <N extends ChatMetaNode<?, ?>> ElementAccumulator<N> newAccumulator(ChatMetaType type) {
|
||||
return new Accumulator<>();
|
||||
}
|
||||
|
||||
private final class Accumulator<N extends ChatMetaNode<?, ?>> implements ElementAccumulator<N> {
|
||||
private final List<N> nodes = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public void offer(@NonNull N node) {
|
||||
this.nodes.add(node);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable N result() {
|
||||
// sort by priority
|
||||
this.nodes.sort(CompareTakeNCheck.this.comparator);
|
||||
|
||||
// return nodes[n]
|
||||
if (this.nodes.size() <= CompareTakeNCheck.this.n) {
|
||||
return null;
|
||||
}
|
||||
return this.nodes.get(CompareTakeNCheck.this.n);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static final class FromGroupOnTrackCheck implements MetaStackElement {
|
||||
private final LuckPermsPlugin plugin;
|
||||
private final String trackName;
|
||||
|
||||
@@ -31,6 +31,7 @@ import me.lucko.luckperms.common.cacheddata.HolderCachedDataManager;
|
||||
import me.lucko.luckperms.common.cacheddata.type.MetaAccumulator;
|
||||
import me.lucko.luckperms.common.inheritance.InheritanceComparator;
|
||||
import me.lucko.luckperms.common.inheritance.InheritanceGraph;
|
||||
import me.lucko.luckperms.common.model.nodemap.MutateResult;
|
||||
import me.lucko.luckperms.common.model.nodemap.NodeMap;
|
||||
import me.lucko.luckperms.common.model.nodemap.NodeMapMutable;
|
||||
import me.lucko.luckperms.common.model.nodemap.RecordedNodeMap;
|
||||
@@ -38,7 +39,6 @@ import me.lucko.luckperms.common.node.NodeEquality;
|
||||
import me.lucko.luckperms.common.node.comparator.NodeWithContextComparator;
|
||||
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
|
||||
import me.lucko.luckperms.common.query.DataSelector;
|
||||
import me.lucko.luckperms.common.util.Difference;
|
||||
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.luckperms.api.context.ContextSet;
|
||||
@@ -223,17 +223,8 @@ public abstract class PermissionHolder {
|
||||
invalidateCache();
|
||||
}
|
||||
|
||||
public Difference<Node> setNodes(DataType type, Iterable<? extends Node> set, boolean callEvent) {
|
||||
Difference<Node> res = getData(type).setContent(set);
|
||||
invalidateCache();
|
||||
if (callEvent) {
|
||||
getPlugin().getEventDispatcher().dispatchNodeChanges(this, type, res);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
public Difference<Node> setNodes(DataType type, Difference<Node> changes, boolean callEvent) {
|
||||
Difference<Node> res = getData(type).applyChanges(changes);
|
||||
public MutateResult setNodes(DataType type, Iterable<? extends Node> set, boolean callEvent) {
|
||||
MutateResult res = getData(type).setContent(set);
|
||||
invalidateCache();
|
||||
if (callEvent) {
|
||||
getPlugin().getEventDispatcher().dispatchNodeChanges(this, type, res);
|
||||
@@ -429,7 +420,7 @@ public abstract class PermissionHolder {
|
||||
}
|
||||
|
||||
private boolean auditTemporaryNodes(DataType dataType) {
|
||||
Difference<Node> result = getData(dataType).removeIf(Node::hasExpired);
|
||||
MutateResult result = getData(dataType).removeIf(Node::hasExpired);
|
||||
if (!result.isEmpty()) {
|
||||
invalidateCache();
|
||||
}
|
||||
@@ -463,7 +454,7 @@ public abstract class PermissionHolder {
|
||||
return DataMutateResult.FAIL_ALREADY_HAS;
|
||||
}
|
||||
|
||||
Difference<Node> changes = getData(dataType).add(node);
|
||||
MutateResult changes = getData(dataType).add(node);
|
||||
invalidateCache();
|
||||
if (callEvent) {
|
||||
this.plugin.getEventDispatcher().dispatchNodeChanges(this, dataType, changes);
|
||||
@@ -500,7 +491,7 @@ public abstract class PermissionHolder {
|
||||
|
||||
if (newNode != null) {
|
||||
// Remove the old Node & add the new one.
|
||||
Difference<Node> changes = data.removeThenAdd(otherMatch, newNode);
|
||||
MutateResult changes = data.removeThenAdd(otherMatch, newNode);
|
||||
invalidateCache();
|
||||
this.plugin.getEventDispatcher().dispatchNodeChanges(this, dataType, changes);
|
||||
|
||||
@@ -518,7 +509,7 @@ public abstract class PermissionHolder {
|
||||
return DataMutateResult.FAIL_LACKS;
|
||||
}
|
||||
|
||||
Difference<Node> changes = getData(dataType).remove(node);
|
||||
MutateResult changes = getData(dataType).remove(node);
|
||||
invalidateCache();
|
||||
this.plugin.getEventDispatcher().dispatchNodeChanges(this, dataType, changes);
|
||||
|
||||
@@ -540,7 +531,7 @@ public abstract class PermissionHolder {
|
||||
Node newNode = node.toBuilder().expiry(newExpiry).build();
|
||||
|
||||
// Remove the old Node & add the new one.
|
||||
Difference<Node> changes = data.removeThenAdd(otherMatch, newNode);
|
||||
MutateResult changes = data.removeThenAdd(otherMatch, newNode);
|
||||
invalidateCache();
|
||||
this.plugin.getEventDispatcher().dispatchNodeChanges(this, dataType, changes);
|
||||
|
||||
@@ -554,7 +545,7 @@ public abstract class PermissionHolder {
|
||||
}
|
||||
|
||||
public boolean removeIf(DataType dataType, @Nullable ContextSet contextSet, Predicate<? super Node> predicate, boolean giveDefault) {
|
||||
Difference<Node> changes;
|
||||
MutateResult changes;
|
||||
if (contextSet == null) {
|
||||
changes = getData(dataType).removeIf(predicate);
|
||||
} else {
|
||||
@@ -575,7 +566,7 @@ public abstract class PermissionHolder {
|
||||
}
|
||||
|
||||
public boolean clearNodes(DataType dataType, ContextSet contextSet, boolean giveDefault) {
|
||||
Difference<Node> changes;
|
||||
MutateResult changes;
|
||||
if (contextSet == null) {
|
||||
changes = getData(dataType).clear();
|
||||
} else {
|
||||
|
||||
+4
-3
@@ -32,7 +32,6 @@ import me.lucko.luckperms.common.model.manager.AbstractManager;
|
||||
import me.lucko.luckperms.common.model.manager.group.GroupManager;
|
||||
import me.lucko.luckperms.common.node.types.Inheritance;
|
||||
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
|
||||
import me.lucko.luckperms.common.util.CompletableFutures;
|
||||
import me.lucko.luckperms.common.verbose.event.CheckOrigin;
|
||||
|
||||
import net.luckperms.api.model.data.DataType;
|
||||
@@ -166,9 +165,11 @@ public abstract class AbstractUserManager<T extends User> extends AbstractManage
|
||||
Set<UUID> ids = new HashSet<>(getAll().keySet());
|
||||
ids.addAll(this.plugin.getBootstrap().getOnlinePlayers());
|
||||
|
||||
return ids.stream()
|
||||
CompletableFuture<?>[] loadTasks = ids.stream()
|
||||
.map(id -> this.plugin.getStorage().loadUser(id, null))
|
||||
.collect(CompletableFutures.collector());
|
||||
.toArray(CompletableFuture[]::new);
|
||||
|
||||
return CompletableFuture.allOf(loadTasks);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
/*
|
||||
* This file is part of LuckPerms, licensed under the MIT License.
|
||||
*
|
||||
* Copyright (c) lucko (Luck) <luck@lucko.me>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* 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.common.model.nodemap;
|
||||
|
||||
import net.luckperms.api.node.Node;
|
||||
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Records a log of the changes that occur as a result of a {@link NodeMap} mutation(s).
|
||||
*/
|
||||
public class MutateResult {
|
||||
private final LinkedHashSet<Change> changes = new LinkedHashSet<>();
|
||||
|
||||
public Set<Change> getChanges() {
|
||||
return this.changes;
|
||||
}
|
||||
|
||||
public Set<Node> getChanges(ChangeType type) {
|
||||
Set<Node> changes = new LinkedHashSet<>(this.changes.size());
|
||||
for (Change change : this.changes) {
|
||||
if (change.getType() == type) {
|
||||
changes.add(change.getNode());
|
||||
}
|
||||
}
|
||||
return changes;
|
||||
}
|
||||
|
||||
void clear() {
|
||||
this.changes.clear();
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return this.changes.isEmpty();
|
||||
}
|
||||
|
||||
public Set<Node> getAdded() {
|
||||
return getChanges(ChangeType.ADD);
|
||||
}
|
||||
|
||||
public Set<Node> getRemoved() {
|
||||
return getChanges(ChangeType.REMOVE);
|
||||
}
|
||||
|
||||
private void recordChange(Change change) {
|
||||
// This method is the magic of this class.
|
||||
// When tracking, we want to ignore changes that cancel each other out, and only
|
||||
// keep track of the net difference.
|
||||
// e.g. adding then removing the same node = zero net change, so ignore it.
|
||||
|
||||
if (this.changes.remove(change.inverse())) {
|
||||
return;
|
||||
}
|
||||
this.changes.add(change);
|
||||
}
|
||||
|
||||
public void recordChange(ChangeType type, Node node) {
|
||||
recordChange(new Change(type, node));
|
||||
}
|
||||
|
||||
public void recordChanges(ChangeType type, Iterable<Node> nodes) {
|
||||
for (Node node : nodes) {
|
||||
recordChange(new Change(type, node));
|
||||
}
|
||||
}
|
||||
|
||||
public MutateResult mergeFrom(MutateResult other) {
|
||||
for (Change change : other.changes) {
|
||||
recordChange(change);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MutateResult{changes=" + this.changes + '}';
|
||||
}
|
||||
|
||||
public static final class Change {
|
||||
private final ChangeType type;
|
||||
private final Node node;
|
||||
|
||||
public Change(ChangeType type, Node node) {
|
||||
this.type = type;
|
||||
this.node = node;
|
||||
}
|
||||
|
||||
public ChangeType getType() {
|
||||
return this.type;
|
||||
}
|
||||
|
||||
public Node getNode() {
|
||||
return this.node;
|
||||
}
|
||||
|
||||
public Change inverse() {
|
||||
return new Change(this.type.inverse(), this.node);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Change change = (Change) o;
|
||||
return this.type == change.type && this.node.equals(change.node);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(this.type, this.node);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Change{type=" + this.type + ", node=" + this.node + '}';
|
||||
}
|
||||
}
|
||||
|
||||
public enum ChangeType {
|
||||
ADD, REMOVE;
|
||||
|
||||
public ChangeType inverse() {
|
||||
return this == ADD ? REMOVE : ADD;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -30,7 +30,6 @@ import com.google.common.collect.ImmutableSet;
|
||||
|
||||
import me.lucko.luckperms.common.model.PermissionHolder;
|
||||
import me.lucko.luckperms.common.node.comparator.NodeWithContextComparator;
|
||||
import me.lucko.luckperms.common.util.Difference;
|
||||
|
||||
import net.luckperms.api.context.ContextSet;
|
||||
import net.luckperms.api.context.ImmutableContextSet;
|
||||
@@ -135,30 +134,28 @@ public interface NodeMap {
|
||||
|
||||
// mutate methods
|
||||
|
||||
Difference<Node> add(Node nodeWithoutInheritanceOrigin);
|
||||
MutateResult add(Node nodeWithoutInheritanceOrigin);
|
||||
|
||||
Difference<Node> remove(Node node);
|
||||
MutateResult remove(Node node);
|
||||
|
||||
Difference<Node> removeExact(Node node);
|
||||
MutateResult removeExact(Node node);
|
||||
|
||||
Difference<Node> removeIf(Predicate<? super Node> predicate);
|
||||
MutateResult removeIf(Predicate<? super Node> predicate);
|
||||
|
||||
Difference<Node> removeIf(ContextSet contextSet, Predicate<? super Node> predicate);
|
||||
MutateResult removeIf(ContextSet contextSet, Predicate<? super Node> predicate);
|
||||
|
||||
Difference<Node> removeThenAdd(Node nodeToRemove, Node nodeToAdd);
|
||||
MutateResult removeThenAdd(Node nodeToRemove, Node nodeToAdd);
|
||||
|
||||
Difference<Node> clear();
|
||||
MutateResult clear();
|
||||
|
||||
Difference<Node> clear(ContextSet contextSet);
|
||||
MutateResult clear(ContextSet contextSet);
|
||||
|
||||
Difference<Node> setContent(Iterable<? extends Node> set);
|
||||
MutateResult setContent(Iterable<? extends Node> set);
|
||||
|
||||
Difference<Node> setContent(Stream<? extends Node> stream);
|
||||
MutateResult setContent(Stream<? extends Node> stream);
|
||||
|
||||
Difference<Node> applyChanges(Difference<Node> changes);
|
||||
MutateResult addAll(Iterable<? extends Node> set);
|
||||
|
||||
Difference<Node> addAll(Iterable<? extends Node> set);
|
||||
|
||||
Difference<Node> addAll(Stream<? extends Node> stream);
|
||||
MutateResult addAll(Stream<? extends Node> stream);
|
||||
|
||||
}
|
||||
@@ -29,9 +29,8 @@ import me.lucko.luckperms.common.config.ConfigKeys;
|
||||
import me.lucko.luckperms.common.context.comparator.ContextSetComparator;
|
||||
import me.lucko.luckperms.common.model.InheritanceOrigin;
|
||||
import me.lucko.luckperms.common.model.PermissionHolder;
|
||||
import me.lucko.luckperms.common.model.nodemap.MutateResult.ChangeType;
|
||||
import me.lucko.luckperms.common.node.comparator.NodeComparator;
|
||||
import me.lucko.luckperms.common.util.Difference;
|
||||
import me.lucko.luckperms.common.util.Difference.ChangeType;
|
||||
|
||||
import net.luckperms.api.context.ContextSatisfyMode;
|
||||
import net.luckperms.api.context.ContextSet;
|
||||
@@ -123,11 +122,11 @@ public class NodeMapMutable extends NodeMapBase {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Difference<Node> add(Node nodeWithoutInheritanceOrigin) {
|
||||
public MutateResult add(Node nodeWithoutInheritanceOrigin) {
|
||||
Node node = addInheritanceOrigin(nodeWithoutInheritanceOrigin);
|
||||
|
||||
ImmutableContextSet context = node.getContexts();
|
||||
Difference<Node> result = new Difference<>();
|
||||
MutateResult result = new MutateResult();
|
||||
|
||||
this.lock.lock();
|
||||
try {
|
||||
@@ -163,9 +162,9 @@ public class NodeMapMutable extends NodeMapBase {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Difference<Node> remove(Node node) {
|
||||
public MutateResult remove(Node node) {
|
||||
ImmutableContextSet context = node.getContexts();
|
||||
Difference<Node> result = new Difference<>();
|
||||
MutateResult result = new MutateResult();
|
||||
|
||||
this.lock.lock();
|
||||
try {
|
||||
@@ -192,7 +191,7 @@ public class NodeMapMutable extends NodeMapBase {
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void removeMatching(Iterator<Node> it, Node node, Difference<Node> result) {
|
||||
private static void removeMatching(Iterator<Node> it, Node node, MutateResult result) {
|
||||
while (it.hasNext()) {
|
||||
Node el = it.next();
|
||||
if (node.equals(el, NodeEqualityPredicate.IGNORE_EXPIRY_TIME_AND_VALUE)) {
|
||||
@@ -202,7 +201,7 @@ public class NodeMapMutable extends NodeMapBase {
|
||||
}
|
||||
}
|
||||
|
||||
private static void removeMatchingButNotSame(Iterator<Node> it, Node node, Difference<Node> result) {
|
||||
private static void removeMatchingButNotSame(Iterator<Node> it, Node node, MutateResult result) {
|
||||
while (it.hasNext()) {
|
||||
Node el = it.next();
|
||||
if (el != node && node.equals(el, NodeEqualityPredicate.IGNORE_EXPIRY_TIME_AND_VALUE)) {
|
||||
@@ -213,9 +212,9 @@ public class NodeMapMutable extends NodeMapBase {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Difference<Node> removeExact(Node node) {
|
||||
public MutateResult removeExact(Node node) {
|
||||
ImmutableContextSet context = node.getContexts();
|
||||
Difference<Node> result = new Difference<>();
|
||||
MutateResult result = new MutateResult();
|
||||
|
||||
this.lock.lock();
|
||||
try {
|
||||
@@ -246,8 +245,8 @@ public class NodeMapMutable extends NodeMapBase {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Difference<Node> removeIf(Predicate<? super Node> predicate) {
|
||||
Difference<Node> result = new Difference<>();
|
||||
public MutateResult removeIf(Predicate<? super Node> predicate) {
|
||||
MutateResult result = new MutateResult();
|
||||
|
||||
this.lock.lock();
|
||||
try {
|
||||
@@ -262,9 +261,9 @@ public class NodeMapMutable extends NodeMapBase {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Difference<Node> removeIf(ContextSet contextSet, Predicate<? super Node> predicate) {
|
||||
public MutateResult removeIf(ContextSet contextSet, Predicate<? super Node> predicate) {
|
||||
ImmutableContextSet context = contextSet.immutableCopy();
|
||||
Difference<Node> result = new Difference<>();
|
||||
MutateResult result = new MutateResult();
|
||||
|
||||
this.lock.lock();
|
||||
try {
|
||||
@@ -280,7 +279,7 @@ public class NodeMapMutable extends NodeMapBase {
|
||||
return result;
|
||||
}
|
||||
|
||||
private void removeMatching(Iterator<Node> it, Predicate<? super Node> predicate, Difference<Node> result) {
|
||||
private void removeMatching(Iterator<Node> it, Predicate<? super Node> predicate, MutateResult result) {
|
||||
while (it.hasNext()) {
|
||||
Node node = it.next();
|
||||
|
||||
@@ -301,9 +300,9 @@ public class NodeMapMutable extends NodeMapBase {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Difference<Node> removeThenAdd(Node nodeToRemove, Node nodeToAdd) {
|
||||
public MutateResult removeThenAdd(Node nodeToRemove, Node nodeToAdd) {
|
||||
if (nodeToAdd.equals(nodeToRemove)) {
|
||||
return new Difference<>();
|
||||
return new MutateResult();
|
||||
}
|
||||
|
||||
this.lock.lock();
|
||||
@@ -315,8 +314,8 @@ public class NodeMapMutable extends NodeMapBase {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Difference<Node> clear() {
|
||||
Difference<Node> result = new Difference<>();
|
||||
public MutateResult clear() {
|
||||
MutateResult result = new MutateResult();
|
||||
|
||||
this.lock.lock();
|
||||
try {
|
||||
@@ -337,9 +336,9 @@ public class NodeMapMutable extends NodeMapBase {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Difference<Node> clear(ContextSet contextSet) {
|
||||
public MutateResult clear(ContextSet contextSet) {
|
||||
ImmutableContextSet context = contextSet.immutableCopy();
|
||||
Difference<Node> result = new Difference<>();
|
||||
MutateResult result = new MutateResult();
|
||||
|
||||
this.lock.lock();
|
||||
try {
|
||||
@@ -356,8 +355,8 @@ public class NodeMapMutable extends NodeMapBase {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Difference<Node> setContent(Iterable<? extends Node> set) {
|
||||
Difference<Node> result = new Difference<>();
|
||||
public MutateResult setContent(Iterable<? extends Node> set) {
|
||||
MutateResult result = new MutateResult();
|
||||
|
||||
this.lock.lock();
|
||||
try {
|
||||
@@ -371,8 +370,8 @@ public class NodeMapMutable extends NodeMapBase {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Difference<Node> setContent(Stream<? extends Node> stream) {
|
||||
Difference<Node> result = new Difference<>();
|
||||
public MutateResult setContent(Stream<? extends Node> stream) {
|
||||
MutateResult result = new MutateResult();
|
||||
|
||||
this.lock.lock();
|
||||
try {
|
||||
@@ -386,27 +385,8 @@ public class NodeMapMutable extends NodeMapBase {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Difference<Node> applyChanges(Difference<Node> changes) {
|
||||
Difference<Node> result = new Difference<>();
|
||||
|
||||
this.lock.lock();
|
||||
try {
|
||||
for (Node n : changes.getAdded()) {
|
||||
result.mergeFrom(add(n));
|
||||
}
|
||||
for (Node n : changes.getRemoved()) {
|
||||
result.mergeFrom(removeExact(n));
|
||||
}
|
||||
} finally {
|
||||
this.lock.unlock();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Difference<Node> addAll(Iterable<? extends Node> set) {
|
||||
Difference<Node> result = new Difference<>();
|
||||
public MutateResult addAll(Iterable<? extends Node> set) {
|
||||
MutateResult result = new MutateResult();
|
||||
|
||||
this.lock.lock();
|
||||
try {
|
||||
@@ -421,8 +401,8 @@ public class NodeMapMutable extends NodeMapBase {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Difference<Node> addAll(Stream<? extends Node> stream) {
|
||||
Difference<Node> result = new Difference<>();
|
||||
public MutateResult addAll(Stream<? extends Node> stream) {
|
||||
MutateResult result = new MutateResult();
|
||||
|
||||
this.lock.lock();
|
||||
try {
|
||||
|
||||
@@ -28,8 +28,6 @@ package me.lucko.luckperms.common.model.nodemap;
|
||||
import com.google.common.collect.ImmutableCollection;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
|
||||
import me.lucko.luckperms.common.util.Difference;
|
||||
|
||||
import net.luckperms.api.context.ContextSet;
|
||||
import net.luckperms.api.context.ImmutableContextSet;
|
||||
import net.luckperms.api.node.Node;
|
||||
@@ -55,7 +53,7 @@ public class RecordedNodeMap implements NodeMap {
|
||||
|
||||
private final NodeMap delegate;
|
||||
private final Lock lock = new ReentrantLock();
|
||||
private Difference<Node> changes = new Difference<>();
|
||||
private MutateResult changes = new MutateResult();
|
||||
|
||||
public RecordedNodeMap(NodeMap delegate) {
|
||||
this.delegate = delegate;
|
||||
@@ -74,12 +72,12 @@ public class RecordedNodeMap implements NodeMap {
|
||||
}
|
||||
}
|
||||
|
||||
public Difference<Node> exportChanges(Predicate<Difference<Node>> onlyIf) {
|
||||
public MutateResult exportChanges(Predicate<MutateResult> onlyIf) {
|
||||
this.lock.lock();
|
||||
try {
|
||||
Difference<Node> existing = this.changes;
|
||||
MutateResult existing = this.changes;
|
||||
if (onlyIf.test(existing)) {
|
||||
this.changes = new Difference<>();
|
||||
this.changes = new MutateResult();
|
||||
return existing;
|
||||
}
|
||||
return null;
|
||||
@@ -88,7 +86,7 @@ public class RecordedNodeMap implements NodeMap {
|
||||
}
|
||||
}
|
||||
|
||||
private Difference<Node> record(Difference<Node> result) {
|
||||
private MutateResult record(MutateResult result) {
|
||||
this.lock.lock();
|
||||
try {
|
||||
this.changes.mergeFrom(result);
|
||||
@@ -101,67 +99,62 @@ public class RecordedNodeMap implements NodeMap {
|
||||
// delegate, but pass the result through #record(MutateResult)
|
||||
|
||||
@Override
|
||||
public Difference<Node> add(Node nodeWithoutInheritanceOrigin) {
|
||||
public MutateResult add(Node nodeWithoutInheritanceOrigin) {
|
||||
return record(this.delegate.add(nodeWithoutInheritanceOrigin));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Difference<Node> remove(Node node) {
|
||||
public MutateResult remove(Node node) {
|
||||
return record(this.delegate.remove(node));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Difference<Node> removeExact(Node node) {
|
||||
public MutateResult removeExact(Node node) {
|
||||
return record(this.delegate.removeExact(node));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Difference<Node> removeIf(Predicate<? super Node> predicate) {
|
||||
public MutateResult removeIf(Predicate<? super Node> predicate) {
|
||||
return record(this.delegate.removeIf(predicate));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Difference<Node> removeIf(ContextSet contextSet, Predicate<? super Node> predicate) {
|
||||
public MutateResult removeIf(ContextSet contextSet, Predicate<? super Node> predicate) {
|
||||
return record(this.delegate.removeIf(contextSet, predicate));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Difference<Node> removeThenAdd(Node nodeToRemove, Node nodeToAdd) {
|
||||
public MutateResult removeThenAdd(Node nodeToRemove, Node nodeToAdd) {
|
||||
return record(this.delegate.removeThenAdd(nodeToRemove, nodeToAdd));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Difference<Node> clear() {
|
||||
public MutateResult clear() {
|
||||
return record(this.delegate.clear());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Difference<Node> clear(ContextSet contextSet) {
|
||||
public MutateResult clear(ContextSet contextSet) {
|
||||
return record(this.delegate.clear(contextSet));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Difference<Node> setContent(Iterable<? extends Node> set) {
|
||||
public MutateResult setContent(Iterable<? extends Node> set) {
|
||||
return record(this.delegate.setContent(set));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Difference<Node> setContent(Stream<? extends Node> stream) {
|
||||
public MutateResult setContent(Stream<? extends Node> stream) {
|
||||
return record(this.delegate.setContent(stream));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Difference<Node> applyChanges(Difference<Node> changes) {
|
||||
return record(this.delegate.applyChanges(changes));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Difference<Node> addAll(Iterable<? extends Node> set) {
|
||||
public MutateResult addAll(Iterable<? extends Node> set) {
|
||||
return record(this.delegate.addAll(set));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Difference<Node> addAll(Stream<? extends Node> stream) {
|
||||
public MutateResult addAll(Stream<? extends Node> stream) {
|
||||
return record(this.delegate.addAll(stream));
|
||||
}
|
||||
|
||||
|
||||
@@ -40,7 +40,6 @@ import me.lucko.luckperms.common.event.EventDispatcher;
|
||||
import me.lucko.luckperms.common.event.gen.GeneratedEventClass;
|
||||
import me.lucko.luckperms.common.extension.SimpleExtensionManager;
|
||||
import me.lucko.luckperms.common.http.BytebinClient;
|
||||
import me.lucko.luckperms.common.http.BytesocksClient;
|
||||
import me.lucko.luckperms.common.inheritance.InheritanceGraphFactory;
|
||||
import me.lucko.luckperms.common.locale.Message;
|
||||
import me.lucko.luckperms.common.locale.TranslationManager;
|
||||
@@ -58,7 +57,7 @@ import me.lucko.luckperms.common.tasks.ExpireTemporaryTask;
|
||||
import me.lucko.luckperms.common.tasks.SyncTask;
|
||||
import me.lucko.luckperms.common.treeview.PermissionRegistry;
|
||||
import me.lucko.luckperms.common.verbose.VerboseHandler;
|
||||
import me.lucko.luckperms.common.webeditor.store.WebEditorStore;
|
||||
import me.lucko.luckperms.common.webeditor.WebEditorSessionStore;
|
||||
|
||||
import net.luckperms.api.LuckPerms;
|
||||
|
||||
@@ -91,8 +90,7 @@ public abstract class AbstractLuckPermsPlugin implements LuckPermsPlugin {
|
||||
private LogDispatcher logDispatcher;
|
||||
private LuckPermsConfiguration configuration;
|
||||
private BytebinClient bytebin;
|
||||
private BytesocksClient bytesocks;
|
||||
private WebEditorStore webEditorStore;
|
||||
private WebEditorSessionStore webEditorSessionStore;
|
||||
private TranslationRepository translationRepository;
|
||||
private FileWatcher fileWatcher = null;
|
||||
private Storage storage;
|
||||
@@ -138,8 +136,7 @@ public abstract class AbstractLuckPermsPlugin implements LuckPermsPlugin {
|
||||
.build();
|
||||
|
||||
this.bytebin = new BytebinClient(httpClient, getConfiguration().get(ConfigKeys.BYTEBIN_URL), "luckperms");
|
||||
this.bytesocks = new BytesocksClient(httpClient, getConfiguration().get(ConfigKeys.BYTESOCKS_HOST), "luckperms/editor");
|
||||
this.webEditorStore = new WebEditorStore(this);
|
||||
this.webEditorSessionStore = new WebEditorSessionStore();
|
||||
|
||||
// init translation repo and update bundle files
|
||||
this.translationRepository = new TranslationRepository(this);
|
||||
@@ -194,7 +191,6 @@ public abstract class AbstractLuckPermsPlugin implements LuckPermsPlugin {
|
||||
|
||||
// register with the LP API
|
||||
this.apiProvider = new LuckPermsApiProvider(this);
|
||||
this.apiProvider.ensureApiWasLoadedByPlugin();
|
||||
this.eventDispatcher = new EventDispatcher(provideEventBus(this.apiProvider));
|
||||
getBootstrap().getScheduler().executeAsync(GeneratedEventClass::preGenerate);
|
||||
ApiRegistrationUtil.registerProvider(this.apiProvider);
|
||||
@@ -424,13 +420,8 @@ public abstract class AbstractLuckPermsPlugin implements LuckPermsPlugin {
|
||||
}
|
||||
|
||||
@Override
|
||||
public BytesocksClient getBytesocks() {
|
||||
return this.bytesocks;
|
||||
}
|
||||
|
||||
@Override
|
||||
public WebEditorStore getWebEditorStore() {
|
||||
return this.webEditorStore;
|
||||
public WebEditorSessionStore getWebEditorSessionStore() {
|
||||
return this.webEditorSessionStore;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -36,7 +36,6 @@ import me.lucko.luckperms.common.dependencies.DependencyManager;
|
||||
import me.lucko.luckperms.common.event.EventDispatcher;
|
||||
import me.lucko.luckperms.common.extension.SimpleExtensionManager;
|
||||
import me.lucko.luckperms.common.http.BytebinClient;
|
||||
import me.lucko.luckperms.common.http.BytesocksClient;
|
||||
import me.lucko.luckperms.common.inheritance.InheritanceGraphFactory;
|
||||
import me.lucko.luckperms.common.locale.TranslationManager;
|
||||
import me.lucko.luckperms.common.locale.TranslationRepository;
|
||||
@@ -56,7 +55,7 @@ import me.lucko.luckperms.common.storage.implementation.file.watcher.FileWatcher
|
||||
import me.lucko.luckperms.common.tasks.SyncTask;
|
||||
import me.lucko.luckperms.common.treeview.PermissionRegistry;
|
||||
import me.lucko.luckperms.common.verbose.VerboseHandler;
|
||||
import me.lucko.luckperms.common.webeditor.store.WebEditorStore;
|
||||
import me.lucko.luckperms.common.webeditor.WebEditorSessionStore;
|
||||
|
||||
import net.luckperms.api.query.QueryOptions;
|
||||
|
||||
@@ -251,18 +250,11 @@ public interface LuckPermsPlugin {
|
||||
BytebinClient getBytebin();
|
||||
|
||||
/**
|
||||
* Gets the bytesocks instance in use by platform.
|
||||
* Gets the web editor session store
|
||||
*
|
||||
* @return the bytesocks instance
|
||||
* @return the web editor session store
|
||||
*/
|
||||
BytesocksClient getBytesocks();
|
||||
|
||||
/**
|
||||
* Gets the web editor store
|
||||
*
|
||||
* @return the web editor store
|
||||
*/
|
||||
WebEditorStore getWebEditorStore();
|
||||
WebEditorSessionStore getWebEditorSessionStore();
|
||||
|
||||
/**
|
||||
* Gets a calculated context instance for the user using the rules of the platform.
|
||||
|
||||
+2
-5
@@ -34,7 +34,8 @@ import java.nio.file.Path;
|
||||
public class ReflectionClassPathAppender implements ClassPathAppender {
|
||||
private final URLClassLoaderAccess classLoaderAccess;
|
||||
|
||||
public ReflectionClassPathAppender(ClassLoader classLoader) throws IllegalStateException {
|
||||
public ReflectionClassPathAppender(LuckPermsBootstrap bootstrap) throws IllegalStateException {
|
||||
ClassLoader classLoader = bootstrap.getClass().getClassLoader();
|
||||
if (classLoader instanceof URLClassLoader) {
|
||||
this.classLoaderAccess = URLClassLoaderAccess.create((URLClassLoader) classLoader);
|
||||
} else {
|
||||
@@ -42,10 +43,6 @@ public class ReflectionClassPathAppender implements ClassPathAppender {
|
||||
}
|
||||
}
|
||||
|
||||
public ReflectionClassPathAppender(LuckPermsBootstrap bootstrap) throws IllegalStateException {
|
||||
this(bootstrap.getClass().getClassLoader());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addJarToClasspath(Path file) {
|
||||
try {
|
||||
|
||||
-7
@@ -96,13 +96,6 @@ public abstract class AbstractJavaScheduler implements SchedulerAdapter {
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
this.worker.shutdown();
|
||||
try {
|
||||
this.worker.awaitTermination(1, TimeUnit.MINUTES);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static final class ErrorReportingExecutor implements Executor {
|
||||
|
||||
@@ -130,7 +130,7 @@ public final class AbstractSender<T> implements Sender {
|
||||
// A small utility method which splits components built using
|
||||
// > join(newLine(), components...)
|
||||
// back into separate components.
|
||||
public static Iterable<Component> splitNewlines(Component message) {
|
||||
private static Iterable<Component> splitNewlines(Component message) {
|
||||
if (message instanceof TextComponent && message.style().isEmpty() && !message.children().isEmpty() && ((TextComponent) message).content().isEmpty()) {
|
||||
LinkedList<List<Component>> split = new LinkedList<>();
|
||||
split.add(new ArrayList<>());
|
||||
|
||||
@@ -154,16 +154,6 @@ public class Storage {
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<Map<UUID, User>> loadUsers(Set<UUID> uniqueIds) {
|
||||
return future(() -> {
|
||||
Map<UUID, User> users = this.implementation.loadUsers(uniqueIds);
|
||||
for (User user : users.values()) {
|
||||
this.plugin.getEventDispatcher().dispatchUserLoad(user);
|
||||
}
|
||||
return users;
|
||||
});
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> saveUser(User user) {
|
||||
return future(() -> this.implementation.saveUser(user));
|
||||
}
|
||||
|
||||
-2
@@ -69,8 +69,6 @@ public interface StorageImplementation {
|
||||
|
||||
User loadUser(UUID uniqueId, String username) throws Exception;
|
||||
|
||||
Map<UUID, User> loadUsers(Set<UUID> uniqueIds) throws Exception;
|
||||
|
||||
void saveUser(User user) throws Exception;
|
||||
|
||||
Set<UUID> getUniqueUsers() throws Exception;
|
||||
|
||||
-11
@@ -67,7 +67,6 @@ import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -201,16 +200,6 @@ public abstract class AbstractConfigurateStorage implements StorageImplementatio
|
||||
return user;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<UUID, User> loadUsers(Set<UUID> uniqueIds) throws Exception {
|
||||
// add multithreading here?
|
||||
Map<UUID, User> map = new HashMap<>();
|
||||
for (UUID uniqueId : uniqueIds) {
|
||||
map.put(uniqueId, loadUser(uniqueId, null));
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void saveUser(User user) throws IOException {
|
||||
user.normalData().discardChanges();
|
||||
|
||||
-11
@@ -72,7 +72,6 @@ import org.bson.Document;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
@@ -329,16 +328,6 @@ public class MongoStorage implements StorageImplementation {
|
||||
return user;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<UUID, User> loadUsers(Set<UUID> uniqueIds) throws Exception {
|
||||
// make this a bulk search?
|
||||
Map<UUID, User> map = new HashMap<>();
|
||||
for (UUID uniqueId : uniqueIds) {
|
||||
map.put(uniqueId, loadUser(uniqueId, null));
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void saveUser(User user) {
|
||||
MongoCollection<Document> c = this.database.getCollection(this.prefix + "users");
|
||||
|
||||
-5
@@ -152,11 +152,6 @@ public class SplitStorage implements StorageImplementation {
|
||||
return implFor(SplitStorageType.USER).loadUser(uniqueId, username);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<UUID, User> loadUsers(Set<UUID> uniqueIds) throws Exception {
|
||||
return implFor(SplitStorageType.USER).loadUsers(uniqueIds);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void saveUser(User user) throws Exception {
|
||||
implFor(SplitStorageType.USER).saveUser(user);
|
||||
|
||||
+10
-86
@@ -39,6 +39,7 @@ import me.lucko.luckperms.common.model.Group;
|
||||
import me.lucko.luckperms.common.model.Track;
|
||||
import me.lucko.luckperms.common.model.User;
|
||||
import me.lucko.luckperms.common.model.manager.group.GroupManager;
|
||||
import me.lucko.luckperms.common.model.nodemap.MutateResult;
|
||||
import me.lucko.luckperms.common.node.factory.NodeBuilders;
|
||||
import me.lucko.luckperms.common.node.matcher.ConstraintNodeMatcher;
|
||||
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
|
||||
@@ -46,7 +47,6 @@ import me.lucko.luckperms.common.storage.implementation.StorageImplementation;
|
||||
import me.lucko.luckperms.common.storage.implementation.sql.connection.ConnectionFactory;
|
||||
import me.lucko.luckperms.common.storage.misc.NodeEntry;
|
||||
import me.lucko.luckperms.common.storage.misc.PlayerSaveResultImpl;
|
||||
import me.lucko.luckperms.common.util.Difference;
|
||||
import me.lucko.luckperms.common.util.Uuids;
|
||||
import me.lucko.luckperms.common.util.gson.GsonProvider;
|
||||
|
||||
@@ -84,7 +84,6 @@ public class SqlStorage implements StorageImplementation {
|
||||
private static final Type LIST_STRING_TYPE = new TypeToken<List<String>>(){}.getType();
|
||||
|
||||
private static final String USER_PERMISSIONS_SELECT = "SELECT id, permission, value, server, world, expiry, contexts FROM '{prefix}user_permissions' WHERE uuid=?";
|
||||
private static final String USER_PERMISSIONS_SELECT_MULTIPLE = "SELECT uuid, id, permission, value, server, world, expiry, contexts FROM '{prefix}user_permissions' WHERE ";
|
||||
private static final String USER_PERMISSIONS_DELETE_SPECIFIC = "DELETE FROM '{prefix}user_permissions' WHERE id=?";
|
||||
private static final String USER_PERMISSIONS_DELETE_SPECIFIC_PROPS = "DELETE FROM '{prefix}user_permissions' WHERE uuid=? AND permission=? AND value=? AND server=? AND world=? AND expiry=? AND contexts=?";
|
||||
private static final String USER_PERMISSIONS_DELETE = "DELETE FROM '{prefix}user_permissions' WHERE uuid=?";
|
||||
@@ -100,7 +99,6 @@ public class SqlStorage implements StorageImplementation {
|
||||
private static final String PLAYER_SELECT_ALL_UUIDS_BY_USERNAME = "SELECT uuid FROM '{prefix}players' WHERE username=? AND NOT uuid=?";
|
||||
private static final String PLAYER_DELETE_ALL_UUIDS_BY_USERNAME = "DELETE FROM '{prefix}players' WHERE username=? AND NOT uuid=?";
|
||||
private static final String PLAYER_SELECT_BY_UUID = "SELECT username, primary_group FROM '{prefix}players' WHERE uuid=? LIMIT 1";
|
||||
private static final String PLAYER_SELECT_BY_UUID_MULTIPLE = "SELECT uuid, username, primary_group FROM '{prefix}players' WHERE ";
|
||||
private static final String PLAYER_SELECT_PRIMARY_GROUP_BY_UUID = "SELECT primary_group FROM '{prefix}players' WHERE uuid=? LIMIT 1";
|
||||
private static final String PLAYER_UPDATE_PRIMARY_GROUP_BY_UUID = "UPDATE '{prefix}players' SET primary_group=? WHERE uuid=?";
|
||||
|
||||
@@ -321,38 +319,16 @@ public class SqlStorage implements StorageImplementation {
|
||||
|
||||
@Override
|
||||
public User loadUser(UUID uniqueId, String username) throws SQLException {
|
||||
User user = this.plugin.getUserManager().getOrMake(uniqueId, username);
|
||||
|
||||
List<Node> nodes;
|
||||
SqlPlayerData playerData;
|
||||
|
||||
try (Connection c = this.connectionFactory.getConnection()) {
|
||||
nodes = selectUserPermissions(c, uniqueId);
|
||||
playerData = selectPlayerData(c, uniqueId);
|
||||
nodes = selectUserPermissions(c, user.getUniqueId());
|
||||
playerData = selectPlayerData(c, user.getUniqueId());
|
||||
}
|
||||
|
||||
return createUser(uniqueId, username, playerData, nodes, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<UUID, User> loadUsers(Set<UUID> uniqueIds) throws Exception {
|
||||
Map<UUID, List<Node>> nodesMap;
|
||||
Map<UUID, SqlPlayerData> playerDataMap;
|
||||
|
||||
try (Connection c = this.connectionFactory.getConnection()) {
|
||||
nodesMap = selectUserPermissions(c, uniqueIds);
|
||||
playerDataMap = selectPlayerData(c, uniqueIds);
|
||||
}
|
||||
|
||||
Map<UUID, User> users = new HashMap<>();
|
||||
for (UUID uniqueId : uniqueIds) {
|
||||
SqlPlayerData playerData = playerDataMap.get(uniqueId);
|
||||
List<Node> nodes = nodesMap.get(uniqueId);
|
||||
users.put(uniqueId, createUser(uniqueId, null, playerData, nodes, false));
|
||||
}
|
||||
return users;
|
||||
}
|
||||
|
||||
private User createUser(UUID uniqueId, String username, SqlPlayerData playerData, List<Node> nodes, boolean saveAfterAudit) throws SQLException {
|
||||
User user = this.plugin.getUserManager().getOrMake(uniqueId, username);
|
||||
if (playerData != null) {
|
||||
if (playerData.primaryGroup != null) {
|
||||
user.getPrimaryGroup().setStoredValue(playerData.primaryGroup);
|
||||
@@ -366,7 +342,7 @@ public class SqlStorage implements StorageImplementation {
|
||||
user.loadNodesFromStorage(nodes);
|
||||
this.plugin.getUserManager().giveDefaultIfNeeded(user);
|
||||
|
||||
if (user.auditTemporaryNodes() && saveAfterAudit) {
|
||||
if (user.auditTemporaryNodes()) {
|
||||
saveUser(user);
|
||||
}
|
||||
|
||||
@@ -375,15 +351,15 @@ public class SqlStorage implements StorageImplementation {
|
||||
|
||||
@Override
|
||||
public void saveUser(User user) throws SQLException {
|
||||
Difference<Node> changes = user.normalData().exportChanges(results -> {
|
||||
MutateResult changes = user.normalData().exportChanges(results -> {
|
||||
if (this.plugin.getUserManager().isNonDefaultUser(user)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// if the only change is adding the default node, we don't need to export
|
||||
if (results.getChanges().size() == 1) {
|
||||
Difference.Change<Node> onlyChange = results.getChanges().iterator().next();
|
||||
return !(onlyChange.type() == Difference.ChangeType.ADD && this.plugin.getUserManager().isDefaultNode(onlyChange.value()));
|
||||
MutateResult.Change onlyChange = results.getChanges().iterator().next();
|
||||
return !(onlyChange.getType() == MutateResult.ChangeType.ADD && this.plugin.getUserManager().isDefaultNode(onlyChange.getNode()));
|
||||
}
|
||||
|
||||
return true;
|
||||
@@ -504,7 +480,7 @@ public class SqlStorage implements StorageImplementation {
|
||||
|
||||
@Override
|
||||
public void saveGroup(Group group) throws SQLException {
|
||||
Difference<Node> changes = group.normalData().exportChanges(c -> true);
|
||||
MutateResult changes = group.normalData().exportChanges(c -> true);
|
||||
|
||||
if (!changes.isEmpty()) {
|
||||
try (Connection c = this.connectionFactory.getConnection()) {
|
||||
@@ -890,58 +866,6 @@ public class SqlStorage implements StorageImplementation {
|
||||
}
|
||||
}
|
||||
|
||||
private Map<UUID, List<Node>> selectUserPermissions(Connection c, Set<UUID> users) throws SQLException {
|
||||
Map<UUID, List<Node>> map = new HashMap<>();
|
||||
for (UUID uuid : users) {
|
||||
map.put(uuid, new ArrayList<>());
|
||||
}
|
||||
|
||||
try (Statement s = c.createStatement()) {
|
||||
String sql = createUserSelectWhereClause(USER_PERMISSIONS_SELECT_MULTIPLE, users);
|
||||
try (ResultSet rs = s.executeQuery(sql)) {
|
||||
while (rs.next()) {
|
||||
UUID uuid = UUID.fromString(rs.getString("uuid"));
|
||||
Node node = readNode(rs);
|
||||
if (node != null) {
|
||||
map.get(uuid).add(readNode(rs));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
private Map<UUID, SqlPlayerData> selectPlayerData(Connection c, Set<UUID> users) throws SQLException {
|
||||
Map<UUID, SqlPlayerData> map = new HashMap<>();
|
||||
|
||||
try (Statement s = c.createStatement()) {
|
||||
String sql = createUserSelectWhereClause(PLAYER_SELECT_BY_UUID_MULTIPLE, users);
|
||||
try (ResultSet rs = s.executeQuery(sql)) {
|
||||
while (rs.next()) {
|
||||
UUID uuid = UUID.fromString(rs.getString("uuid"));
|
||||
SqlPlayerData data = new SqlPlayerData(
|
||||
rs.getString("primary_group"),
|
||||
rs.getString("username")
|
||||
);
|
||||
map.put(uuid, data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
private String createUserSelectWhereClause(String baseQuery, Set<UUID> users) {
|
||||
String param = users.stream()
|
||||
.map(uuid -> "'" + uuid + "'")
|
||||
.collect(Collectors.joining(",", "uuid IN (", ")"));
|
||||
|
||||
// we don't want to use preparedstatements because the parameter length is variable
|
||||
// safe to do string concat/replacement because the UUID.toString value isn't injectable
|
||||
return this.statementProcessor.apply(baseQuery) + param;
|
||||
}
|
||||
|
||||
private void deleteUser(Connection c, UUID user) throws SQLException {
|
||||
try (PreparedStatement ps = c.prepareStatement(this.statementProcessor.apply(USER_PERMISSIONS_DELETE))) {
|
||||
ps.setString(1, user.toString());
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
/*
|
||||
* This file is part of LuckPerms, licensed under the MIT License.
|
||||
*
|
||||
* Copyright (c) lucko (Luck) <luck@lucko.me>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* 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.common.util;
|
||||
|
||||
import com.google.common.collect.ImmutableList;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Collector;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public final class CompletableFutures {
|
||||
private CompletableFutures() {}
|
||||
|
||||
public static <T extends CompletableFuture<?>> Collector<T, ImmutableList.Builder<T>, CompletableFuture<Void>> collector() {
|
||||
return Collector.of(
|
||||
ImmutableList.Builder::new,
|
||||
ImmutableList.Builder::add,
|
||||
(l, r) -> l.addAll(r.build()),
|
||||
builder -> allOf(builder.build())
|
||||
);
|
||||
}
|
||||
|
||||
public static CompletableFuture<Void> allOf(Stream<? extends CompletableFuture<?>> futures) {
|
||||
CompletableFuture<?>[] arr = futures.toArray(CompletableFuture[]::new);
|
||||
return CompletableFuture.allOf(arr);
|
||||
}
|
||||
|
||||
public static CompletableFuture<Void> allOf(Collection<? extends CompletableFuture<?>> futures) {
|
||||
CompletableFuture<?>[] arr = futures.toArray(new CompletableFuture[0]);
|
||||
return CompletableFuture.allOf(arr);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,208 +0,0 @@
|
||||
/*
|
||||
* This file is part of LuckPerms, licensed under the MIT License.
|
||||
*
|
||||
* Copyright (c) lucko (Luck) <luck@lucko.me>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* 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.common.util;
|
||||
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Records a log of the changes that occur as a result
|
||||
* of mutations (add or remove operations).
|
||||
*
|
||||
* @param <T> the value type
|
||||
*/
|
||||
public class Difference<T> {
|
||||
private final LinkedHashSet<Change<T>> changes = new LinkedHashSet<>();
|
||||
|
||||
/**
|
||||
* Gets the recorded changes.
|
||||
*
|
||||
* @return the changes
|
||||
*/
|
||||
public Set<Change<T>> getChanges() {
|
||||
return this.changes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets if no changes have been recorded.
|
||||
*
|
||||
* @return if no changes have been recorded
|
||||
*/
|
||||
public boolean isEmpty() {
|
||||
return this.changes.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the recorded changes of a given type
|
||||
*
|
||||
* @param type the type of change
|
||||
* @return the changes
|
||||
*/
|
||||
public Set<T> getChanges(ChangeType type) {
|
||||
Set<T> changes = new LinkedHashSet<>(this.changes.size());
|
||||
for (Change<T> change : this.changes) {
|
||||
if (change.type() == type) {
|
||||
changes.add(change.value());
|
||||
}
|
||||
}
|
||||
return changes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the values that have been added.
|
||||
*
|
||||
* @return the added values
|
||||
*/
|
||||
public Set<T> getAdded() {
|
||||
return getChanges(ChangeType.ADD);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the values that have been removed.
|
||||
*
|
||||
* @return the removed values
|
||||
*/
|
||||
public Set<T> getRemoved() {
|
||||
return getChanges(ChangeType.REMOVE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears all recorded changes.
|
||||
*/
|
||||
public void clear() {
|
||||
this.changes.clear();
|
||||
}
|
||||
|
||||
private void recordChange(Change<T> change) {
|
||||
// This method is the magic of this class.
|
||||
// When tracking, we want to ignore changes that cancel each other out, and only
|
||||
// keep track of the net difference.
|
||||
// e.g. adding then removing the same value = zero net change, so ignore it.
|
||||
|
||||
if (this.changes.remove(change.inverse())) {
|
||||
return;
|
||||
}
|
||||
this.changes.add(change);
|
||||
}
|
||||
|
||||
/**
|
||||
* Records a change.
|
||||
*
|
||||
* @param type the type of change
|
||||
* @param value the changed value
|
||||
*/
|
||||
public void recordChange(ChangeType type, T value) {
|
||||
recordChange(new Change<>(type, value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Records some changes.
|
||||
*
|
||||
* @param type the type of change
|
||||
* @param values the changed values
|
||||
*/
|
||||
public void recordChanges(ChangeType type, Iterable<T> values) {
|
||||
for (T value : values) {
|
||||
recordChange(new Change<>(type, value));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges the recorded differences in {@code other} into this.
|
||||
*
|
||||
* @param other the other differences
|
||||
* @return this
|
||||
*/
|
||||
public Difference<T> mergeFrom(Difference<T> other) {
|
||||
for (Change<T> change : other.changes) {
|
||||
recordChange(change);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Difference{" + this.changes + '}';
|
||||
}
|
||||
|
||||
/**
|
||||
* A single change recorded in the {@link Difference} tracker.
|
||||
*
|
||||
* @param <T> the value type
|
||||
*/
|
||||
public static final class Change<T> {
|
||||
private final ChangeType type;
|
||||
private final T value;
|
||||
|
||||
public Change(ChangeType type, T value) {
|
||||
this.type = type;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public ChangeType type() {
|
||||
return this.type;
|
||||
}
|
||||
|
||||
public T value() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
public Change<T> inverse() {
|
||||
return new Change<>(this.type.inverse(), this.value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Change<?> change = (Change<?>) o;
|
||||
return this.type == change.type && this.value.equals(change.value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(this.type, this.value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "(" + this.type + ": " + this.value + ')';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The type of change.
|
||||
*/
|
||||
public enum ChangeType {
|
||||
ADD, REMOVE;
|
||||
|
||||
public ChangeType inverse() {
|
||||
return this == ADD ? REMOVE : ADD;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+15
-7
@@ -23,18 +23,26 @@
|
||||
* SOFTWARE.
|
||||
*/
|
||||
|
||||
package me.lucko.luckperms.common.plugin.bootstrap;
|
||||
package me.lucko.luckperms.common.webeditor;
|
||||
|
||||
/**
|
||||
* A {@link LuckPermsBootstrap} that was bootstrapped by a loader.
|
||||
* Represents the state of a web editor session
|
||||
*/
|
||||
public interface BootstrappedWithLoader {
|
||||
enum SessionState {
|
||||
|
||||
/**
|
||||
* Gets the loader object that did the bootstrapping.
|
||||
*
|
||||
* @return the loader
|
||||
* The session is not known to this server.
|
||||
*/
|
||||
Object getLoader();
|
||||
NOT_KNOWN,
|
||||
|
||||
/**
|
||||
* The session is in progress - it has been created, but updates have not been applied.
|
||||
*/
|
||||
IN_PROGRESS,
|
||||
|
||||
/**
|
||||
* The session is complete - updates have been applied.
|
||||
*/
|
||||
COMPLETED
|
||||
|
||||
}
|
||||
@@ -28,11 +28,14 @@ package me.lucko.luckperms.common.webeditor;
|
||||
import com.google.common.base.Preconditions;
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
import me.lucko.luckperms.common.config.ConfigKeys;
|
||||
import me.lucko.luckperms.common.context.ImmutableContextSetImpl;
|
||||
import me.lucko.luckperms.common.context.serializer.ContextSetJsonSerializer;
|
||||
import me.lucko.luckperms.common.http.AbstractHttpClient;
|
||||
import me.lucko.luckperms.common.http.UnsuccessfulRequestException;
|
||||
import me.lucko.luckperms.common.locale.Message;
|
||||
import me.lucko.luckperms.common.model.Group;
|
||||
import me.lucko.luckperms.common.model.PermissionHolder;
|
||||
import me.lucko.luckperms.common.model.PermissionHolderIdentifier;
|
||||
import me.lucko.luckperms.common.model.Track;
|
||||
import me.lucko.luckperms.common.model.User;
|
||||
import me.lucko.luckperms.common.node.matcher.ConstraintNodeMatcher;
|
||||
@@ -40,7 +43,6 @@ import me.lucko.luckperms.common.node.utils.NodeJsonSerializer;
|
||||
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
|
||||
import me.lucko.luckperms.common.sender.Sender;
|
||||
import me.lucko.luckperms.common.storage.misc.NodeEntry;
|
||||
import me.lucko.luckperms.common.util.ImmutableCollectors;
|
||||
import me.lucko.luckperms.common.util.gson.GsonProvider;
|
||||
import me.lucko.luckperms.common.util.gson.JArray;
|
||||
import me.lucko.luckperms.common.util.gson.JObject;
|
||||
@@ -61,11 +63,8 @@ import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
@@ -76,48 +75,6 @@ public class WebEditorRequest {
|
||||
|
||||
public static final int MAX_USERS = 500;
|
||||
|
||||
/**
|
||||
* The encoded json object this payload is made up of
|
||||
*/
|
||||
private final JsonObject payload;
|
||||
|
||||
private final Map<PermissionHolderIdentifier, List<Node>> holders;
|
||||
private final Map<String, List<String>> tracks;
|
||||
|
||||
private WebEditorRequest(JsonObject payload, Map<PermissionHolder, List<Node>> holders, Map<Track, List<String>> tracks) {
|
||||
this.payload = payload;
|
||||
this.holders = holders.entrySet().stream().collect(ImmutableCollectors.toMap(
|
||||
e -> e.getKey().getIdentifier(),
|
||||
Map.Entry::getValue
|
||||
));
|
||||
this.tracks = tracks.entrySet().stream().collect(ImmutableCollectors.toMap(
|
||||
e -> e.getKey().getName(),
|
||||
Map.Entry::getValue
|
||||
));
|
||||
}
|
||||
|
||||
public JsonObject getPayload() {
|
||||
return this.payload;
|
||||
}
|
||||
|
||||
public byte[] encode() {
|
||||
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
|
||||
try (Writer writer = new OutputStreamWriter(new GZIPOutputStream(bytesOut), StandardCharsets.UTF_8)) {
|
||||
GsonProvider.normal().toJson(this.payload, writer);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return bytesOut.toByteArray();
|
||||
}
|
||||
|
||||
public Map<PermissionHolderIdentifier, List<Node>> getHolders() {
|
||||
return this.holders;
|
||||
}
|
||||
|
||||
public Map<String, List<String>> getTracks() {
|
||||
return this.tracks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a web editor request payload.
|
||||
*
|
||||
@@ -138,35 +95,34 @@ public class WebEditorRequest {
|
||||
}
|
||||
|
||||
// form the payload data
|
||||
Map<PermissionHolder, List<Node>> holdersMap = holders.stream().collect(ImmutableCollectors.toMap(
|
||||
Function.identity(),
|
||||
holder -> holder.normalData().asList()
|
||||
));
|
||||
|
||||
Map<Track, List<String>> tracksMap = tracks.stream().collect(ImmutableCollectors.toMap(
|
||||
Function.identity(),
|
||||
Track::getGroups
|
||||
));
|
||||
|
||||
JsonObject json = createJsonPayload(holdersMap, tracksMap, sender, cmdLabel, potentialContexts.build(), plugin).toJson();
|
||||
return new WebEditorRequest(json, holdersMap, tracksMap);
|
||||
return new WebEditorRequest(holders, tracks, sender, cmdLabel, potentialContexts.build(), plugin);
|
||||
}
|
||||
|
||||
private static JObject createJsonPayload(Map<PermissionHolder, List<Node>> holders, Map<Track, List<String>> tracks, Sender sender, String cmdLabel, ImmutableContextSet potentialContexts, LuckPermsPlugin plugin) {
|
||||
return new JObject()
|
||||
/**
|
||||
* The encoded json object this payload is made up of
|
||||
*/
|
||||
private final JsonObject payload;
|
||||
|
||||
private WebEditorRequest(List<PermissionHolder> holders, List<Track> tracks, Sender sender, String cmdLabel, ImmutableContextSet potentialContexts, LuckPermsPlugin plugin) {
|
||||
this.payload = new JObject()
|
||||
.add("metadata", formMetadata(sender, cmdLabel, plugin.getBootstrap().getVersion()))
|
||||
.add("permissionHolders", new JArray().consume(arr ->
|
||||
holders.forEach((holder, data) ->
|
||||
arr.add(formPermissionHolder(holder, data))
|
||||
)
|
||||
))
|
||||
.add("tracks", new JArray().consume(arr ->
|
||||
tracks.forEach((track, data) ->
|
||||
arr.add(formTrack(track, data))
|
||||
)
|
||||
))
|
||||
.add("permissionHolders", new JArray()
|
||||
.consume(arr -> {
|
||||
for (PermissionHolder holder : holders) {
|
||||
arr.add(formPermissionHolder(holder));
|
||||
}
|
||||
})
|
||||
)
|
||||
.add("tracks", new JArray()
|
||||
.consume(arr -> {
|
||||
for (Track track : tracks) {
|
||||
arr.add(formTrack(track));
|
||||
}
|
||||
})
|
||||
)
|
||||
.add("knownPermissions", new JArray().addAll(plugin.getPermissionRegistry().rootAsList()))
|
||||
.add("potentialContexts", ContextSetJsonSerializer.serialize(potentialContexts));
|
||||
.add("potentialContexts", ContextSetJsonSerializer.serialize(potentialContexts))
|
||||
.toJson();
|
||||
}
|
||||
|
||||
private static JObject formMetadata(Sender sender, String cmdLabel, String pluginVersion) {
|
||||
@@ -180,19 +136,56 @@ public class WebEditorRequest {
|
||||
.add("pluginVersion", pluginVersion);
|
||||
}
|
||||
|
||||
private static JObject formPermissionHolder(PermissionHolder holder, List<Node> data) {
|
||||
private static JObject formPermissionHolder(PermissionHolder holder) {
|
||||
return new JObject()
|
||||
.add("type", holder.getType().toString())
|
||||
.add("id", holder.getIdentifier().getName())
|
||||
.add("displayName", holder.getPlainDisplayName())
|
||||
.add("nodes", NodeJsonSerializer.serializeNodes(data));
|
||||
.add("nodes", NodeJsonSerializer.serializeNodes(holder.normalData().asList()));
|
||||
}
|
||||
|
||||
private static JObject formTrack(Track track, List<String> data) {
|
||||
private static JObject formTrack(Track track) {
|
||||
return new JObject()
|
||||
.add("type", "track")
|
||||
.add("id", track.getName())
|
||||
.add("groups", new JArray().addAll(data));
|
||||
.add("groups", new JArray().addAll(track.getGroups()));
|
||||
}
|
||||
|
||||
public byte[] encode() {
|
||||
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
|
||||
try (Writer writer = new OutputStreamWriter(new GZIPOutputStream(bytesOut), StandardCharsets.UTF_8)) {
|
||||
GsonProvider.normal().toJson(this.payload, writer);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return bytesOut.toByteArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a web editor session, and sends the URL to the sender.
|
||||
*
|
||||
* @param plugin the plugin
|
||||
* @param sender the sender creating the session
|
||||
* @return the command result
|
||||
*/
|
||||
public void createSession(LuckPermsPlugin plugin, Sender sender) {
|
||||
String pasteId;
|
||||
try {
|
||||
pasteId = plugin.getBytebin().postContent(encode(), AbstractHttpClient.JSON_TYPE).key();
|
||||
} catch (UnsuccessfulRequestException e) {
|
||||
Message.EDITOR_HTTP_REQUEST_FAILURE.send(sender, e.getResponse().code(), e.getResponse().message());
|
||||
return;
|
||||
} catch (IOException e) {
|
||||
new RuntimeException("Error uploading data to bytebin", e).printStackTrace();
|
||||
Message.EDITOR_HTTP_UNKNOWN_FAILURE.send(sender);
|
||||
return;
|
||||
}
|
||||
|
||||
plugin.getWebEditorSessionStore().addNewSession(pasteId);
|
||||
|
||||
// form a url for the editor
|
||||
String url = plugin.getConfiguration().get(ConfigKeys.WEB_EDITOR_URL_PATTERN) + pasteId;
|
||||
Message.EDITOR_URL.send(sender, url);
|
||||
}
|
||||
|
||||
public static void includeMatchingGroups(List<? super Group> holders, Predicate<? super Group> filter, LuckPermsPlugin plugin) {
|
||||
@@ -259,24 +252,17 @@ public class WebEditorRequest {
|
||||
.distinct();
|
||||
}
|
||||
|
||||
Set<UUID> uuids = stream
|
||||
.filter(uuid -> !users.containsKey(uuid))
|
||||
stream.filter(uuid -> !users.containsKey(uuid))
|
||||
.sorted()
|
||||
.limit(MAX_USERS - users.size())
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
if (uuids.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// load users in bulk from storage
|
||||
Map<UUID, User> loadedUsers = plugin.getStorage().loadUsers(uuids).join();
|
||||
users.putAll(loadedUsers);
|
||||
|
||||
// schedule cleanup
|
||||
for (UUID uniqueId : loadedUsers.keySet()) {
|
||||
plugin.getUserManager().getHouseKeeper().cleanup(uniqueId);
|
||||
}
|
||||
.map(uuid -> plugin.getStorage().loadUser(uuid, null))
|
||||
.forEach(fut -> {
|
||||
User user = fut.join();
|
||||
if (user != null) {
|
||||
users.put(user.getUniqueId(), user);
|
||||
plugin.getUserManager().getHouseKeeper().cleanup(user.getUniqueId());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -40,12 +40,11 @@ import me.lucko.luckperms.common.model.PermissionHolder;
|
||||
import me.lucko.luckperms.common.model.Track;
|
||||
import me.lucko.luckperms.common.model.User;
|
||||
import me.lucko.luckperms.common.model.manager.group.GroupManager;
|
||||
import me.lucko.luckperms.common.model.nodemap.MutateResult;
|
||||
import me.lucko.luckperms.common.node.utils.NodeJsonSerializer;
|
||||
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
|
||||
import me.lucko.luckperms.common.sender.Sender;
|
||||
import me.lucko.luckperms.common.util.Difference;
|
||||
import me.lucko.luckperms.common.util.Uuids;
|
||||
import me.lucko.luckperms.common.webeditor.store.RemoteSession;
|
||||
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.luckperms.api.actionlog.Action;
|
||||
@@ -56,6 +55,7 @@ import net.luckperms.api.node.Node;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
@@ -86,31 +86,41 @@ public class WebEditorResponse {
|
||||
* @param plugin the plugin
|
||||
* @param sender the sender who is applying the session
|
||||
*/
|
||||
public void apply(LuckPermsPlugin plugin, Sender sender, WebEditorSession editorSession, String commandLabel, boolean ignoreSessionWarning) {
|
||||
String sessionId = this.payload.get("sessionId").getAsString();
|
||||
RemoteSession remoteSession = plugin.getWebEditorStore().sessions().getSession(sessionId);
|
||||
public void apply(LuckPermsPlugin plugin, Sender sender, String commandLabel, boolean ignoreSessionWarning) {
|
||||
JsonElement sessionIdJson = this.payload.get("sessionId");
|
||||
if (sessionIdJson != null) {
|
||||
String sessionId = sessionIdJson.getAsString();
|
||||
WebEditorSessionStore sessionStore = plugin.getWebEditorSessionStore();
|
||||
|
||||
if (remoteSession == null) {
|
||||
// session is unknown
|
||||
if (!ignoreSessionWarning) {
|
||||
Message.APPLY_EDITS_SESSION_UNKNOWN.send(sender, this.id, commandLabel);
|
||||
return;
|
||||
}
|
||||
} else if (remoteSession.isCompleted()) {
|
||||
// session has been completed already
|
||||
if (!ignoreSessionWarning) {
|
||||
Message.APPLY_EDITS_SESSION_APPLIED_ALREADY.send(sender, this.id, commandLabel);
|
||||
return;
|
||||
SessionState state = sessionStore.getSessionState(sessionId);
|
||||
switch (state) {
|
||||
case COMPLETED:
|
||||
if (!ignoreSessionWarning) {
|
||||
Message.APPLY_EDITS_SESSION_APPLIED_ALREADY.send(sender, this.id, commandLabel);
|
||||
return;
|
||||
}
|
||||
break;
|
||||
case NOT_KNOWN:
|
||||
if (!ignoreSessionWarning) {
|
||||
Message.APPLY_EDITS_SESSION_UNKNOWN.send(sender, this.id, commandLabel);
|
||||
return;
|
||||
}
|
||||
break;
|
||||
case IN_PROGRESS:
|
||||
sessionStore.markSessionCompleted(sessionId);
|
||||
break;
|
||||
default:
|
||||
throw new AssertionError(state);
|
||||
}
|
||||
}
|
||||
|
||||
ChangeApplier changeApplier = new ChangeApplier(plugin, sender, editorSession, remoteSession);
|
||||
Session session = new Session(plugin, sender);
|
||||
boolean work = false;
|
||||
|
||||
if (this.payload.has("changes")) {
|
||||
JsonArray changes = this.payload.get("changes").getAsJsonArray();
|
||||
for (JsonElement change : changes) {
|
||||
if (changeApplier.applyChange(change.getAsJsonObject())) {
|
||||
if (session.applyChange(change.getAsJsonObject())) {
|
||||
work = true;
|
||||
}
|
||||
}
|
||||
@@ -118,7 +128,7 @@ public class WebEditorResponse {
|
||||
if (this.payload.has("userDeletions")) {
|
||||
JsonArray userDeletions = this.payload.get("userDeletions").getAsJsonArray();
|
||||
for (JsonElement userDeletion : userDeletions) {
|
||||
if (changeApplier.applyUserDelete(userDeletion)) {
|
||||
if (session.applyUserDelete(userDeletion)) {
|
||||
work = true;
|
||||
}
|
||||
}
|
||||
@@ -126,7 +136,7 @@ public class WebEditorResponse {
|
||||
if (this.payload.has("groupDeletions")) {
|
||||
JsonArray groupDeletions = this.payload.get("groupDeletions").getAsJsonArray();
|
||||
for (JsonElement groupDeletion : groupDeletions) {
|
||||
if (changeApplier.applyGroupDelete(groupDeletion)) {
|
||||
if (session.applyGroupDelete(groupDeletion)) {
|
||||
work = true;
|
||||
}
|
||||
}
|
||||
@@ -134,16 +144,12 @@ public class WebEditorResponse {
|
||||
if (this.payload.has("trackDeletions")) {
|
||||
JsonArray trackDeletions = this.payload.get("trackDeletions").getAsJsonArray();
|
||||
for (JsonElement trackDeletion : trackDeletions) {
|
||||
if (changeApplier.applyTrackDelete(trackDeletion)) {
|
||||
if (session.applyTrackDelete(trackDeletion)) {
|
||||
work = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (remoteSession != null) {
|
||||
remoteSession.complete();
|
||||
}
|
||||
|
||||
if (!work) {
|
||||
Message.APPLY_EDITS_TARGET_NO_CHANGES_PRESENT.send(sender);
|
||||
}
|
||||
@@ -152,17 +158,13 @@ public class WebEditorResponse {
|
||||
/**
|
||||
* Represents the application of a given editor session on this platform.
|
||||
*/
|
||||
private static class ChangeApplier {
|
||||
private static class Session {
|
||||
private final LuckPermsPlugin plugin;
|
||||
private final Sender sender;
|
||||
private final WebEditorSession session;
|
||||
private final RemoteSession remoteSession;
|
||||
|
||||
ChangeApplier(LuckPermsPlugin plugin, Sender sender, WebEditorSession session, RemoteSession remoteSession) {
|
||||
Session(LuckPermsPlugin plugin, Sender sender) {
|
||||
this.plugin = plugin;
|
||||
this.sender = sender;
|
||||
this.session = session;
|
||||
this.remoteSession = remoteSession;
|
||||
}
|
||||
|
||||
private boolean applyChange(JsonObject changeInfo) {
|
||||
@@ -200,9 +202,6 @@ public class WebEditorResponse {
|
||||
holder = this.plugin.getStorage().loadGroup(id).join().orElse(null);
|
||||
if (holder == null) {
|
||||
holder = this.plugin.getStorage().createAndLoadGroup(id, CreationCause.WEB_EDITOR).join();
|
||||
if (this.session != null) {
|
||||
this.session.includeCreatedGroup((Group) holder);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -212,7 +211,7 @@ public class WebEditorResponse {
|
||||
}
|
||||
|
||||
Set<Node> nodes = NodeJsonSerializer.deserializeNodes(changeInfo.getAsJsonArray("nodes"));
|
||||
Difference<Node> res = applyNodeChanges(holder, nodes);
|
||||
MutateResult res = holder.setNodes(DataType.NORMAL, nodes, true);
|
||||
|
||||
if (res.isEmpty()) {
|
||||
return false;
|
||||
@@ -234,51 +233,22 @@ public class WebEditorResponse {
|
||||
|
||||
Message.APPLY_EDITS_SUCCESS.send(this.sender, type, holder.getFormattedDisplayName());
|
||||
Message.APPLY_EDITS_SUCCESS_SUMMARY.send(this.sender, added.size(), removed.size());
|
||||
|
||||
for (Node n : added) {
|
||||
Message.APPLY_EDITS_DIFF_ADDED.send(this.sender, n);
|
||||
}
|
||||
for (Node n : removed) {
|
||||
Message.APPLY_EDITS_DIFF_REMOVED.send(this.sender, n);
|
||||
}
|
||||
|
||||
StorageAssistant.save(holder, this.sender, this.plugin);
|
||||
return true;
|
||||
}
|
||||
|
||||
private Difference<Node> applyNodeChanges(PermissionHolder holder, Set<Node> nodes) {
|
||||
if (this.remoteSession != null) {
|
||||
|
||||
WebEditorRequest request = this.remoteSession.request();
|
||||
if (request != null) {
|
||||
|
||||
List<Node> nodesBefore = request.getHolders().get(holder.getIdentifier());
|
||||
if (nodesBefore != null) {
|
||||
|
||||
// if the initial data sent to the remote session is still known
|
||||
// use that to calculate a diff of the changes made to avoid overriding
|
||||
// modified/added/removed nodes since the editor session was created
|
||||
Difference<Node> diff = new Difference<>();
|
||||
diff.recordChanges(Difference.ChangeType.REMOVE, nodesBefore);
|
||||
diff.recordChanges(Difference.ChangeType.ADD, nodes);
|
||||
|
||||
return holder.setNodes(DataType.NORMAL, diff, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return holder.setNodes(DataType.NORMAL, nodes, true);
|
||||
}
|
||||
|
||||
private boolean applyTrackChange(JsonObject changeInfo) {
|
||||
String id = changeInfo.get("id").getAsString();
|
||||
|
||||
Track track = this.plugin.getStorage().loadTrack(id).join().orElse(null);
|
||||
if (track == null) {
|
||||
track = this.plugin.getStorage().createAndLoadTrack(id, CreationCause.WEB_EDITOR).join();
|
||||
if (this.session != null) {
|
||||
this.session.includeCreatedTrack(track);
|
||||
}
|
||||
}
|
||||
|
||||
if (ArgumentPermissions.checkModifyPerms(this.plugin, this.sender, CommandPermission.APPLY_EDITS, track)) {
|
||||
@@ -294,33 +264,32 @@ public class WebEditorResponse {
|
||||
return false;
|
||||
}
|
||||
|
||||
Difference<String> diff = new Difference<>();
|
||||
diff.recordChanges(Difference.ChangeType.REMOVE, before);
|
||||
diff.recordChanges(Difference.ChangeType.ADD, after);
|
||||
Set<String> diffAdded = getAdded(before, after);
|
||||
Set<String> diffRemoved = getRemoved(before, after);
|
||||
|
||||
Set<String> added = diff.getAdded();
|
||||
Set<String> removed = diff.getRemoved();
|
||||
int additions = diffAdded.size();
|
||||
int deletions = diffRemoved.size();
|
||||
|
||||
track.setGroups(after);
|
||||
|
||||
if (hasBeenReordered(before, after, added, removed)) {
|
||||
if (hasBeenReordered(before, after, diffAdded, diffRemoved)) {
|
||||
LoggedAction.build().source(this.sender).target(track)
|
||||
.description("webeditor", "reorder", after)
|
||||
.build().submit(this.plugin, this.sender);
|
||||
}
|
||||
for (String n : added) {
|
||||
for (String n : diffAdded) {
|
||||
LoggedAction.build().source(this.sender).target(track)
|
||||
.description("webeditor", "add", n)
|
||||
.build().submit(this.plugin, this.sender);
|
||||
}
|
||||
for (String n : removed) {
|
||||
for (String n : diffRemoved) {
|
||||
LoggedAction.build().source(this.sender).target(track)
|
||||
.description("webeditor", "remove", n)
|
||||
.build().submit(this.plugin, this.sender);
|
||||
}
|
||||
|
||||
Message.APPLY_EDITS_SUCCESS.send(this.sender, "track", Component.text(track.getName()));
|
||||
Message.APPLY_EDITS_SUCCESS_SUMMARY.send(this.sender, added.size(), removed.size());
|
||||
Message.APPLY_EDITS_SUCCESS_SUMMARY.send(this.sender, additions, deletions);
|
||||
Message.APPLY_EDITS_TRACK_BEFORE.send(this.sender, before);
|
||||
Message.APPLY_EDITS_TRACK_AFTER.send(this.sender, after);
|
||||
|
||||
@@ -370,10 +339,6 @@ public class WebEditorResponse {
|
||||
.description("webeditor", "delete")
|
||||
.build().submit(this.plugin, this.sender);
|
||||
|
||||
if (this.session != null) {
|
||||
this.session.excludeDeletedUser(user);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -409,10 +374,6 @@ public class WebEditorResponse {
|
||||
.description("webeditor", "delete")
|
||||
.build().submit(this.plugin, this.sender);
|
||||
|
||||
if (this.session != null) {
|
||||
this.session.excludeDeletedGroup(group);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -443,13 +404,21 @@ public class WebEditorResponse {
|
||||
.description("webeditor", "delete")
|
||||
.build().submit(this.plugin, this.sender);
|
||||
|
||||
if (this.session != null) {
|
||||
this.session.excludeDeletedTrack(track);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static <T> Set<T> getAdded(Collection<T> before, Collection<T> after) {
|
||||
Set<T> added = new LinkedHashSet<>(after);
|
||||
added.removeAll(before);
|
||||
return added;
|
||||
}
|
||||
|
||||
private static <T> Set<T> getRemoved(Collection<T> before, Collection<T> after) {
|
||||
Set<T> removed = new LinkedHashSet<>(before);
|
||||
removed.removeAll(after);
|
||||
return removed;
|
||||
}
|
||||
|
||||
private static <T> boolean hasBeenReordered(List<T> before, List<T> after, Collection<T> diffAdded, Collection<T> diffRemoved) {
|
||||
after = new ArrayList<>(after);
|
||||
before = new ArrayList<>(before);
|
||||
|
||||
@@ -1,215 +0,0 @@
|
||||
/*
|
||||
* This file is part of LuckPerms, licensed under the MIT License.
|
||||
*
|
||||
* Copyright (c) lucko (Luck) <luck@lucko.me>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* 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.common.webeditor;
|
||||
|
||||
import me.lucko.luckperms.common.config.ConfigKeys;
|
||||
import me.lucko.luckperms.common.http.AbstractHttpClient;
|
||||
import me.lucko.luckperms.common.http.UnsuccessfulRequestException;
|
||||
import me.lucko.luckperms.common.locale.Message;
|
||||
import me.lucko.luckperms.common.model.Group;
|
||||
import me.lucko.luckperms.common.model.PermissionHolder;
|
||||
import me.lucko.luckperms.common.model.PermissionHolderIdentifier;
|
||||
import me.lucko.luckperms.common.model.Track;
|
||||
import me.lucko.luckperms.common.model.User;
|
||||
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
|
||||
import me.lucko.luckperms.common.sender.Sender;
|
||||
import me.lucko.luckperms.common.webeditor.socket.WebEditorSocket;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Encapsulates a session with the web editor.
|
||||
*
|
||||
* <p>A session is tied to a specific user, and can comprise of multiple requests to and
|
||||
* responses from the web editor.</p>
|
||||
*/
|
||||
public class WebEditorSession {
|
||||
|
||||
public static void createAndOpen(List<PermissionHolder> holders, List<Track> tracks, Sender sender, String cmdLabel, LuckPermsPlugin plugin) {
|
||||
WebEditorRequest initialRequest = WebEditorRequest.generate(holders, tracks, sender, cmdLabel, plugin);
|
||||
WebEditorSession session = new WebEditorSession(initialRequest, plugin, sender, cmdLabel);
|
||||
session.open();
|
||||
}
|
||||
|
||||
private WebEditorRequest initialRequest;
|
||||
|
||||
private final LuckPermsPlugin plugin;
|
||||
private final Sender sender;
|
||||
private final String cmdLabel;
|
||||
|
||||
private final Set<PermissionHolderIdentifier> holders;
|
||||
private final Set<String> tracks;
|
||||
|
||||
private WebEditorSocket socket = null;
|
||||
|
||||
public WebEditorSession(WebEditorRequest initialRequest, LuckPermsPlugin plugin, Sender sender, String cmdLabel) {
|
||||
this.initialRequest = initialRequest;
|
||||
this.plugin = plugin;
|
||||
this.sender = sender;
|
||||
this.cmdLabel = cmdLabel;
|
||||
|
||||
this.holders = new HashSet<>(initialRequest.getHolders().keySet());
|
||||
this.tracks = new HashSet<>(initialRequest.getTracks().keySet());
|
||||
}
|
||||
|
||||
public void open() {
|
||||
createSocket();
|
||||
createInitialSession();
|
||||
}
|
||||
|
||||
private void createSocket() {
|
||||
try {
|
||||
// create and connect to a socket
|
||||
WebEditorSocket socket = new WebEditorSocket(this.plugin, this.sender, this);
|
||||
socket.initialize(this.plugin.getBytesocks());
|
||||
socket.waitForConnect(5, TimeUnit.SECONDS);
|
||||
|
||||
this.socket = socket;
|
||||
this.plugin.getWebEditorStore().sockets().putSocket(this.sender, this.socket);
|
||||
} catch (Exception e) {
|
||||
if (!ignoreSocketConnectError(e)) {
|
||||
this.plugin.getLogger().warn("Unable to establish socket connection", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean ignoreSocketConnectError(Exception e) {
|
||||
if (e instanceof UnsuccessfulRequestException) {
|
||||
UnsuccessfulRequestException req = (UnsuccessfulRequestException) e;
|
||||
int code = req.getResponse().code();
|
||||
|
||||
// 502 - bad gateway / 503 - service unavailable
|
||||
// probably means the socket service is offline, that's ok, no need to send a warning
|
||||
return code == 502 || code == 503;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void createInitialSession() {
|
||||
Objects.requireNonNull(this.initialRequest);
|
||||
|
||||
WebEditorRequest request = this.initialRequest;
|
||||
this.initialRequest = null;
|
||||
|
||||
if (this.socket != null) {
|
||||
this.socket.appendDetailToRequest(request);
|
||||
}
|
||||
|
||||
String id = uploadRequestData(request);
|
||||
if (id == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// form a url for the editor
|
||||
String url = this.plugin.getConfiguration().get(ConfigKeys.WEB_EDITOR_URL_PATTERN) + id;
|
||||
Message.EDITOR_URL.send(this.sender, url);
|
||||
|
||||
// schedule socket close
|
||||
if (this.socket != null) {
|
||||
this.socket.scheduleCleanupIfUnused();
|
||||
}
|
||||
}
|
||||
|
||||
public void includeCreatedGroup(Group group) {
|
||||
this.holders.add(group.getIdentifier());
|
||||
}
|
||||
|
||||
public void includeCreatedTrack(Track track) {
|
||||
this.tracks.add(track.getName());
|
||||
}
|
||||
|
||||
public void excludeDeletedUser(User user) {
|
||||
this.holders.remove(user.getIdentifier());
|
||||
}
|
||||
|
||||
public void excludeDeletedGroup(Group group) {
|
||||
this.holders.remove(group.getIdentifier());
|
||||
}
|
||||
|
||||
public void excludeDeletedTrack(Track track) {
|
||||
this.tracks.remove(track.getName());
|
||||
}
|
||||
|
||||
public String createFollowUpSession() {
|
||||
List<PermissionHolder> holders = this.holders.stream()
|
||||
.map(id -> {
|
||||
switch (id.getType()) {
|
||||
case PermissionHolderIdentifier.USER_TYPE:
|
||||
return this.plugin.getStorage().loadUser(UUID.fromString(id.getName()), null);
|
||||
case PermissionHolderIdentifier.GROUP_TYPE:
|
||||
return this.plugin.getStorage().loadGroup(id.getName()).thenApply(o -> o.orElse(null));
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.filter(Objects::nonNull)
|
||||
.map(CompletableFuture::join)
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
List<Track> tracks = this.tracks.stream()
|
||||
.map(id -> this.plugin.getStorage().loadTrack(id).thenApply(o -> o.orElse(null)))
|
||||
.map(CompletableFuture::join)
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return uploadRequestData(WebEditorRequest.generate(holders, tracks, this.sender, this.cmdLabel, this.plugin));
|
||||
}
|
||||
|
||||
public String getCommandLabel() {
|
||||
return this.cmdLabel;
|
||||
}
|
||||
|
||||
private String uploadRequestData(WebEditorRequest request) {
|
||||
byte[] requestBuf = request.encode();
|
||||
|
||||
String pasteId;
|
||||
try {
|
||||
pasteId = this.plugin.getBytebin().postContent(requestBuf, AbstractHttpClient.JSON_TYPE, "editor").key();
|
||||
} catch (UnsuccessfulRequestException e) {
|
||||
Message.EDITOR_HTTP_REQUEST_FAILURE.send(this.sender, e.getResponse().code(), e.getResponse().message());
|
||||
return null;
|
||||
} catch (IOException e) {
|
||||
new RuntimeException("Error uploading data to bytebin", e).printStackTrace();
|
||||
Message.EDITOR_HTTP_UNKNOWN_FAILURE.send(this.sender);
|
||||
return null;
|
||||
}
|
||||
|
||||
this.plugin.getWebEditorStore().sessions().addNewSession(pasteId, request);
|
||||
return pasteId;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+22
-12
@@ -23,35 +23,45 @@
|
||||
* SOFTWARE.
|
||||
*/
|
||||
|
||||
package me.lucko.luckperms.common.webeditor.store;
|
||||
package me.lucko.luckperms.common.webeditor;
|
||||
|
||||
import me.lucko.luckperms.common.webeditor.WebEditorRequest;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public final class WebEditorSessionMap {
|
||||
private final Map<String, RemoteSession> sessions = new ConcurrentHashMap<>();
|
||||
/**
|
||||
* Contains a store of known web editor sessions.
|
||||
*/
|
||||
public class WebEditorSessionStore {
|
||||
private final Map<String, SessionState> sessions = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* Adds a newly created session to the store.
|
||||
*
|
||||
* @param id the id of the session
|
||||
*/
|
||||
public void addNewSession(String id, WebEditorRequest request) {
|
||||
this.sessions.put(id, new RemoteSession(request));
|
||||
public void addNewSession(String id) {
|
||||
this.sessions.put(id, SessionState.IN_PROGRESS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the session for the given session id.
|
||||
* Gets the session state for the given session id.
|
||||
*
|
||||
* @param id the id of the session
|
||||
* @return the session
|
||||
* @return the session state
|
||||
*/
|
||||
public @Nullable RemoteSession getSession(String id) {
|
||||
return this.sessions.get(id);
|
||||
public @NonNull SessionState getSessionState(String id) {
|
||||
return this.sessions.getOrDefault(id, SessionState.NOT_KNOWN);
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks a given session as complete.
|
||||
*
|
||||
* @param id the id of the session
|
||||
*/
|
||||
public void markSessionCompleted(String id) {
|
||||
this.sessions.put(id, SessionState.COMPLETED);
|
||||
}
|
||||
|
||||
}
|
||||
-118
@@ -1,118 +0,0 @@
|
||||
/*
|
||||
* This file is part of LuckPerms, licensed under the MIT License.
|
||||
*
|
||||
* Copyright (c) lucko (Luck) <luck@lucko.me>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* 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.common.webeditor.socket;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
import java.security.Signature;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
* Utilities for public/private key crypto used by the web editor socket connection.
|
||||
*/
|
||||
public final class CryptographyUtils {
|
||||
private CryptographyUtils() {}
|
||||
|
||||
/**
|
||||
* Parse a public key from the given string.
|
||||
*
|
||||
* @param base64String a base64 string encoding the public key
|
||||
* @return the parsed public key
|
||||
* @throws IllegalArgumentException if the input was invalid
|
||||
*/
|
||||
public static PublicKey parsePublicKey(String base64String) throws IllegalArgumentException {
|
||||
try {
|
||||
byte[] bytes = Base64.getDecoder().decode(base64String);
|
||||
X509EncodedKeySpec spec = new X509EncodedKeySpec(bytes);
|
||||
KeyFactory rsa = KeyFactory.getInstance("RSA");
|
||||
return rsa.generatePublic(spec);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalArgumentException("Exception parsing public key", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a public/private key pair.
|
||||
*
|
||||
* @return the generated key pair
|
||||
*/
|
||||
public static KeyPair generateKeyPair() {
|
||||
try {
|
||||
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
|
||||
generator.initialize(4096);
|
||||
return generator.generateKeyPair();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Exception generating keypair", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs {@code msg} using the given {@link PrivateKey}.
|
||||
*
|
||||
* @param privateKey the private key to sign with
|
||||
* @param msg the message
|
||||
* @return a base64 string containing the signature
|
||||
*/
|
||||
public static String sign(PrivateKey privateKey, String msg) {
|
||||
try {
|
||||
Signature sign = Signature.getInstance("SHA256withRSA");
|
||||
sign.initSign(privateKey);
|
||||
sign.update(msg.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
return Base64.getEncoder().encodeToString(sign.sign());
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify that the given base64 encoded signature matches
|
||||
* the given message and {@link PublicKey}.
|
||||
*
|
||||
* @param publicKey the public key that the message was supposedly signed with
|
||||
* @param msg the message
|
||||
* @param signatureBase64 the provided signature
|
||||
* @return true if the signature is ok
|
||||
*/
|
||||
public static boolean verify(PublicKey publicKey, String msg, String signatureBase64) {
|
||||
try {
|
||||
Signature sign = Signature.getInstance("SHA256withRSA");
|
||||
sign.initVerify(publicKey);
|
||||
sign.update(msg.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
byte[] signatureBytes = Base64.getDecoder().decode(signatureBase64);
|
||||
return sign.verify(signatureBytes);
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
-78
@@ -1,78 +0,0 @@
|
||||
/*
|
||||
* This file is part of LuckPerms, licensed under the MIT License.
|
||||
*
|
||||
* Copyright (c) lucko (Luck) <luck@lucko.me>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* 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.common.webeditor.socket;
|
||||
|
||||
import me.lucko.luckperms.common.util.ImmutableCollectors;
|
||||
import me.lucko.luckperms.common.util.gson.JObject;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
public enum SocketMessageType {
|
||||
|
||||
/** Sent when the editor first says "hello" over the channel. (editor -> plugin) */
|
||||
HELLO("hello"),
|
||||
|
||||
/** Sent when the plugin replies to the editors "hello" message. (plugin -> editor) */
|
||||
HELLO_REPLY("hello-reply"),
|
||||
|
||||
/** Sent by the editor to confirm that a connection has been established. (editor -> plugin) */
|
||||
CONNECTED("connected"),
|
||||
|
||||
/** Sent by the editor to request that the plugin applies a change. (editor -> plugin) */
|
||||
CHANGE_REQUEST("change-request"),
|
||||
|
||||
/** Sent by the plugin to confirm that the changes sent by the editor have been accepted or applied. (plugin -> editor) */
|
||||
CHANGE_RESPONSE("change-response"),
|
||||
|
||||
/** Ping message to keep the socket alive. (editor -> plugin) */
|
||||
PING("ping"),
|
||||
|
||||
/** Ping response. (plugin -> editor) */
|
||||
PONG("pong");
|
||||
|
||||
public final String id;
|
||||
|
||||
SocketMessageType(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public JObject builder() {
|
||||
return new JObject().add("type", this.id);
|
||||
}
|
||||
|
||||
private static final Map<String, SocketMessageType> LOOKUP = Arrays.stream(SocketMessageType.values())
|
||||
.collect(ImmutableCollectors.toMap(m -> m.id, Function.identity()));
|
||||
|
||||
public static SocketMessageType getById(String id) {
|
||||
SocketMessageType type = LOOKUP.get(id);
|
||||
if (type == null) {
|
||||
throw new IllegalArgumentException(id);
|
||||
}
|
||||
return type;
|
||||
}
|
||||
}
|
||||
@@ -1,258 +0,0 @@
|
||||
/*
|
||||
* This file is part of LuckPerms, licensed under the MIT License.
|
||||
*
|
||||
* Copyright (c) lucko (Luck) <luck@lucko.me>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* 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.common.webeditor.socket;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
import me.lucko.luckperms.common.http.BytesocksClient;
|
||||
import me.lucko.luckperms.common.http.UnsuccessfulRequestException;
|
||||
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
|
||||
import me.lucko.luckperms.common.plugin.scheduler.SchedulerTask;
|
||||
import me.lucko.luckperms.common.sender.Sender;
|
||||
import me.lucko.luckperms.common.util.gson.GsonProvider;
|
||||
import me.lucko.luckperms.common.util.gson.JObject;
|
||||
import me.lucko.luckperms.common.webeditor.WebEditorRequest;
|
||||
import me.lucko.luckperms.common.webeditor.WebEditorSession;
|
||||
import me.lucko.luckperms.common.webeditor.socket.listener.WebEditorSocketListener;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.security.KeyPair;
|
||||
import java.security.PublicKey;
|
||||
import java.util.Base64;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
public class WebEditorSocket {
|
||||
|
||||
private static final int PROTOCOL_VERSION = 1;
|
||||
|
||||
/** The plugin */
|
||||
private final LuckPermsPlugin plugin;
|
||||
/** The sender who created the editor session */
|
||||
private final Sender sender;
|
||||
/** The web editor session */
|
||||
private final WebEditorSession session;
|
||||
/** The socket listener that handles incoming messages */
|
||||
private final WebEditorSocketListener listener;
|
||||
/** The public and private keys used to sign messages sent by the plugin */
|
||||
private final KeyPair pluginKeyPair;
|
||||
|
||||
/** The websocket backing the connection */
|
||||
private BytesocksClient.Socket socket;
|
||||
/** A task to check if the socket is still active */
|
||||
private SchedulerTask keepaliveTask;
|
||||
/** The public key used by the editor to sign messages */
|
||||
private PublicKey remotePublicKey;
|
||||
/** If the connection is closed */
|
||||
private boolean closed = false;
|
||||
|
||||
public WebEditorSocket(LuckPermsPlugin plugin, Sender sender, WebEditorSession session) {
|
||||
this.plugin = plugin;
|
||||
this.sender = sender;
|
||||
this.session = session;
|
||||
this.listener = new WebEditorSocketListener(this);
|
||||
this.pluginKeyPair = plugin.getWebEditorStore().keyPair();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the socket connection.
|
||||
*
|
||||
* @param client the bytesocks client to connect to
|
||||
* @throws UnsuccessfulRequestException if the request fails
|
||||
* @throws IOException if an i/o error occurs
|
||||
*/
|
||||
public void initialize(BytesocksClient client) throws UnsuccessfulRequestException, IOException {
|
||||
this.socket = client.createSocket(this.listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits the specified amount of time for the socket to connect,
|
||||
* before throwing an exception if a timeout occurs.
|
||||
*
|
||||
* @param timeout the timeout
|
||||
* @param unit the timeout unit
|
||||
*/
|
||||
public void waitForConnect(long timeout, TimeUnit unit) {
|
||||
try {
|
||||
this.listener.connectFuture().get(timeout, unit);
|
||||
} catch (ExecutionException | TimeoutException | InterruptedException e) {
|
||||
throw new RuntimeException("Timed out waiting to socket to connect", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds detail about the socket channel and the plugin public key to
|
||||
* the editor request payload that gets sent via bytebin to the viewer.
|
||||
*
|
||||
* @param request the request
|
||||
*/
|
||||
public void appendDetailToRequest(WebEditorRequest request) {
|
||||
String channelId = this.socket.channelId();
|
||||
String publicKey = Base64.getEncoder().encodeToString(this.pluginKeyPair.getPublic().getEncoded());
|
||||
|
||||
JsonObject socket = new JsonObject();
|
||||
socket.addProperty("protocolVersion", PROTOCOL_VERSION);
|
||||
socket.addProperty("channelId", channelId);
|
||||
socket.addProperty("publicKey", publicKey);
|
||||
|
||||
JsonObject payload = request.getPayload();
|
||||
payload.add("socket", socket);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a message to the socket.
|
||||
*
|
||||
* <p>The message will be encoded as JSON and
|
||||
* signed using the public public key.</p>
|
||||
*
|
||||
* @param msg the message
|
||||
*/
|
||||
public void send(JsonObject msg) {
|
||||
String encoded = GsonProvider.normal().toJson(msg);
|
||||
String signature = CryptographyUtils.sign(this.pluginKeyPair.getPrivate(), encoded);
|
||||
|
||||
JsonObject frame = new JObject()
|
||||
.add("msg", encoded)
|
||||
.add("signature", signature)
|
||||
.toJson();
|
||||
|
||||
this.socket.socket().send(GsonProvider.normal().toJson(frame));
|
||||
}
|
||||
|
||||
public boolean trustConnection(String nonce) {
|
||||
if (this.listener.shouldIgnoreMessages()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.remotePublicKey != null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
PublicKey publicKey = this.listener.helloHandler().getAttemptedConnection(nonce);
|
||||
if (publicKey == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.remotePublicKey = publicKey;
|
||||
|
||||
// save the key in the keystore
|
||||
this.plugin.getWebEditorStore().keystore().trust(this.sender, this.remotePublicKey.getEncoded());
|
||||
|
||||
// send a reply back to the editor to say that it is now trusted
|
||||
send(SocketMessageType.HELLO_REPLY.builder()
|
||||
.add("nonce", nonce)
|
||||
.add("state", "trusted")
|
||||
.toJson()
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
public void scheduleCleanupIfUnused() {
|
||||
this.plugin.getBootstrap().getScheduler().asyncLater(this::afterOpenFor1Minute, 1, TimeUnit.MINUTES);
|
||||
}
|
||||
|
||||
private void afterOpenFor1Minute() {
|
||||
if (this.closed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.remotePublicKey == null && !this.listener.helloHandler().hasAttemptedConnection()) {
|
||||
// If the editor hasn't made an initial connection after 1 minute,
|
||||
// then close + stop listening to the socket.
|
||||
closeSocket();
|
||||
} else {
|
||||
// Otherwise, setup a keepalive monitoring task
|
||||
this.keepaliveTask = this.plugin.getBootstrap().getScheduler().asyncRepeating(this::keepalive, 10, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The keepalive tasks checks to see when the last ping from the editor was. If the editor
|
||||
* hasn't sent anything for 1 minute, then close the connection
|
||||
*/
|
||||
private void keepalive() {
|
||||
if (System.currentTimeMillis() - this.listener.pingHandler().getLastPing() > TimeUnit.MINUTES.toMillis(1)) {
|
||||
cancelKeepalive();
|
||||
closeSocket();
|
||||
}
|
||||
}
|
||||
|
||||
public void close() {
|
||||
try {
|
||||
send(SocketMessageType.PONG.builder()
|
||||
.add("ok", false)
|
||||
.toJson()
|
||||
);
|
||||
} catch (Exception e) {
|
||||
// ignore
|
||||
}
|
||||
|
||||
cancelKeepalive();
|
||||
closeSocket();
|
||||
}
|
||||
|
||||
private void closeSocket() {
|
||||
this.socket.socket().close(1000, "Normal");
|
||||
this.closed = true;
|
||||
}
|
||||
|
||||
private void cancelKeepalive() {
|
||||
if (this.keepaliveTask != null) {
|
||||
this.keepaliveTask.cancel();
|
||||
this.keepaliveTask = null;
|
||||
}
|
||||
}
|
||||
|
||||
public LuckPermsPlugin getPlugin() {
|
||||
return this.plugin;
|
||||
}
|
||||
|
||||
public Sender getSender() {
|
||||
return this.sender;
|
||||
}
|
||||
|
||||
public WebEditorSession getSession() {
|
||||
return this.session;
|
||||
}
|
||||
|
||||
public BytesocksClient.Socket getSocket() {
|
||||
return this.socket;
|
||||
}
|
||||
|
||||
public PublicKey getRemotePublicKey() {
|
||||
return this.remotePublicKey;
|
||||
}
|
||||
|
||||
public void setRemotePublicKey(PublicKey remotePublicKey) {
|
||||
this.remotePublicKey = remotePublicKey;
|
||||
}
|
||||
|
||||
public boolean isClosed() {
|
||||
return this.closed;
|
||||
}
|
||||
|
||||
}
|
||||
-105
@@ -1,105 +0,0 @@
|
||||
/*
|
||||
* This file is part of LuckPerms, licensed under the MIT License.
|
||||
*
|
||||
* Copyright (c) lucko (Luck) <luck@lucko.me>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* 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.common.webeditor.socket.listener;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
import me.lucko.luckperms.common.command.access.CommandPermission;
|
||||
import me.lucko.luckperms.common.http.UnsuccessfulRequestException;
|
||||
import me.lucko.luckperms.common.locale.Message;
|
||||
import me.lucko.luckperms.common.webeditor.WebEditorResponse;
|
||||
import me.lucko.luckperms.common.webeditor.socket.SocketMessageType;
|
||||
import me.lucko.luckperms.common.webeditor.socket.WebEditorSocket;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Handler for {@link SocketMessageType#CHANGE_REQUEST}
|
||||
*/
|
||||
public class HandlerChangeRequest implements Handler {
|
||||
|
||||
/** The change has been accepted, and the plugin will now apply it. */
|
||||
private static final String STATE_ACCEPTED = "accepted";
|
||||
/** The change has been applied. */
|
||||
private static final String STATE_APPLIED = "applied";
|
||||
|
||||
/** The socket */
|
||||
private final WebEditorSocket socket;
|
||||
|
||||
public HandlerChangeRequest(WebEditorSocket socket) {
|
||||
this.socket = socket;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handle(JsonObject msg) {
|
||||
if (!this.socket.getSender().hasPermission(CommandPermission.APPLY_EDITS)) {
|
||||
throw new IllegalStateException("Sender does not have applyedits permission");
|
||||
}
|
||||
|
||||
// get the bytebin code containing the editor data
|
||||
String code = msg.get("code").getAsString();
|
||||
if (code == null || code.isEmpty()) {
|
||||
throw new IllegalArgumentException("Invalid code");
|
||||
}
|
||||
|
||||
// send "change-accepted" response
|
||||
this.socket.getPlugin().getBootstrap().getScheduler().executeAsync(() ->
|
||||
this.socket.send(SocketMessageType.CHANGE_RESPONSE.builder()
|
||||
.add("state", STATE_ACCEPTED)
|
||||
.toJson()
|
||||
)
|
||||
);
|
||||
|
||||
// download data from bytebin
|
||||
JsonObject data;
|
||||
try {
|
||||
data = this.socket.getPlugin().getBytebin().getJsonContent(code).getAsJsonObject();
|
||||
Objects.requireNonNull(data);
|
||||
} catch (UnsuccessfulRequestException | IOException e) {
|
||||
throw new RuntimeException("Error reading data", e);
|
||||
}
|
||||
|
||||
// apply changes
|
||||
Message.EDITOR_SOCKET_CHANGES_RECEIVED.send(this.socket.getSender());
|
||||
new WebEditorResponse(code, data).apply(
|
||||
this.socket.getPlugin(),
|
||||
this.socket.getSender(),
|
||||
this.socket.getSession(),
|
||||
"lp",
|
||||
false
|
||||
);
|
||||
|
||||
// create a new session
|
||||
String newSessionCode = this.socket.getSession().createFollowUpSession();
|
||||
this.socket.send(SocketMessageType.CHANGE_RESPONSE.builder()
|
||||
.add("state", STATE_APPLIED)
|
||||
.add("newSessionCode", newSessionCode)
|
||||
.toJson()
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
-50
@@ -1,50 +0,0 @@
|
||||
/*
|
||||
* This file is part of LuckPerms, licensed under the MIT License.
|
||||
*
|
||||
* Copyright (c) lucko (Luck) <luck@lucko.me>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* 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.common.webeditor.socket.listener;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
import me.lucko.luckperms.common.locale.Message;
|
||||
import me.lucko.luckperms.common.webeditor.socket.SocketMessageType;
|
||||
import me.lucko.luckperms.common.webeditor.socket.WebEditorSocket;
|
||||
|
||||
/**
|
||||
* Handler for {@link SocketMessageType#CONNECTED}
|
||||
*/
|
||||
public class HandlerConnected implements Handler {
|
||||
|
||||
/** The socket */
|
||||
private final WebEditorSocket socket;
|
||||
|
||||
public HandlerConnected(WebEditorSocket socket) {
|
||||
this.socket = socket;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handle(JsonObject msg) {
|
||||
Message.EDITOR_SOCKET_CONNECTED.send(this.socket.getSender());
|
||||
}
|
||||
}
|
||||
-130
@@ -1,130 +0,0 @@
|
||||
/*
|
||||
* This file is part of LuckPerms, licensed under the MIT License.
|
||||
*
|
||||
* Copyright (c) lucko (Luck) <luck@lucko.me>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* 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.common.webeditor.socket.listener;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
import me.lucko.luckperms.common.locale.Message;
|
||||
import me.lucko.luckperms.common.webeditor.socket.CryptographyUtils;
|
||||
import me.lucko.luckperms.common.webeditor.socket.SocketMessageType;
|
||||
import me.lucko.luckperms.common.webeditor.socket.WebEditorSocket;
|
||||
import me.lucko.luckperms.common.webeditor.store.RemoteSession;
|
||||
|
||||
import java.security.PublicKey;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Handler for {@link SocketMessageType#HELLO}
|
||||
*/
|
||||
public class HandlerHello implements Handler {
|
||||
|
||||
/** The session is accepted, the editor public key is already known so no further action is needed */
|
||||
private static final String STATE_ACCEPTED = "accepted";
|
||||
/** The session is accepted, but the user needs to confirm in-game before any changes will be accepted. */
|
||||
private static final String STATE_UNTRUSTED = "untrusted";
|
||||
/** A session has already been established with a different identity */
|
||||
private static final String STATE_REJECTED = "rejected";
|
||||
/** The remote editor session is based off session data which has already been applied */
|
||||
private static final String STATE_INVALID = "invalid";
|
||||
|
||||
/** The socket */
|
||||
private final WebEditorSocket socket;
|
||||
|
||||
/** A list of attempted connections (connections that have been attempted with an untrusted public key) */
|
||||
private final Map<String, PublicKey> attemptedConnections = new HashMap<>();
|
||||
|
||||
public HandlerHello(WebEditorSocket socket) {
|
||||
this.socket = socket;
|
||||
}
|
||||
|
||||
public PublicKey getAttemptedConnection(String nonce) {
|
||||
return this.attemptedConnections.get(nonce);
|
||||
}
|
||||
|
||||
public boolean hasAttemptedConnection() {
|
||||
return !this.attemptedConnections.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handle(JsonObject msg) {
|
||||
String nonce = getStringOrThrow(msg, "nonce");
|
||||
String sessionId = getStringOrThrow(msg, "sessionId");
|
||||
String browser = msg.get("browser").getAsString();
|
||||
PublicKey remotePublicKey = CryptographyUtils.parsePublicKey(msg.get("publicKey").getAsString());
|
||||
|
||||
// check if the public keys are the same
|
||||
// (this allows the same editor to re-connect, but prevents new connections)
|
||||
if (this.socket.getRemotePublicKey() != null && !this.socket.getRemotePublicKey().equals(remotePublicKey)) {
|
||||
sendReply(nonce, STATE_REJECTED);
|
||||
return;
|
||||
}
|
||||
|
||||
// check if session is valid
|
||||
RemoteSession session = this.socket.getPlugin().getWebEditorStore().sessions().getSession(sessionId);
|
||||
if (session == null || session.isCompleted()) {
|
||||
sendReply(nonce, STATE_INVALID);
|
||||
return;
|
||||
}
|
||||
|
||||
// check if the public key is trusted
|
||||
if (!this.socket.getPlugin().getWebEditorStore().keystore().isTrusted(this.socket.getSender(), remotePublicKey.getEncoded())) {
|
||||
sendReply(nonce, STATE_UNTRUSTED);
|
||||
|
||||
// ask the user if they want to trust the connection
|
||||
Message.EDITOR_SOCKET_UNTRUSTED.send(this.socket.getSender(), nonce, browser, this.socket.getSession().getCommandLabel(), this.socket.getSender().isConsole());
|
||||
this.attemptedConnections.put(nonce, remotePublicKey);
|
||||
return;
|
||||
}
|
||||
|
||||
boolean reconnected = this.socket.getRemotePublicKey() != null;
|
||||
this.socket.setRemotePublicKey(remotePublicKey);
|
||||
|
||||
sendReply(nonce, STATE_ACCEPTED);
|
||||
|
||||
if (reconnected) {
|
||||
Message.EDITOR_SOCKET_RECONNECTED.send(this.socket.getSender());
|
||||
} else {
|
||||
Message.EDITOR_SOCKET_CONNECTED.send(this.socket.getSender());
|
||||
}
|
||||
}
|
||||
|
||||
private void sendReply(String nonce, String state) {
|
||||
this.socket.send(SocketMessageType.HELLO_REPLY.builder()
|
||||
.add("nonce", nonce)
|
||||
.add("state", state)
|
||||
.toJson()
|
||||
);
|
||||
}
|
||||
|
||||
private static String getStringOrThrow(JsonObject msg, String key) {
|
||||
String val = msg.get(key).getAsString();
|
||||
if (val == null || val.isEmpty()) {
|
||||
throw new IllegalStateException("missing " + key);
|
||||
}
|
||||
return val;
|
||||
}
|
||||
}
|
||||
-181
@@ -1,181 +0,0 @@
|
||||
/*
|
||||
* This file is part of LuckPerms, licensed under the MIT License.
|
||||
*
|
||||
* Copyright (c) lucko (Luck) <luck@lucko.me>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* 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.common.webeditor.socket.listener;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
import me.lucko.luckperms.common.util.gson.GsonProvider;
|
||||
import me.lucko.luckperms.common.webeditor.socket.CryptographyUtils;
|
||||
import me.lucko.luckperms.common.webeditor.socket.SocketMessageType;
|
||||
import me.lucko.luckperms.common.webeditor.socket.WebEditorSocket;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import okhttp3.Response;
|
||||
import okhttp3.WebSocket;
|
||||
import okhttp3.WebSocketListener;
|
||||
|
||||
import java.io.EOFException;
|
||||
import java.security.PublicKey;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
public class WebEditorSocketListener extends WebSocketListener {
|
||||
|
||||
/** The socket */
|
||||
private final WebEditorSocket socket;
|
||||
|
||||
// Individual handlers for each message type
|
||||
private final HandlerHello helloHandler;
|
||||
private final HandlerConnected connectedHandler;
|
||||
private final HandlerPing pingHandler;
|
||||
private final HandlerChangeRequest changeRequestHandler;
|
||||
|
||||
/** A future that will complete when the connection is established successfully */
|
||||
private final CompletableFuture<Void> connectFuture = new CompletableFuture<>();
|
||||
|
||||
/** Message receive lock */
|
||||
private final ReentrantLock lock = new ReentrantLock();
|
||||
|
||||
public WebEditorSocketListener(WebEditorSocket socket) {
|
||||
this.socket = socket;
|
||||
this.helloHandler = new HandlerHello(socket);
|
||||
this.connectedHandler = new HandlerConnected(socket);
|
||||
this.pingHandler = new HandlerPing(socket);
|
||||
this.changeRequestHandler = new HandlerChangeRequest(socket);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onOpen(@NonNull WebSocket webSocket, @NonNull Response response) {
|
||||
this.connectFuture.complete(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(@NonNull WebSocket webSocket, @NonNull Throwable e, Response response) {
|
||||
if (e instanceof EOFException) {
|
||||
return; // ignore
|
||||
}
|
||||
this.socket.getPlugin().getLogger().warn("Exception occurred in web socket", e);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessage(@NonNull WebSocket webSocket, @NonNull String msg) {
|
||||
this.socket.getPlugin().getBootstrap().getScheduler().executeAsync(() -> {
|
||||
this.lock.lock();
|
||||
try {
|
||||
if (shouldIgnoreMessages()) {
|
||||
return;
|
||||
}
|
||||
|
||||
handleMessageFrame(msg);
|
||||
} catch (Exception e) {
|
||||
this.socket.getPlugin().getLogger().warn("Exception occurred handling message from socket", e);
|
||||
} finally {
|
||||
this.lock.unlock();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if incoming messages should be ignored.
|
||||
*
|
||||
* @return true if messages should be ignored
|
||||
*/
|
||||
public boolean shouldIgnoreMessages() {
|
||||
if (this.socket.isClosed()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!this.socket.getSender().isValid()) {
|
||||
this.socket.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void handleMessageFrame(String stringMsg) {
|
||||
JsonObject frame = GsonProvider.parser().parse(stringMsg).getAsJsonObject();
|
||||
|
||||
String innerMsg = frame.get("msg").getAsString();
|
||||
String signature = frame.get("signature").getAsString();
|
||||
|
||||
if (innerMsg == null || innerMsg.isEmpty() || signature == null || signature.isEmpty()) {
|
||||
throw new IllegalArgumentException("Incomplete message");
|
||||
}
|
||||
|
||||
// check signature to ensure the message is from the connected editor
|
||||
PublicKey remotePublicKey = this.socket.getRemotePublicKey();
|
||||
boolean verified = remotePublicKey == null || CryptographyUtils.verify(remotePublicKey, innerMsg, signature);
|
||||
|
||||
// parse the inner message
|
||||
JsonObject msg = GsonProvider.parser().parse(innerMsg).getAsJsonObject();
|
||||
SocketMessageType type = SocketMessageType.getById(msg.get("type").getAsString());
|
||||
|
||||
if (type == SocketMessageType.HELLO) {
|
||||
this.helloHandler.handle(msg);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!verified) {
|
||||
throw new IllegalStateException("Signature not accepted");
|
||||
}
|
||||
|
||||
switch (type) {
|
||||
case CHANGE_REQUEST:
|
||||
this.changeRequestHandler.handle(msg);
|
||||
break;
|
||||
case CONNECTED:
|
||||
this.connectedHandler.handle(msg);
|
||||
break;
|
||||
case PING:
|
||||
this.pingHandler.handle(msg);
|
||||
break;
|
||||
default:
|
||||
throw new IllegalStateException("Invalid message type: " + type);
|
||||
}
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> connectFuture() {
|
||||
return this.connectFuture;
|
||||
}
|
||||
|
||||
public HandlerHello helloHandler() {
|
||||
return this.helloHandler;
|
||||
}
|
||||
|
||||
public HandlerConnected connectedHandler() {
|
||||
return this.connectedHandler;
|
||||
}
|
||||
|
||||
public HandlerPing pingHandler() {
|
||||
return this.pingHandler;
|
||||
}
|
||||
|
||||
public HandlerChangeRequest changeRequestHandler() {
|
||||
return this.changeRequestHandler;
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
/*
|
||||
* This file is part of LuckPerms, licensed under the MIT License.
|
||||
*
|
||||
* Copyright (c) lucko (Luck) <luck@lucko.me>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* 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.common.webeditor.store;
|
||||
|
||||
import me.lucko.luckperms.common.webeditor.WebEditorRequest;
|
||||
|
||||
public final class RemoteSession {
|
||||
private WebEditorRequest request;
|
||||
private boolean completed;
|
||||
|
||||
public RemoteSession(WebEditorRequest request) {
|
||||
this.request = request;
|
||||
this.completed = false;
|
||||
}
|
||||
|
||||
public WebEditorRequest request() {
|
||||
return this.request;
|
||||
}
|
||||
|
||||
public boolean isCompleted() {
|
||||
return this.completed;
|
||||
}
|
||||
|
||||
public void complete() {
|
||||
this.completed = true;
|
||||
this.request = null;
|
||||
}
|
||||
}
|
||||
-196
@@ -1,196 +0,0 @@
|
||||
/*
|
||||
* This file is part of LuckPerms, licensed under the MIT License.
|
||||
*
|
||||
* Copyright (c) lucko (Luck) <luck@lucko.me>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* 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.common.webeditor.store;
|
||||
|
||||
import me.lucko.luckperms.common.context.ImmutableContextSetImpl;
|
||||
import me.lucko.luckperms.common.model.User;
|
||||
import me.lucko.luckperms.common.node.types.Meta;
|
||||
import me.lucko.luckperms.common.query.QueryOptionsImpl;
|
||||
import me.lucko.luckperms.common.sender.Sender;
|
||||
import me.lucko.luckperms.common.util.gson.GsonProvider;
|
||||
import me.lucko.luckperms.common.verbose.event.CheckOrigin;
|
||||
|
||||
import net.luckperms.api.model.data.DataType;
|
||||
import net.luckperms.api.node.NodeType;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CopyOnWriteArraySet;
|
||||
|
||||
public final class WebEditorKeystore {
|
||||
private static final String META_KEY = "lp-editor-key";
|
||||
|
||||
private final Path consoleKeysPath;
|
||||
private final Set<String> trustedConsoleKeys;
|
||||
|
||||
public WebEditorKeystore(Path consoleKeysPath) {
|
||||
this.consoleKeysPath = consoleKeysPath;
|
||||
this.trustedConsoleKeys = new CopyOnWriteArraySet<>();
|
||||
|
||||
try {
|
||||
load();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given public key has been trusted by the sender.
|
||||
*
|
||||
* @param sender the sender
|
||||
* @param publicKey the public key
|
||||
* @return true if trusted
|
||||
*/
|
||||
public boolean isTrusted(Sender sender, byte[] publicKey) {
|
||||
return isTrusted(sender, hash(publicKey));
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the given public key hash has been trusted by the sender.
|
||||
*
|
||||
* @param sender the sender
|
||||
* @param hash the public key hash
|
||||
* @return true if trusted
|
||||
*/
|
||||
public boolean isTrusted(Sender sender, String hash) {
|
||||
if (sender.isConsole()) {
|
||||
return isTrustedConsole(hash);
|
||||
} else {
|
||||
User user = sender.getPlugin().getUserManager().getIfLoaded(sender.getUniqueId());
|
||||
return user != null && isTrusted(user, hash);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Trusts the given public key for the sender.
|
||||
*
|
||||
* @param sender the sender
|
||||
* @param publicKey the public key
|
||||
*/
|
||||
public void trust(Sender sender, byte[] publicKey) {
|
||||
trust(sender, hash(publicKey));
|
||||
}
|
||||
|
||||
/**
|
||||
* Trusts the given public key hash for the sender.
|
||||
*
|
||||
* @param sender the sender
|
||||
* @param hash the public key hash
|
||||
*/
|
||||
public void trust(Sender sender, String hash) {
|
||||
if (sender.isConsole()) {
|
||||
trustConsole(hash);
|
||||
} else {
|
||||
User user = sender.getPlugin().getUserManager().getIfLoaded(sender.getUniqueId());
|
||||
if (user != null) {
|
||||
trust(user, hash);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// console
|
||||
|
||||
private boolean isTrustedConsole(String hash) {
|
||||
return this.trustedConsoleKeys.contains(hash);
|
||||
}
|
||||
|
||||
private void trustConsole(String hash) {
|
||||
this.trustedConsoleKeys.add(hash);
|
||||
|
||||
try {
|
||||
save();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private void load() throws Exception {
|
||||
if (Files.exists(this.consoleKeysPath)) {
|
||||
try (BufferedReader reader = Files.newBufferedReader(this.consoleKeysPath, StandardCharsets.UTF_8)) {
|
||||
KeystoreFile file = GsonProvider.normal().fromJson(reader, KeystoreFile.class);
|
||||
if (file != null && file.consoleKeys != null) {
|
||||
this.trustedConsoleKeys.addAll(file.consoleKeys);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void save() throws Exception {
|
||||
try (BufferedWriter writer = Files.newBufferedWriter(this.consoleKeysPath, StandardCharsets.UTF_8)) {
|
||||
KeystoreFile file = new KeystoreFile();
|
||||
file.consoleKeys = new ArrayList<>(this.trustedConsoleKeys);
|
||||
GsonProvider.prettyPrinting().toJson(file, writer);
|
||||
}
|
||||
}
|
||||
|
||||
// users
|
||||
|
||||
private boolean isTrusted(User user, String hash) {
|
||||
String key = user.getCachedData().getMetaData(QueryOptionsImpl.DEFAULT_CONTEXTUAL)
|
||||
.getMetaValue(META_KEY, CheckOrigin.INTERNAL).result();
|
||||
|
||||
if (key == null || key.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return hash.equals(key);
|
||||
}
|
||||
|
||||
private void trust(User user, String hash) {
|
||||
user.removeIf(DataType.NORMAL, ImmutableContextSetImpl.EMPTY, NodeType.META.predicate(mn -> mn.getMetaKey().equals(META_KEY)), false);
|
||||
user.setNode(DataType.NORMAL, Meta.builder(META_KEY, hash).build(), false);
|
||||
|
||||
user.getPlugin().getStorage().saveUser(user).join();
|
||||
}
|
||||
|
||||
private static String hash(byte[] buf) {
|
||||
byte[] digest = createDigest().digest(buf);
|
||||
return Base64.getEncoder().encodeToString(digest);
|
||||
}
|
||||
|
||||
private static MessageDigest createDigest() {
|
||||
try {
|
||||
return MessageDigest.getInstance("SHA-1");
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings({"FieldMayBeFinal", "unused"})
|
||||
private static class KeystoreFile {
|
||||
private String _comment = "This file stores a list of trusted editor public keys";
|
||||
private List<String> consoleKeys = null;
|
||||
}
|
||||
}
|
||||
-50
@@ -1,50 +0,0 @@
|
||||
/*
|
||||
* This file is part of LuckPerms, licensed under the MIT License.
|
||||
*
|
||||
* Copyright (c) lucko (Luck) <luck@lucko.me>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* 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.common.webeditor.store;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
|
||||
import me.lucko.luckperms.common.sender.Sender;
|
||||
import me.lucko.luckperms.common.util.CaffeineFactory;
|
||||
import me.lucko.luckperms.common.webeditor.socket.WebEditorSocket;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public final class WebEditorSocketMap {
|
||||
private final Cache<UUID, WebEditorSocket> sockets = CaffeineFactory.newBuilder()
|
||||
.weakValues()
|
||||
.expireAfterWrite(5, TimeUnit.MINUTES)
|
||||
.build();
|
||||
|
||||
public WebEditorSocket getSocket(Sender sender) {
|
||||
return this.sockets.getIfPresent(sender.getUniqueId());
|
||||
}
|
||||
|
||||
public void putSocket(Sender sender, WebEditorSocket socket) {
|
||||
this.sockets.put(sender.getUniqueId(), socket);
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
/*
|
||||
* This file is part of LuckPerms, licensed under the MIT License.
|
||||
*
|
||||
* Copyright (c) lucko (Luck) <luck@lucko.me>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* 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.common.webeditor.store;
|
||||
|
||||
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
|
||||
import me.lucko.luckperms.common.webeditor.socket.CryptographyUtils;
|
||||
|
||||
import java.security.KeyPair;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/**
|
||||
* Contains a store of known web editor sessions and provides a lookup function for
|
||||
* trusted editor public keys.
|
||||
*/
|
||||
public class WebEditorStore {
|
||||
private final WebEditorSessionMap sessions;
|
||||
private final WebEditorSocketMap sockets;
|
||||
private final WebEditorKeystore keystore;
|
||||
private final CompletableFuture<KeyPair> keyPair;
|
||||
|
||||
public WebEditorStore(LuckPermsPlugin plugin) {
|
||||
this.sessions = new WebEditorSessionMap();
|
||||
this.sockets = new WebEditorSocketMap();
|
||||
this.keystore = new WebEditorKeystore(plugin.getBootstrap().getConfigDirectory().resolve("editor-keystore.json"));
|
||||
this.keyPair = CompletableFuture.supplyAsync(CryptographyUtils::generateKeyPair, plugin.getBootstrap().getScheduler().async());
|
||||
}
|
||||
|
||||
public WebEditorSessionMap sessions() {
|
||||
return this.sessions;
|
||||
}
|
||||
|
||||
public WebEditorSocketMap sockets() {
|
||||
return this.sockets;
|
||||
}
|
||||
|
||||
public WebEditorKeystore keystore() {
|
||||
return this.keystore;
|
||||
}
|
||||
|
||||
public KeyPair keyPair() {
|
||||
if (!this.keyPair.isDone()) {
|
||||
throw new IllegalStateException("Web editor keypair has not been generated yet! Has the server just started?");
|
||||
}
|
||||
return this.keyPair.join();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -91,18 +91,6 @@ luckperms.command.misc.loading.error.track-invalid={0} is not a valid track name
|
||||
luckperms.command.editor.no-match=Unable to open editor, no objects matched the desired type
|
||||
luckperms.command.editor.start=Preparing a new editor session, please wait...
|
||||
luckperms.command.editor.url=Click the link below to open the editor
|
||||
luckperms.command.editor.socket.connected=Editor window connected successfully
|
||||
luckperms.command.editor.socket.reconnected=Editor window reconnected successfully
|
||||
luckperms.command.editor.socket.changes-received=Changes have been received from the connected web editor session
|
||||
luckperms.command.editor.socket.untrusted=An editor window has connected, but it is not yet trusted
|
||||
luckperms.command.editor.socket.untrusted.prompt.click=If it was you, {0} to trust the session!
|
||||
luckperms.command.editor.socket.untrusted.prompt.click.action=click here
|
||||
luckperms.command.editor.socket.untrusted.prompt.runcommand=If it was you, run {0} to trust the session!
|
||||
luckperms.command.editor.socket.untrusted.sessioninfo=session id = {0}, browser = {1}
|
||||
luckperms.command.editor.socket.trust.success=The editor session has been marked as trusted
|
||||
luckperms.command.editor.socket.trust.futureinfo=In the future, connections from the same browser will be trusted automatically
|
||||
luckperms.command.editor.socket.trust.connecting=The plugin will now attempt to establish a connection with the editor...
|
||||
luckperms.command.editor.socket.trust.failure=Unable to trust the given session because the socket is closed, or because a different connection was established instead
|
||||
luckperms.command.editor.unable-to-communicate=Unable to communicate with the editor
|
||||
luckperms.command.editor.apply-edits.success=Web editor data was applied to {0} {1} successfully
|
||||
luckperms.command.editor.apply-edits.success-summary={0} {1} and {2} {3}
|
||||
|
||||
+3
-3
@@ -27,16 +27,16 @@ package me.lucko.luckperms.fabric.listeners;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.LoadingCache;
|
||||
|
||||
import me.lucko.luckperms.common.api.implementation.ApiGroup;
|
||||
import me.lucko.luckperms.fabric.LPFabricPlugin;
|
||||
import me.lucko.luckperms.common.cache.BufferedRequest;
|
||||
import me.lucko.luckperms.common.event.LuckPermsEventListener;
|
||||
import me.lucko.luckperms.common.util.CaffeineFactory;
|
||||
import me.lucko.luckperms.fabric.LPFabricPlugin;
|
||||
import me.lucko.luckperms.common.api.implementation.ApiGroup;
|
||||
|
||||
import net.luckperms.api.event.EventBus;
|
||||
import net.luckperms.api.event.context.ContextUpdateEvent;
|
||||
import net.luckperms.api.event.group.GroupDataRecalculateEvent;
|
||||
import net.luckperms.api.event.user.UserDataRecalculateEvent;
|
||||
import net.luckperms.api.event.group.GroupDataRecalculateEvent;
|
||||
import net.minecraft.server.network.ServerPlayerEntity;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@@ -29,7 +29,6 @@ import me.lucko.luckperms.fabric.event.PreExecuteCommandCallback;
|
||||
|
||||
import net.minecraft.server.command.CommandManager;
|
||||
import net.minecraft.server.command.ServerCommandSource;
|
||||
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
|
||||
@@ -26,7 +26,6 @@
|
||||
package me.lucko.luckperms.nukkit;
|
||||
|
||||
import me.lucko.luckperms.common.loader.LoaderBootstrap;
|
||||
import me.lucko.luckperms.common.plugin.bootstrap.BootstrappedWithLoader;
|
||||
import me.lucko.luckperms.common.plugin.bootstrap.LuckPermsBootstrap;
|
||||
import me.lucko.luckperms.common.plugin.classpath.ClassPathAppender;
|
||||
import me.lucko.luckperms.common.plugin.classpath.JarInJarClassPathAppender;
|
||||
@@ -50,7 +49,7 @@ import java.util.concurrent.CountDownLatch;
|
||||
/**
|
||||
* Bootstrap plugin for LuckPerms running on Nukkit.
|
||||
*/
|
||||
public class LPNukkitBootstrap implements LuckPermsBootstrap, LoaderBootstrap, BootstrappedWithLoader {
|
||||
public class LPNukkitBootstrap implements LuckPermsBootstrap, LoaderBootstrap {
|
||||
private final PluginBase loader;
|
||||
|
||||
/**
|
||||
@@ -92,7 +91,6 @@ public class LPNukkitBootstrap implements LuckPermsBootstrap, LoaderBootstrap, B
|
||||
|
||||
// provide adapters
|
||||
|
||||
@Override
|
||||
public PluginBase getLoader() {
|
||||
return this.loader;
|
||||
}
|
||||
|
||||
+1
-1
@@ -23,6 +23,6 @@ include (
|
||||
'fabric',
|
||||
'nukkit',
|
||||
'nukkit:loader',
|
||||
'sponge', 'sponge:sponge-service', 'sponge:sponge-service-api8',
|
||||
'sponge', 'sponge:sponge-service', 'sponge:sponge-service-api6', 'sponge:sponge-service-api7',
|
||||
'velocity'
|
||||
)
|
||||
+15
-8
@@ -1,17 +1,25 @@
|
||||
plugins {
|
||||
id 'net.kyori.blossom' version '1.3.0'
|
||||
id 'com.github.johnrengelman.shadow' version '7.0.0'
|
||||
}
|
||||
|
||||
repositories {
|
||||
maven { url 'https://repo.spongepowered.org/repository/maven-public/' }
|
||||
maven { url 'https://repo.spongepowered.org/maven' }
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation project(':common')
|
||||
implementation project(':sponge:sponge-service')
|
||||
implementation project(':sponge:sponge-service-api8')
|
||||
implementation project(':sponge:sponge-service-api6')
|
||||
implementation project(':sponge:sponge-service-api7')
|
||||
|
||||
compileOnly('org.spongepowered:spongeapi:8.0.0') {
|
||||
compileOnly('org.spongepowered:spongeapi:7.3.0') {
|
||||
exclude(module: 'configurate-core')
|
||||
exclude(module: 'configurate-hocon')
|
||||
exclude(module: 'configurate-gson')
|
||||
exclude(module: 'configurate-yaml')
|
||||
}
|
||||
annotationProcessor('org.spongepowered:spongeapi:7.3.0') {
|
||||
exclude(module: 'configurate-core')
|
||||
exclude(module: 'configurate-hocon')
|
||||
exclude(module: 'configurate-gson')
|
||||
@@ -19,10 +27,9 @@ dependencies {
|
||||
}
|
||||
}
|
||||
|
||||
processResources {
|
||||
filesMatching('META-INF/sponge_plugins.json') {
|
||||
expand 'pluginVersion': project.ext.fullVersion
|
||||
}
|
||||
blossom {
|
||||
replaceTokenIn('src/main/java/me/lucko/luckperms/sponge/LPSpongeBootstrap.java')
|
||||
replaceToken '@version@', project.ext.fullVersion
|
||||
}
|
||||
|
||||
shadowJar {
|
||||
@@ -33,7 +40,7 @@ shadowJar {
|
||||
include(dependency('me.lucko.luckperms:.*'))
|
||||
}
|
||||
|
||||
//relocate 'net.kyori.adventure', 'me.lucko.luckperms.lib.adventure'
|
||||
relocate 'net.kyori.adventure', 'me.lucko.luckperms.lib.adventure'
|
||||
relocate 'net.kyori.event', 'me.lucko.luckperms.lib.eventbus'
|
||||
relocate 'com.github.benmanes.caffeine', 'me.lucko.luckperms.lib.caffeine'
|
||||
relocate 'okio', 'me.lucko.luckperms.lib.okio'
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
repositories {
|
||||
maven { url 'https://repo.spongepowered.org/repository/maven-public/' }
|
||||
maven { url 'https://repo.spongepowered.org/maven' }
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation project(':common')
|
||||
implementation project(':sponge:sponge-service')
|
||||
|
||||
compileOnly('org.spongepowered:spongeapi:8.0.0') {
|
||||
compileOnly('org.spongepowered:spongeapi:6.0.0') {
|
||||
exclude(module: 'configurate-core')
|
||||
exclude(module: 'configurate-hocon')
|
||||
exclude(module: 'configurate-gson')
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
/*
|
||||
* This file is part of LuckPerms, licensed under the MIT License.
|
||||
*
|
||||
* Copyright (c) lucko (Luck) <luck@lucko.me>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* 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.sponge.service.proxy.api6;
|
||||
|
||||
import me.lucko.luckperms.common.context.ImmutableContextSetImpl;
|
||||
import me.lucko.luckperms.sponge.service.model.LPPermissionDescription;
|
||||
import me.lucko.luckperms.sponge.service.model.LPPermissionService;
|
||||
import me.lucko.luckperms.sponge.service.model.LPSubject;
|
||||
import me.lucko.luckperms.sponge.service.model.LPSubjectCollection;
|
||||
import me.lucko.luckperms.sponge.service.model.ProxiedServiceObject;
|
||||
|
||||
import net.luckperms.api.util.Tristate;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
import org.spongepowered.api.plugin.PluginContainer;
|
||||
import org.spongepowered.api.service.permission.PermissionDescription;
|
||||
import org.spongepowered.api.service.permission.PermissionService;
|
||||
import org.spongepowered.api.text.Text;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class DescriptionBuilder implements PermissionDescription.Builder, ProxiedServiceObject {
|
||||
|
||||
public static LPPermissionDescription registerDescription(LPPermissionService service, PermissionDescription description) {
|
||||
//noinspection ConstantConditions
|
||||
if (description.getOwner() == null) {
|
||||
return null;
|
||||
}
|
||||
return service.registerPermissionDescription(description.getId(), description.getDescription(), description.getOwner());
|
||||
}
|
||||
|
||||
private final @NonNull LPPermissionService service;
|
||||
private final @NonNull PluginContainer container;
|
||||
private final @NonNull Map<String, Tristate> roles = new HashMap<>();
|
||||
private @Nullable String id = null;
|
||||
private @Nullable Text description = null;
|
||||
|
||||
public DescriptionBuilder(@NonNull LPPermissionService service, @NonNull PluginContainer container) {
|
||||
this.service = Objects.requireNonNull(service, "service");
|
||||
this.container = Objects.requireNonNull(container, "container");
|
||||
}
|
||||
|
||||
@Override
|
||||
public PermissionDescription.@NonNull Builder id(@NonNull String id) {
|
||||
this.id = Objects.requireNonNull(id, "id");
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PermissionDescription.@NonNull Builder description(@NonNull Text description) {
|
||||
this.description = Objects.requireNonNull(description, "description");
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PermissionDescription.@NonNull Builder assign(@NonNull String role, boolean value) {
|
||||
Objects.requireNonNull(role, "role");
|
||||
this.roles.put(role, Tristate.of(value));
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull PermissionDescription register() throws IllegalStateException {
|
||||
if (this.id == null) {
|
||||
throw new IllegalStateException("id cannot be null");
|
||||
}
|
||||
|
||||
LPPermissionDescription description = this.service.registerPermissionDescription(this.id, this.description, this.container);
|
||||
|
||||
// Set role-templates
|
||||
LPSubjectCollection subjects = this.service.getCollection(PermissionService.SUBJECTS_ROLE_TEMPLATE);
|
||||
for (Map.Entry<String, Tristate> assignment : this.roles.entrySet()) {
|
||||
LPSubject roleSubject = subjects.loadSubject(assignment.getKey()).join();
|
||||
roleSubject.getTransientSubjectData().setPermission(ImmutableContextSetImpl.EMPTY, this.id, assignment.getValue());
|
||||
}
|
||||
|
||||
// null stuff so this instance can be reused
|
||||
this.roles.clear();
|
||||
this.id = null;
|
||||
this.description = null;
|
||||
|
||||
return description.sponge();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (o == this) return true;
|
||||
if (!(o instanceof DescriptionBuilder)) return false;
|
||||
final DescriptionBuilder other = (DescriptionBuilder) o;
|
||||
|
||||
return this.container.equals(other.container) &&
|
||||
this.roles.equals(other.roles) &&
|
||||
Objects.equals(this.id, other.id) &&
|
||||
Objects.equals(this.description, other.description);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int PRIME = 59;
|
||||
int result = 1;
|
||||
result = result * PRIME + this.container.hashCode();
|
||||
result = result * PRIME + this.roles.hashCode();
|
||||
result = result * PRIME + (this.id == null ? 43 : this.id.hashCode());
|
||||
result = result * PRIME + (this.description == null ? 43 : this.description.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "SimpleDescriptionBuilder(" +
|
||||
"container=" + this.container + ", " +
|
||||
"roles=" + this.roles + ", " +
|
||||
"id=" + this.id + ", " +
|
||||
"description=" + this.description + ")";
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
* This file is part of LuckPerms, licensed under the MIT License.
|
||||
*
|
||||
* Copyright (c) lucko (Luck) <luck@lucko.me>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* 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.sponge.service.proxy.api6;
|
||||
|
||||
import me.lucko.luckperms.common.util.ImmutableCollectors;
|
||||
import me.lucko.luckperms.sponge.service.model.LPPermissionDescription;
|
||||
import me.lucko.luckperms.sponge.service.model.LPPermissionService;
|
||||
import me.lucko.luckperms.sponge.service.model.ProxiedServiceObject;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.spongepowered.api.Sponge;
|
||||
import org.spongepowered.api.plugin.PluginContainer;
|
||||
import org.spongepowered.api.service.permission.PermissionDescription;
|
||||
import org.spongepowered.api.service.permission.Subject;
|
||||
import org.spongepowered.api.text.Text;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public final class PermissionDescriptionProxy implements PermissionDescription, ProxiedServiceObject {
|
||||
private final LPPermissionService service;
|
||||
private final LPPermissionDescription handle;
|
||||
|
||||
public PermissionDescriptionProxy(LPPermissionService service, LPPermissionDescription handle) {
|
||||
this.service = service;
|
||||
this.handle = handle;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull String getId() {
|
||||
return this.handle.getId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Text getDescription() {
|
||||
return this.handle.getDescription().orElse(Text.EMPTY);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull PluginContainer getOwner() {
|
||||
return this.handle.getOwner().orElseGet(() -> Sponge.getGame().getPluginManager().fromInstance(this.service.getPlugin()).orElseThrow(() -> new RuntimeException("Unable to get LuckPerms instance.")));
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Map<Subject, Boolean> getAssignedSubjects(@NonNull String s) {
|
||||
return this.handle.getAssignedSubjects(s).entrySet().stream()
|
||||
.collect(ImmutableCollectors.toMap(
|
||||
e -> new SubjectProxy(this.service, e.getKey().toReference()),
|
||||
Map.Entry::getValue
|
||||
));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
return o == this || o instanceof PermissionDescriptionProxy && this.handle.equals(((PermissionDescriptionProxy) o).handle);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return this.handle.hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "luckperms.api6.PermissionDescriptionProxy(handle=" + this.handle + ")";
|
||||
}
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
/*
|
||||
* This file is part of LuckPerms, licensed under the MIT License.
|
||||
*
|
||||
* Copyright (c) lucko (Luck) <luck@lucko.me>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* 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.sponge.service.proxy.api6;
|
||||
|
||||
import me.lucko.luckperms.common.util.ImmutableCollectors;
|
||||
import me.lucko.luckperms.sponge.service.model.LPPermissionDescription;
|
||||
import me.lucko.luckperms.sponge.service.model.LPPermissionService;
|
||||
import me.lucko.luckperms.sponge.service.model.ProxiedServiceObject;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.spongepowered.api.Sponge;
|
||||
import org.spongepowered.api.plugin.PluginContainer;
|
||||
import org.spongepowered.api.service.context.ContextCalculator;
|
||||
import org.spongepowered.api.service.permission.PermissionDescription;
|
||||
import org.spongepowered.api.service.permission.PermissionService;
|
||||
import org.spongepowered.api.service.permission.Subject;
|
||||
import org.spongepowered.api.service.permission.SubjectCollection;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
public final class PermissionServiceProxy implements PermissionService, ProxiedServiceObject {
|
||||
private final LPPermissionService handle;
|
||||
|
||||
public PermissionServiceProxy(LPPermissionService handle) {
|
||||
this.handle = handle;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull SubjectCollection getUserSubjects() {
|
||||
return this.handle.getUserSubjects().sponge();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull SubjectCollection getGroupSubjects() {
|
||||
return this.handle.getGroupSubjects().sponge();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Subject getDefaults() {
|
||||
return this.handle.getRootDefaults().sponge();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull SubjectCollection getSubjects(@NonNull String s) {
|
||||
return this.handle.getCollection(s).sponge();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Map<String, SubjectCollection> getKnownSubjects() {
|
||||
return this.handle.getLoadedCollections().entrySet().stream()
|
||||
.collect(ImmutableCollectors.toMap(
|
||||
Map.Entry::getKey,
|
||||
e -> e.getValue().sponge()
|
||||
));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<PermissionDescription.Builder> newDescriptionBuilder(@NonNull Object o) {
|
||||
Optional<PluginContainer> container = Sponge.getGame().getPluginManager().fromInstance(o);
|
||||
if (!container.isPresent()) {
|
||||
throw new IllegalArgumentException("Couldn't find a plugin container for " + o.getClass().getSimpleName());
|
||||
}
|
||||
|
||||
return Optional.of(new DescriptionBuilder(this.handle, container.get()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Optional<PermissionDescription> getDescription(@NonNull String s) {
|
||||
return this.handle.getDescription(s).map(LPPermissionDescription::sponge);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Collection<PermissionDescription> getDescriptions() {
|
||||
return this.handle.getDescriptions().stream().map(LPPermissionDescription::sponge).collect(ImmutableCollectors.toSet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerContextCalculator(@NonNull ContextCalculator<Subject> contextCalculator) {
|
||||
this.handle.registerContextCalculator(contextCalculator);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
return o == this || o instanceof PermissionServiceProxy && this.handle.equals(((PermissionServiceProxy) o).handle);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return this.handle.hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "luckperms.api6.PermissionServiceProxy(handle=" + this.handle + ")";
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
/*
|
||||
* This file is part of LuckPerms, licensed under the MIT License.
|
||||
*
|
||||
* Copyright (c) lucko (Luck) <luck@lucko.me>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* 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.sponge.service.proxy.api6;
|
||||
|
||||
import me.lucko.luckperms.common.util.ImmutableCollectors;
|
||||
import me.lucko.luckperms.sponge.service.CompatibilityUtil;
|
||||
import me.lucko.luckperms.sponge.service.model.LPPermissionService;
|
||||
import me.lucko.luckperms.sponge.service.model.LPSubject;
|
||||
import me.lucko.luckperms.sponge.service.model.LPSubjectCollection;
|
||||
import me.lucko.luckperms.sponge.service.model.ProxiedServiceObject;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.spongepowered.api.service.context.Context;
|
||||
import org.spongepowered.api.service.permission.Subject;
|
||||
import org.spongepowered.api.service.permission.SubjectCollection;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public final class SubjectCollectionProxy implements SubjectCollection, ProxiedServiceObject {
|
||||
private final LPPermissionService service;
|
||||
private final LPSubjectCollection handle;
|
||||
|
||||
public SubjectCollectionProxy(LPPermissionService service, LPSubjectCollection handle) {
|
||||
this.service = service;
|
||||
this.handle = handle;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull String getIdentifier() {
|
||||
return this.handle.getIdentifier();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Subject get(@NonNull String s) {
|
||||
// force load the subject.
|
||||
// after this call, users will expect that the subject is loaded in memory.
|
||||
return this.handle.loadSubject(s).thenApply(LPSubject::sponge).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasRegistered(@NonNull String s) {
|
||||
return this.handle.hasRegistered(s).join();
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
@Override
|
||||
public @NonNull Iterable<Subject> getAllSubjects() {
|
||||
// this will lazily load all subjects. it will initially just get the identifiers of each subject, and will initialize dummy
|
||||
// providers for those identifiers. when any methods against the dummy are called, the actual data will be loaded.
|
||||
// this behaviour should be replaced when CompletableFutures are added to Sponge
|
||||
return (List) this.handle.getAllIdentifiers()
|
||||
.thenApply(ids -> ids.stream()
|
||||
.map(s -> new SubjectProxy(this.service, this.service.getReferenceFactory().obtain(getIdentifier(), s)))
|
||||
.collect(ImmutableCollectors.toList())
|
||||
).join();
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
@Override
|
||||
public @NonNull Map<Subject, Boolean> getAllWithPermission(@NonNull String s) {
|
||||
// again, these methods will lazily load subjects.
|
||||
return (Map) this.handle.getAllWithPermission(s)
|
||||
.thenApply(map -> map.entrySet().stream()
|
||||
.collect(ImmutableCollectors.toMap(
|
||||
e -> new SubjectProxy(this.service, e.getKey()),
|
||||
Map.Entry::getValue
|
||||
))
|
||||
).join();
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
@Override
|
||||
public @NonNull Map<Subject, Boolean> getAllWithPermission(@NonNull Set<Context> set, @NonNull String s) {
|
||||
return (Map) this.handle.getAllWithPermission(CompatibilityUtil.convertContexts(set), s)
|
||||
.thenApply(map -> map.entrySet().stream()
|
||||
.collect(ImmutableCollectors.toMap(
|
||||
e -> new SubjectProxy(this.service, e.getKey()),
|
||||
Map.Entry::getValue
|
||||
))
|
||||
).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Subject getDefaults() {
|
||||
return this.handle.getDefaults().sponge();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
return o == this || o instanceof SubjectCollectionProxy && this.handle.equals(((SubjectCollectionProxy) o).handle);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return this.handle.hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "luckperms.api6.SubjectCollectionProxy(handle=" + this.handle + ")";
|
||||
}
|
||||
}
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
/*
|
||||
* This file is part of LuckPerms, licensed under the MIT License.
|
||||
*
|
||||
* Copyright (c) lucko (Luck) <luck@lucko.me>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* 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.sponge.service.proxy.api6;
|
||||
|
||||
import me.lucko.luckperms.common.util.ImmutableCollectors;
|
||||
import me.lucko.luckperms.sponge.service.CompatibilityUtil;
|
||||
import me.lucko.luckperms.sponge.service.model.LPPermissionService;
|
||||
import me.lucko.luckperms.sponge.service.model.LPSubject;
|
||||
import me.lucko.luckperms.sponge.service.model.LPSubjectData;
|
||||
import me.lucko.luckperms.sponge.service.model.LPSubjectReference;
|
||||
import me.lucko.luckperms.sponge.service.model.ProxiedServiceObject;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.spongepowered.api.service.context.Context;
|
||||
import org.spongepowered.api.service.permission.Subject;
|
||||
import org.spongepowered.api.service.permission.SubjectData;
|
||||
import org.spongepowered.api.util.Tristate;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public final class SubjectDataProxy implements SubjectData, ProxiedServiceObject {
|
||||
private final LPPermissionService service;
|
||||
private final LPSubjectReference ref;
|
||||
private final boolean enduring;
|
||||
|
||||
public SubjectDataProxy(LPPermissionService service, LPSubjectReference ref, boolean enduring) {
|
||||
this.service = service;
|
||||
this.ref = ref;
|
||||
this.enduring = enduring;
|
||||
}
|
||||
|
||||
private CompletableFuture<LPSubjectData> handle() {
|
||||
return this.enduring ?
|
||||
this.ref.resolveLp().thenApply(LPSubject::getSubjectData) :
|
||||
this.ref.resolveLp().thenApply(LPSubject::getTransientSubjectData);
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
@Override
|
||||
public @NonNull Map<Set<Context>, Map<String, Boolean>> getAllPermissions() {
|
||||
return (Map) handle().thenApply(handle -> handle.getAllPermissions().entrySet().stream()
|
||||
.collect(ImmutableCollectors.toMap(
|
||||
e -> CompatibilityUtil.convertContexts(e.getKey()),
|
||||
Map.Entry::getValue
|
||||
))).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Map<String, Boolean> getPermissions(@NonNull Set<Context> contexts) {
|
||||
return handle().thenApply(handle -> handle.getPermissions(CompatibilityUtil.convertContexts(contexts))).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean setPermission(@NonNull Set<Context> contexts, @NonNull String permission, @NonNull Tristate value) {
|
||||
handle().thenCompose(handle -> handle.setPermission(
|
||||
CompatibilityUtil.convertContexts(contexts),
|
||||
permission,
|
||||
CompatibilityUtil.convertTristate(value)
|
||||
));
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean clearPermissions() {
|
||||
handle().thenCompose(LPSubjectData::clearPermissions);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean clearPermissions(@NonNull Set<Context> contexts) {
|
||||
handle().thenCompose(handle -> handle.clearPermissions(CompatibilityUtil.convertContexts(contexts)));
|
||||
return true;
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
@Override
|
||||
public @NonNull Map<Set<Context>, List<Subject>> getAllParents() {
|
||||
return (Map) handle().thenApply(handle -> handle.getAllParents().entrySet().stream()
|
||||
.collect(ImmutableCollectors.toMap(
|
||||
e -> CompatibilityUtil.convertContexts(e.getKey()),
|
||||
e -> e.getValue().stream()
|
||||
.map(s -> new SubjectProxy(this.service, s))
|
||||
.collect(ImmutableCollectors.toList())
|
||||
)
|
||||
)).join();
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
@Override
|
||||
public @NonNull List<Subject> getParents(@NonNull Set<Context> contexts) {
|
||||
return (List) handle().thenApply(handle -> handle.getParents(CompatibilityUtil.convertContexts(contexts)).stream()
|
||||
.map(s -> new SubjectProxy(this.service, s))
|
||||
.collect(ImmutableCollectors.toList())).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean addParent(@NonNull Set<Context> contexts, @NonNull Subject parent) {
|
||||
handle().thenCompose(handle -> handle.addParent(
|
||||
CompatibilityUtil.convertContexts(contexts),
|
||||
this.service.getReferenceFactory().obtain(parent)
|
||||
));
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean removeParent(@NonNull Set<Context> contexts, @NonNull Subject parent) {
|
||||
handle().thenCompose(handle -> handle.removeParent(
|
||||
CompatibilityUtil.convertContexts(contexts),
|
||||
this.service.getReferenceFactory().obtain(parent)
|
||||
));
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean clearParents() {
|
||||
handle().thenCompose(LPSubjectData::clearParents);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean clearParents(@NonNull Set<Context> contexts) {
|
||||
handle().thenCompose(handle -> handle.clearParents(CompatibilityUtil.convertContexts(contexts)));
|
||||
return true;
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
@Override
|
||||
public @NonNull Map<Set<Context>, Map<String, String>> getAllOptions() {
|
||||
return (Map) handle().thenApply(handle -> handle.getAllOptions().entrySet().stream()
|
||||
.collect(ImmutableCollectors.toMap(
|
||||
e -> CompatibilityUtil.convertContexts(e.getKey()),
|
||||
Map.Entry::getValue
|
||||
))).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Map<String, String> getOptions(@NonNull Set<Context> contexts) {
|
||||
return handle().thenApply(handle -> handle.getOptions(CompatibilityUtil.convertContexts(contexts))).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean setOption(@NonNull Set<Context> contexts, @NonNull String key, String value) {
|
||||
if (value == null) {
|
||||
handle().thenCompose(handle -> handle.unsetOption(CompatibilityUtil.convertContexts(contexts), key));
|
||||
} else {
|
||||
handle().thenCompose(handle -> handle.setOption(CompatibilityUtil.convertContexts(contexts), key, value));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean clearOptions(@NonNull Set<Context> contexts) {
|
||||
handle().thenCompose(handle -> handle.clearOptions(CompatibilityUtil.convertContexts(contexts)));
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean clearOptions() {
|
||||
handle().thenCompose(LPSubjectData::clearOptions);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (o == this) return true;
|
||||
if (!(o instanceof SubjectDataProxy)) return false;
|
||||
final SubjectDataProxy other = (SubjectDataProxy) o;
|
||||
return this.ref.equals(other.ref) && this.enduring == other.enduring;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int PRIME = 59;
|
||||
int result = 1;
|
||||
result = result * PRIME + this.ref.hashCode();
|
||||
result = result * PRIME + (this.enduring ? 79 : 97);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "luckperms.api6.SubjectDataProxy(ref=" + this.ref + ", enduring=" + this.enduring + ")";
|
||||
}
|
||||
}
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
/*
|
||||
* This file is part of LuckPerms, licensed under the MIT License.
|
||||
*
|
||||
* Copyright (c) lucko (Luck) <luck@lucko.me>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* 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.sponge.service.proxy.api6;
|
||||
|
||||
import me.lucko.luckperms.common.context.manager.QueryOptionsSupplier;
|
||||
import me.lucko.luckperms.common.util.ImmutableCollectors;
|
||||
import me.lucko.luckperms.sponge.service.CompatibilityUtil;
|
||||
import me.lucko.luckperms.sponge.service.model.LPPermissionService;
|
||||
import me.lucko.luckperms.sponge.service.model.LPSubject;
|
||||
import me.lucko.luckperms.sponge.service.model.LPSubjectReference;
|
||||
import me.lucko.luckperms.sponge.service.model.ProxiedServiceObject;
|
||||
import me.lucko.luckperms.sponge.service.model.ProxiedSubject;
|
||||
|
||||
import net.luckperms.api.query.QueryOptions;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.spongepowered.api.command.CommandSource;
|
||||
import org.spongepowered.api.service.context.Context;
|
||||
import org.spongepowered.api.service.permission.Subject;
|
||||
import org.spongepowered.api.service.permission.SubjectCollection;
|
||||
import org.spongepowered.api.service.permission.SubjectData;
|
||||
import org.spongepowered.api.util.Tristate;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public final class SubjectProxy implements Subject, ProxiedSubject, ProxiedServiceObject {
|
||||
private final LPPermissionService service;
|
||||
private final LPSubjectReference ref;
|
||||
|
||||
private QueryOptionsSupplier queryOptionsSupplier = null;
|
||||
|
||||
public SubjectProxy(LPPermissionService service, LPSubjectReference ref) {
|
||||
this.service = service;
|
||||
this.ref = ref;
|
||||
}
|
||||
|
||||
private CompletableFuture<LPSubject> handle() {
|
||||
return this.ref.resolveLp();
|
||||
}
|
||||
|
||||
// lazy init
|
||||
private QueryOptionsSupplier getContextsCache() {
|
||||
if (this.queryOptionsSupplier == null) {
|
||||
this.queryOptionsSupplier = this.service.getContextManager().getCacheFor(this);
|
||||
}
|
||||
return this.queryOptionsSupplier;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull LPSubjectReference asSubjectReference() {
|
||||
return this.ref;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull QueryOptions getQueryOptions() {
|
||||
return getContextsCache().getQueryOptions();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Optional<CommandSource> getCommandSource() {
|
||||
return handle().thenApply(LPSubject::getCommandSource).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull SubjectCollection getContainingCollection() {
|
||||
return this.service.getCollection(this.ref.getCollectionIdentifier()).sponge();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SubjectData getSubjectData() {
|
||||
return new SubjectDataProxy(this.service, this.ref, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SubjectData getTransientSubjectData() {
|
||||
return new SubjectDataProxy(this.service, this.ref, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPermission(@NonNull Set<Context> contexts, @NonNull String permission) {
|
||||
return handle().thenApply(handle -> handle.getPermissionValue(CompatibilityUtil.convertContexts(contexts), permission).asBoolean()).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasPermission(@NonNull String permission) {
|
||||
return handle().thenApply(handle -> handle.getPermissionValue(getContextsCache().getContextSet(), permission).asBoolean()).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Tristate getPermissionValue(@NonNull Set<Context> contexts, @NonNull String permission) {
|
||||
return handle().thenApply(handle -> CompatibilityUtil.convertTristate(handle.getPermissionValue(CompatibilityUtil.convertContexts(contexts), permission))).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isChildOf(@NonNull Subject parent) {
|
||||
return handle().thenApply(handle -> handle.isChildOf(
|
||||
getContextsCache().getContextSet(),
|
||||
this.service.getReferenceFactory().obtain(parent)
|
||||
)).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isChildOf(@NonNull Set<Context> contexts, @NonNull Subject parent) {
|
||||
return handle().thenApply(handle -> handle.isChildOf(
|
||||
CompatibilityUtil.convertContexts(contexts),
|
||||
this.service.getReferenceFactory().obtain(parent)
|
||||
)).join();
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
@Override
|
||||
public @NonNull List<Subject> getParents() {
|
||||
return (List) handle().thenApply(handle -> handle.getParents(getContextsCache().getContextSet()).stream()
|
||||
.map(s -> new SubjectProxy(this.service, s))
|
||||
.collect(ImmutableCollectors.toList())).join();
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
@Override
|
||||
public @NonNull List<Subject> getParents(@NonNull Set<Context> contexts) {
|
||||
return (List) handle().thenApply(handle -> handle.getParents(CompatibilityUtil.convertContexts(contexts)).stream()
|
||||
.map(s -> new SubjectProxy(this.service, s))
|
||||
.collect(ImmutableCollectors.toList())).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Optional<String> getOption(@NonNull Set<Context> contexts, @NonNull String key) {
|
||||
return handle().thenApply(handle -> handle.getOption(CompatibilityUtil.convertContexts(contexts), key)).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Optional<String> getOption(@NonNull String key) {
|
||||
return handle().thenApply(handle -> handle.getOption(getContextsCache().getContextSet(), key)).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getIdentifier() {
|
||||
return this.ref.getSubjectIdentifier();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Set<Context> getActiveContexts() {
|
||||
return CompatibilityUtil.convertContexts(getContextsCache().getContextSet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
return o == this || o instanceof SubjectProxy && this.ref.equals(((SubjectProxy) o).ref);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return this.ref.hashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "luckperms.api6.SubjectProxy(ref=" + this.ref + ")";
|
||||
}
|
||||
}
|
||||
+11
-6
@@ -23,15 +23,20 @@
|
||||
* SOFTWARE.
|
||||
*/
|
||||
|
||||
package me.lucko.luckperms.common.webeditor.socket.listener;
|
||||
package org.spongepowered.api.service.permission;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/**
|
||||
* A handler for a given type of message.
|
||||
* This is included, as the interface didn't exist in API6.
|
||||
* We just shade it into the LP jar so we can still implement it. :)
|
||||
*/
|
||||
public interface Handler {
|
||||
public interface SubjectReference {
|
||||
|
||||
void handle(JsonObject msg);
|
||||
String getCollectionIdentifier();
|
||||
|
||||
}
|
||||
String getSubjectIdentifier();
|
||||
|
||||
CompletableFuture<Subject> resolve();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
repositories {
|
||||
maven { url 'https://repo.spongepowered.org/maven' }
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation project(':common')
|
||||
implementation project(':sponge:sponge-service')
|
||||
|
||||
compileOnly('org.spongepowered:spongeapi:7.3.0') {
|
||||
exclude(module: 'configurate-core')
|
||||
exclude(module: 'configurate-hocon')
|
||||
exclude(module: 'configurate-gson')
|
||||
exclude(module: 'configurate-yaml')
|
||||
}
|
||||
}
|
||||
+22
-13
@@ -23,34 +23,42 @@
|
||||
* SOFTWARE.
|
||||
*/
|
||||
|
||||
package me.lucko.luckperms.sponge.service.proxy.api8;
|
||||
package me.lucko.luckperms.sponge.service.proxy.api7;
|
||||
|
||||
import me.lucko.luckperms.common.context.ImmutableContextSetImpl;
|
||||
import me.lucko.luckperms.sponge.service.model.LPPermissionDescription;
|
||||
import me.lucko.luckperms.sponge.service.model.LPPermissionService;
|
||||
import me.lucko.luckperms.sponge.service.model.LPProxiedServiceObject;
|
||||
import me.lucko.luckperms.sponge.service.model.LPSubject;
|
||||
import me.lucko.luckperms.sponge.service.model.LPSubjectCollection;
|
||||
import me.lucko.luckperms.sponge.service.model.ProxiedServiceObject;
|
||||
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.luckperms.api.util.Tristate;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
import org.spongepowered.api.plugin.PluginContainer;
|
||||
import org.spongepowered.api.service.permission.PermissionDescription;
|
||||
import org.spongepowered.api.service.permission.PermissionService;
|
||||
import org.spongepowered.plugin.PluginContainer;
|
||||
import org.spongepowered.api.text.Text;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class DescriptionBuilder implements PermissionDescription.Builder, LPProxiedServiceObject {
|
||||
public final class DescriptionBuilder implements PermissionDescription.Builder, ProxiedServiceObject {
|
||||
|
||||
public static LPPermissionDescription registerDescription(LPPermissionService service, PermissionDescription description) {
|
||||
if (!description.getOwner().isPresent()) {
|
||||
return null;
|
||||
}
|
||||
return service.registerPermissionDescription(description.getId(), description.getDescription().orElse(null), description.getOwner().get());
|
||||
}
|
||||
|
||||
private final @NonNull LPPermissionService service;
|
||||
private final @NonNull PluginContainer container;
|
||||
private final @NonNull Map<String, Tristate> roles = new HashMap<>();
|
||||
private @Nullable String id = null;
|
||||
private @Nullable Component description = null;
|
||||
private @Nullable Text description = null;
|
||||
|
||||
public DescriptionBuilder(LPPermissionService service, PluginContainer container) {
|
||||
this.service = Objects.requireNonNull(service, "service");
|
||||
@@ -64,7 +72,7 @@ public final class DescriptionBuilder implements PermissionDescription.Builder,
|
||||
}
|
||||
|
||||
@Override
|
||||
public PermissionDescription.@NonNull Builder description(@Nullable Component description) {
|
||||
public PermissionDescription.@NonNull Builder description(@Nullable Text description) {
|
||||
this.description = description;
|
||||
return this;
|
||||
}
|
||||
@@ -76,11 +84,6 @@ public final class DescriptionBuilder implements PermissionDescription.Builder,
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PermissionDescription.Builder defaultValue(org.spongepowered.api.util.Tristate defaultValue) {
|
||||
throw new UnsupportedOperationException("LuckPerms does not support assigning a default value to permission descriptions");
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull PermissionDescription register() throws IllegalStateException {
|
||||
if (this.id == null) {
|
||||
@@ -118,7 +121,13 @@ public final class DescriptionBuilder implements PermissionDescription.Builder,
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(this.container, this.roles, this.id, this.description);
|
||||
final int PRIME = 59;
|
||||
int result = 1;
|
||||
result = result * PRIME + this.container.hashCode();
|
||||
result = result * PRIME + this.roles.hashCode();
|
||||
result = result * PRIME + (this.id == null ? 43 : this.id.hashCode());
|
||||
result = result * PRIME + (this.description == null ? 43 : this.description.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
+10
-50
@@ -23,29 +23,25 @@
|
||||
* SOFTWARE.
|
||||
*/
|
||||
|
||||
package me.lucko.luckperms.sponge.service.proxy.api8;
|
||||
package me.lucko.luckperms.sponge.service.proxy.api7;
|
||||
|
||||
import me.lucko.luckperms.common.util.ImmutableCollectors;
|
||||
import me.lucko.luckperms.sponge.service.model.LPPermissionDescription;
|
||||
import me.lucko.luckperms.sponge.service.model.LPPermissionService;
|
||||
import me.lucko.luckperms.sponge.service.model.LPProxiedServiceObject;
|
||||
|
||||
import net.kyori.adventure.text.Component;
|
||||
import me.lucko.luckperms.sponge.service.model.ProxiedServiceObject;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.spongepowered.api.ResourceKey;
|
||||
import org.spongepowered.api.plugin.PluginContainer;
|
||||
import org.spongepowered.api.service.permission.PermissionDescription;
|
||||
import org.spongepowered.api.service.permission.Subject;
|
||||
import org.spongepowered.api.service.permission.SubjectReference;
|
||||
import org.spongepowered.api.util.Tristate;
|
||||
import org.spongepowered.plugin.PluginContainer;
|
||||
import org.spongepowered.api.text.Text;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public final class PermissionDescriptionProxy implements PermissionDescription, LPProxiedServiceObject {
|
||||
public final class PermissionDescriptionProxy implements PermissionDescription, ProxiedServiceObject {
|
||||
private final LPPermissionService service;
|
||||
private final LPPermissionDescription handle;
|
||||
|
||||
@@ -55,27 +51,22 @@ public final class PermissionDescriptionProxy implements PermissionDescription,
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull String id() {
|
||||
public @NonNull String getId() {
|
||||
return this.handle.getId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Optional<Component> description() {
|
||||
public @NonNull Optional<Text> getDescription() {
|
||||
return this.handle.getDescription();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Optional<PluginContainer> owner() {
|
||||
public @NonNull Optional<PluginContainer> getOwner() {
|
||||
return this.handle.getOwner();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Tristate defaultValue() {
|
||||
return Tristate.UNDEFINED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Map<Subject, Boolean> assignedSubjects(@NonNull String s) {
|
||||
public @NonNull Map<Subject, Boolean> getAssignedSubjects(@NonNull String s) {
|
||||
return this.handle.getAssignedSubjects(s).entrySet().stream()
|
||||
.collect(ImmutableCollectors.toMap(
|
||||
e -> new SubjectProxy(this.service, e.getKey().toReference()),
|
||||
@@ -83,37 +74,6 @@ public final class PermissionDescriptionProxy implements PermissionDescription,
|
||||
));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean query(Subject subj) {
|
||||
return subj.hasPermission(this.handle.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean query(Subject subj, String parameter) {
|
||||
Objects.requireNonNull(parameter, "parameter");
|
||||
return subj.hasPermission(this.handle.getId() + '.' + parameter);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean query(Subject subj, ResourceKey key) {
|
||||
return query(subj, key.namespace() + '.' + key.value());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean query(Subject subj, String... parameters) {
|
||||
if (parameters.length == 0) {
|
||||
return this.query(subj);
|
||||
} else if (parameters.length == 1) {
|
||||
return this.query(subj, parameters[0]);
|
||||
}
|
||||
|
||||
StringBuilder builder = new StringBuilder(this.handle.getId());
|
||||
for (String parameter : parameters) {
|
||||
builder.append('.').append(parameter);
|
||||
}
|
||||
return subj.hasPermission(builder.toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
public @NonNull CompletableFuture<Map<SubjectReference, Boolean>> findAssignedSubjects(@NonNull String s) {
|
||||
@@ -132,6 +92,6 @@ public final class PermissionDescriptionProxy implements PermissionDescription,
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "luckperms.api8.PermissionDescriptionProxy(handle=" + this.handle + ")";
|
||||
return "luckperms.api7.PermissionDescriptionProxy(handle=" + this.handle + ")";
|
||||
}
|
||||
}
|
||||
+26
-35
@@ -23,28 +23,25 @@
|
||||
* SOFTWARE.
|
||||
*/
|
||||
|
||||
package me.lucko.luckperms.sponge.service.proxy.api8;
|
||||
package me.lucko.luckperms.sponge.service.proxy.api7;
|
||||
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
|
||||
import me.lucko.luckperms.common.util.ImmutableCollectors;
|
||||
import me.lucko.luckperms.sponge.service.CompatibilityUtil;
|
||||
import me.lucko.luckperms.sponge.service.PermissionAndContextService;
|
||||
import me.lucko.luckperms.sponge.service.model.LPPermissionDescription;
|
||||
import me.lucko.luckperms.sponge.service.model.LPPermissionService;
|
||||
import me.lucko.luckperms.sponge.service.model.LPProxiedServiceObject;
|
||||
import me.lucko.luckperms.sponge.service.model.LPSubjectCollection;
|
||||
import me.lucko.luckperms.sponge.service.model.ProxiedServiceObject;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.spongepowered.api.event.Cause;
|
||||
import org.spongepowered.api.service.context.Context;
|
||||
import org.spongepowered.api.Sponge;
|
||||
import org.spongepowered.api.plugin.PluginContainer;
|
||||
import org.spongepowered.api.service.context.ContextCalculator;
|
||||
import org.spongepowered.api.service.permission.PermissionDescription;
|
||||
import org.spongepowered.api.service.permission.PermissionService;
|
||||
import org.spongepowered.api.service.permission.Subject;
|
||||
import org.spongepowered.api.service.permission.SubjectCollection;
|
||||
import org.spongepowered.api.service.permission.SubjectReference;
|
||||
import org.spongepowered.plugin.PluginContainer;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Locale;
|
||||
@@ -55,7 +52,7 @@ import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
public final class PermissionServiceProxy implements PermissionAndContextService, LPProxiedServiceObject {
|
||||
public final class PermissionServiceProxy implements PermissionService, ProxiedServiceObject {
|
||||
private final LPPermissionService handle;
|
||||
|
||||
public PermissionServiceProxy(LPPermissionService handle) {
|
||||
@@ -63,22 +60,22 @@ public final class PermissionServiceProxy implements PermissionAndContextService
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull SubjectCollection userSubjects() {
|
||||
public @NonNull SubjectCollection getUserSubjects() {
|
||||
return this.handle.getUserSubjects().sponge();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull SubjectCollection groupSubjects() {
|
||||
public @NonNull SubjectCollection getGroupSubjects() {
|
||||
return this.handle.getGroupSubjects().sponge();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Subject defaults() {
|
||||
public @NonNull Subject getDefaults() {
|
||||
return this.handle.getRootDefaults().sponge();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Predicate<String> identifierValidityPredicate() {
|
||||
public @NonNull Predicate<String> getIdentifierValidityPredicate() {
|
||||
return this.handle.getIdentifierValidityPredicate();
|
||||
}
|
||||
|
||||
@@ -88,7 +85,7 @@ public final class PermissionServiceProxy implements PermissionAndContextService
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Optional<SubjectCollection> collection(String s) {
|
||||
public @NonNull Optional<SubjectCollection> getCollection(String s) {
|
||||
return Optional.ofNullable(this.handle.getLoadedCollections().get(s.toLowerCase(Locale.ROOT))).map(LPSubjectCollection::sponge);
|
||||
}
|
||||
|
||||
@@ -98,7 +95,7 @@ public final class PermissionServiceProxy implements PermissionAndContextService
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Map<String, SubjectCollection> loadedCollections() {
|
||||
public @NonNull Map<String, SubjectCollection> getLoadedCollections() {
|
||||
return this.handle.getLoadedCollections().entrySet().stream()
|
||||
.collect(ImmutableCollectors.toMap(
|
||||
Map.Entry::getKey,
|
||||
@@ -107,7 +104,7 @@ public final class PermissionServiceProxy implements PermissionAndContextService
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<? extends Set<String>> allIdentifiers() {
|
||||
public CompletableFuture<Set<String>> getAllIdentifiers() {
|
||||
return CompletableFuture.completedFuture(ImmutableSet.copyOf(this.handle.getLoadedCollections().keySet()));
|
||||
}
|
||||
|
||||
@@ -117,11 +114,10 @@ public final class PermissionServiceProxy implements PermissionAndContextService
|
||||
Objects.requireNonNull(subjectIdentifier, "subjectIdentifier");
|
||||
|
||||
// test the identifiers
|
||||
if (collectionIdentifier.equalsIgnoreCase(PermissionService.SUBJECTS_USER) &&
|
||||
!this.handle.getUserSubjects().getIdentifierValidityPredicate().test(subjectIdentifier)) {
|
||||
String collection = collectionIdentifier.toLowerCase(Locale.ROOT);
|
||||
if (collection.equals("user") && !this.handle.getUserSubjects().getIdentifierValidityPredicate().test(subjectIdentifier)) {
|
||||
throw new IllegalArgumentException("Subject identifier '" + subjectIdentifier + "' does not pass the validity predicate for the user subject collection");
|
||||
} else if (collectionIdentifier.equalsIgnoreCase(PermissionService.SUBJECTS_GROUP) &&
|
||||
!this.handle.getGroupSubjects().getIdentifierValidityPredicate().test(subjectIdentifier)) {
|
||||
} else if (collection.equals("group") && !this.handle.getGroupSubjects().getIdentifierValidityPredicate().test(subjectIdentifier)) {
|
||||
throw new IllegalArgumentException("Subject identifier '" + subjectIdentifier + "' does not pass the validity predicate for the group subject collection");
|
||||
}
|
||||
|
||||
@@ -130,32 +126,27 @@ public final class PermissionServiceProxy implements PermissionAndContextService
|
||||
}
|
||||
|
||||
@Override
|
||||
public PermissionDescription.Builder newDescriptionBuilder(@NonNull PluginContainer container) {
|
||||
return new DescriptionBuilder(this.handle, container);
|
||||
public PermissionDescription.Builder newDescriptionBuilder(@NonNull Object o) {
|
||||
Optional<PluginContainer> container = Sponge.getGame().getPluginManager().fromInstance(o);
|
||||
if (!container.isPresent()) {
|
||||
throw new IllegalArgumentException("Couldn't find a plugin container for " + o.getClass().getSimpleName());
|
||||
}
|
||||
|
||||
return new DescriptionBuilder(this.handle, container.get());
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Optional<PermissionDescription> description(@NonNull String s) {
|
||||
public @NonNull Optional<PermissionDescription> getDescription(@NonNull String s) {
|
||||
return this.handle.getDescription(s).map(LPPermissionDescription::sponge);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Collection<PermissionDescription> descriptions() {
|
||||
public @NonNull Collection<PermissionDescription> getDescriptions() {
|
||||
return this.handle.getDescriptions().stream().map(LPPermissionDescription::sponge).collect(ImmutableCollectors.toSet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Context> contexts() {
|
||||
return CompatibilityUtil.convertContexts(this.handle.getContextsForCurrentCause());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Context> contextsFor(Cause cause) {
|
||||
return CompatibilityUtil.convertContexts(this.handle.getContextsForCurrentCause());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerContextCalculator(@NonNull ContextCalculator contextCalculator) {
|
||||
public void registerContextCalculator(@NonNull ContextCalculator<Subject> contextCalculator) {
|
||||
this.handle.registerContextCalculator(contextCalculator);
|
||||
}
|
||||
|
||||
@@ -171,6 +162,6 @@ public final class PermissionServiceProxy implements PermissionAndContextService
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "luckperms.api8.PermissionServiceProxy(handle=" + this.handle + ")";
|
||||
return "luckperms.api7.PermissionServiceProxy(handle=" + this.handle + ")";
|
||||
}
|
||||
}
|
||||
+20
-19
@@ -23,15 +23,16 @@
|
||||
* SOFTWARE.
|
||||
*/
|
||||
|
||||
package me.lucko.luckperms.sponge.service.proxy.api8;
|
||||
package me.lucko.luckperms.sponge.service.proxy.api7;
|
||||
|
||||
import me.lucko.luckperms.common.util.ImmutableCollectors;
|
||||
import me.lucko.luckperms.sponge.service.model.LPProxiedServiceObject;
|
||||
import me.lucko.luckperms.sponge.service.CompatibilityUtil;
|
||||
import me.lucko.luckperms.sponge.service.model.LPSubject;
|
||||
import me.lucko.luckperms.sponge.service.model.LPSubjectCollection;
|
||||
import me.lucko.luckperms.sponge.service.model.ProxiedServiceObject;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.spongepowered.api.event.Cause;
|
||||
import org.spongepowered.api.service.context.Context;
|
||||
import org.spongepowered.api.service.permission.Subject;
|
||||
import org.spongepowered.api.service.permission.SubjectCollection;
|
||||
import org.spongepowered.api.service.permission.SubjectReference;
|
||||
@@ -45,7 +46,7 @@ import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public final class SubjectCollectionProxy implements SubjectCollection, LPProxiedServiceObject {
|
||||
public final class SubjectCollectionProxy implements SubjectCollection, ProxiedServiceObject {
|
||||
private final LPSubjectCollection handle;
|
||||
|
||||
public SubjectCollectionProxy(LPSubjectCollection handle) {
|
||||
@@ -53,12 +54,12 @@ public final class SubjectCollectionProxy implements SubjectCollection, LPProxie
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull String identifier() {
|
||||
public @NonNull String getIdentifier() {
|
||||
return this.handle.getIdentifier();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Predicate<String> identifierValidityPredicate() {
|
||||
public @NonNull Predicate<String> getIdentifierValidityPredicate() {
|
||||
return this.handle.getIdentifierValidityPredicate();
|
||||
}
|
||||
|
||||
@@ -68,7 +69,7 @@ public final class SubjectCollectionProxy implements SubjectCollection, LPProxie
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Optional<Subject> subject(@NonNull String s) {
|
||||
public @NonNull Optional<Subject> getSubject(@NonNull String s) {
|
||||
return this.handle.getSubject(s).map(LPSubject::sponge);
|
||||
}
|
||||
|
||||
@@ -78,18 +79,18 @@ public final class SubjectCollectionProxy implements SubjectCollection, LPProxie
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull CompletableFuture<Map<String, Subject>> loadSubjects(@NonNull Iterable<String> set) {
|
||||
public @NonNull CompletableFuture<Map<String, Subject>> loadSubjects(@NonNull Set<String> set) {
|
||||
return this.handle.loadSubjects(set).thenApply(subs -> subs.stream().collect(ImmutableCollectors.toMap(lpSubject -> lpSubject.getIdentifier().getName(), LPSubject::sponge)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Collection<Subject> loadedSubjects() {
|
||||
public @NonNull Collection<Subject> getLoadedSubjects() {
|
||||
return this.handle.getLoadedSubjects().stream().map(LPSubject::sponge).collect(ImmutableCollectors.toSet());
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
@Override
|
||||
public @NonNull CompletableFuture<Set<String>> allIdentifiers() {
|
||||
public @NonNull CompletableFuture<Set<String>> getAllIdentifiers() {
|
||||
return (CompletableFuture) this.handle.getAllIdentifiers();
|
||||
}
|
||||
|
||||
@@ -100,23 +101,23 @@ public final class SubjectCollectionProxy implements SubjectCollection, LPProxie
|
||||
throw new IllegalArgumentException("Subject identifier '" + subjectIdentifier + "' does not pass the validity predicate");
|
||||
}
|
||||
|
||||
return this.handle.getService().getReferenceFactory().obtain(identifier(), subjectIdentifier);
|
||||
return this.handle.getService().getReferenceFactory().obtain(getIdentifier(), subjectIdentifier);
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
@Override
|
||||
public @NonNull CompletableFuture<Map<SubjectReference, Boolean>> allWithPermission(@NonNull String s) {
|
||||
public @NonNull CompletableFuture<Map<SubjectReference, Boolean>> getAllWithPermission(@NonNull String s) {
|
||||
return (CompletableFuture) this.handle.getAllWithPermission(s);
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
@Override
|
||||
public @NonNull CompletableFuture<Map<SubjectReference, Boolean>> allWithPermission(@NonNull String s, @NonNull Cause cause) {
|
||||
return (CompletableFuture) this.handle.getAllWithPermission(this.handle.getService().getContextsForCause(cause), s);
|
||||
public @NonNull CompletableFuture<Map<SubjectReference, Boolean>> getAllWithPermission(@NonNull Set<Context> set, @NonNull String s) {
|
||||
return (CompletableFuture) this.handle.getAllWithPermission(CompatibilityUtil.convertContexts(set), s);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Map<Subject, Boolean> loadedWithPermission(@NonNull String s) {
|
||||
public @NonNull Map<Subject, Boolean> getLoadedWithPermission(@NonNull String s) {
|
||||
return this.handle.getLoadedWithPermission(s).entrySet().stream()
|
||||
.collect(ImmutableCollectors.toMap(
|
||||
sub -> sub.getKey().sponge(),
|
||||
@@ -125,8 +126,8 @@ public final class SubjectCollectionProxy implements SubjectCollection, LPProxie
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Map<Subject, Boolean> loadedWithPermission(@NonNull String s, @NonNull Cause cause) {
|
||||
return this.handle.getLoadedWithPermission(this.handle.getService().getContextsForCause(cause), s).entrySet().stream()
|
||||
public @NonNull Map<Subject, Boolean> getLoadedWithPermission(@NonNull Set<Context> set, @NonNull String s) {
|
||||
return this.handle.getLoadedWithPermission(CompatibilityUtil.convertContexts(set), s).entrySet().stream()
|
||||
.collect(ImmutableCollectors.toMap(
|
||||
sub -> sub.getKey().sponge(),
|
||||
Map.Entry::getValue
|
||||
@@ -134,7 +135,7 @@ public final class SubjectCollectionProxy implements SubjectCollection, LPProxie
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Subject defaults() {
|
||||
public @NonNull Subject getDefaults() {
|
||||
return this.handle.getDefaults().sponge();
|
||||
}
|
||||
|
||||
@@ -155,7 +156,7 @@ public final class SubjectCollectionProxy implements SubjectCollection, LPProxie
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "luckperms.api8.SubjectCollectionProxy(handle=" + this.handle + ")";
|
||||
return "luckperms.api7.SubjectCollectionProxy(handle=" + this.handle + ")";
|
||||
}
|
||||
|
||||
}
|
||||
+15
-85
@@ -23,36 +23,29 @@
|
||||
* SOFTWARE.
|
||||
*/
|
||||
|
||||
package me.lucko.luckperms.sponge.service.proxy.api8;
|
||||
package me.lucko.luckperms.sponge.service.proxy.api7;
|
||||
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
|
||||
import me.lucko.luckperms.common.util.CompletableFutures;
|
||||
import me.lucko.luckperms.common.util.ImmutableCollectors;
|
||||
import me.lucko.luckperms.sponge.service.CompatibilityUtil;
|
||||
import me.lucko.luckperms.sponge.service.model.LPPermissionService;
|
||||
import me.lucko.luckperms.sponge.service.model.LPProxiedServiceObject;
|
||||
import me.lucko.luckperms.sponge.service.model.LPSubject;
|
||||
import me.lucko.luckperms.sponge.service.model.LPSubjectData;
|
||||
import me.lucko.luckperms.sponge.service.model.LPSubjectReference;
|
||||
import me.lucko.luckperms.sponge.service.model.ProxiedServiceObject;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
import org.spongepowered.api.service.context.Context;
|
||||
import org.spongepowered.api.service.permission.Subject;
|
||||
import org.spongepowered.api.service.permission.SubjectData;
|
||||
import org.spongepowered.api.service.permission.SubjectReference;
|
||||
import org.spongepowered.api.service.permission.TransferMethod;
|
||||
import org.spongepowered.api.util.Tristate;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public final class SubjectDataProxy implements SubjectData, LPProxiedServiceObject {
|
||||
public final class SubjectDataProxy implements SubjectData, ProxiedServiceObject {
|
||||
private final LPPermissionService service;
|
||||
private final LPSubjectReference ref;
|
||||
private final boolean enduring;
|
||||
@@ -69,19 +62,9 @@ public final class SubjectDataProxy implements SubjectData, LPProxiedServiceObje
|
||||
this.ref.resolveLp().thenApply(LPSubject::getTransientSubjectData);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Subject subject() {
|
||||
return handle().thenApply(handle -> handle.getParentSubject().sponge()).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isTransient() {
|
||||
return !this.enduring;
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
@Override
|
||||
public @NonNull Map<Set<Context>, Map<String, Boolean>> allPermissions() {
|
||||
public @NonNull Map<Set<Context>, Map<String, Boolean>> getAllPermissions() {
|
||||
return (Map) handle().thenApply(handle -> handle.getAllPermissions().entrySet().stream()
|
||||
.collect(ImmutableCollectors.toMap(
|
||||
e -> CompatibilityUtil.convertContexts(e.getKey()),
|
||||
@@ -90,7 +73,7 @@ public final class SubjectDataProxy implements SubjectData, LPProxiedServiceObje
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Map<String, Boolean> permissions(@NonNull Set<Context> contexts) {
|
||||
public @NonNull Map<String, Boolean> getPermissions(@NonNull Set<Context> contexts) {
|
||||
return handle().thenApply(handle -> handle.getPermissions(CompatibilityUtil.convertContexts(contexts))).join();
|
||||
}
|
||||
|
||||
@@ -103,43 +86,6 @@ public final class SubjectDataProxy implements SubjectData, LPProxiedServiceObje
|
||||
));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Boolean> setPermissions(Set<Context> contexts, Map<String, Boolean> permissions, TransferMethod method) {
|
||||
CompletableFuture<Boolean> fut;
|
||||
if (method == TransferMethod.OVERWRITE) {
|
||||
fut = clearPermissions(contexts);
|
||||
} else {
|
||||
fut = CompletableFuture.completedFuture(true);
|
||||
}
|
||||
|
||||
return fut.thenCompose(bool -> permissions.entrySet().stream()
|
||||
.map(entry -> setPermission(contexts, entry.getKey(), Tristate.fromBoolean(entry.getValue())))
|
||||
.collect(CompletableFutures.collector())
|
||||
)
|
||||
.thenApply(x -> true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Tristate fallbackPermissionValue(Set<Context> contexts) {
|
||||
// TODO: check subject type here to return a more appropriate value?
|
||||
return Tristate.UNDEFINED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<Set<Context>, Tristate> allFallbackPermissionValues() {
|
||||
return ImmutableMap.of();
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Boolean> setFallbackPermissionValue(Set<Context> contexts, Tristate fallback) {
|
||||
throw new UnsupportedOperationException("LuckPerms does not support setting fallback permission values");
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Boolean> clearFallbackPermissionValues() {
|
||||
return CompletableFuture.completedFuture(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull CompletableFuture<Boolean> clearPermissions() {
|
||||
return handle().thenCompose(LPSubjectData::clearPermissions);
|
||||
@@ -152,7 +98,7 @@ public final class SubjectDataProxy implements SubjectData, LPProxiedServiceObje
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
@Override
|
||||
public @NonNull Map<Set<Context>, List<org.spongepowered.api.service.permission.SubjectReference>> allParents() {
|
||||
public @NonNull Map<Set<Context>, List<org.spongepowered.api.service.permission.SubjectReference>> getAllParents() {
|
||||
return (Map) handle().thenApply(handle -> handle.getAllParents().entrySet().stream()
|
||||
.collect(ImmutableCollectors.toMap(
|
||||
e -> CompatibilityUtil.convertContexts(e.getKey()),
|
||||
@@ -162,15 +108,10 @@ public final class SubjectDataProxy implements SubjectData, LPProxiedServiceObje
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
@Override
|
||||
public @NonNull List<org.spongepowered.api.service.permission.SubjectReference> parents(@NonNull Set<Context> contexts) {
|
||||
public @NonNull List<org.spongepowered.api.service.permission.SubjectReference> getParents(@NonNull Set<Context> contexts) {
|
||||
return (List) handle().thenApply(handle -> handle.getParents(CompatibilityUtil.convertContexts(contexts))).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Boolean> setParents(Set<Context> contexts, List<? extends SubjectReference> parents, TransferMethod method) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull CompletableFuture<Boolean> addParent(@NonNull Set<Context> contexts, org.spongepowered.api.service.permission.@NonNull SubjectReference ref) {
|
||||
return handle().thenCompose(handle -> handle.addParent(CompatibilityUtil.convertContexts(contexts), this.service.getReferenceFactory().obtain(ref)));
|
||||
@@ -193,7 +134,7 @@ public final class SubjectDataProxy implements SubjectData, LPProxiedServiceObje
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
@Override
|
||||
public @NonNull Map<Set<Context>, Map<String, String>> allOptions() {
|
||||
public @NonNull Map<Set<Context>, Map<String, String>> getAllOptions() {
|
||||
return (Map) handle().thenApply(handle -> handle.getAllOptions().entrySet().stream()
|
||||
.collect(ImmutableCollectors.toMap(
|
||||
e -> CompatibilityUtil.convertContexts(e.getKey()),
|
||||
@@ -202,7 +143,7 @@ public final class SubjectDataProxy implements SubjectData, LPProxiedServiceObje
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Map<String, String> options(@NonNull Set<Context> contexts) {
|
||||
public @NonNull Map<String, String> getOptions(@NonNull Set<Context> contexts) {
|
||||
return handle().thenApply(handle -> handle.getOptions(CompatibilityUtil.convertContexts(contexts))).join();
|
||||
}
|
||||
|
||||
@@ -215,11 +156,6 @@ public final class SubjectDataProxy implements SubjectData, LPProxiedServiceObje
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Boolean> setOptions(Set<Context> contexts, Map<String, String> options, TransferMethod method) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull CompletableFuture<Boolean> clearOptions() {
|
||||
return handle().thenCompose(LPSubjectData::clearOptions);
|
||||
@@ -230,16 +166,6 @@ public final class SubjectDataProxy implements SubjectData, LPProxiedServiceObje
|
||||
return handle().thenCompose(handle -> handle.clearOptions(CompatibilityUtil.convertContexts(contexts)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Boolean> copyFrom(SubjectData other, TransferMethod method) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Boolean> moveFrom(SubjectData other, TransferMethod method) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (o == this) return true;
|
||||
@@ -250,11 +176,15 @@ public final class SubjectDataProxy implements SubjectData, LPProxiedServiceObje
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(this.ref, this.enduring);
|
||||
final int PRIME = 59;
|
||||
int result = 1;
|
||||
result = result * PRIME + this.ref.hashCode();
|
||||
result = result * PRIME + (this.enduring ? 79 : 97);
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "luckperms.api8.SubjectDataProxy(ref=" + this.ref + ", enduring=" + this.enduring + ")";
|
||||
return "luckperms.api7.SubjectDataProxy(ref=" + this.ref + ", enduring=" + this.enduring + ")";
|
||||
}
|
||||
}
|
||||
+58
-47
@@ -23,23 +23,21 @@
|
||||
* SOFTWARE.
|
||||
*/
|
||||
|
||||
package me.lucko.luckperms.sponge.service.proxy.api8;
|
||||
package me.lucko.luckperms.sponge.service.proxy.api7;
|
||||
|
||||
import me.lucko.luckperms.common.context.manager.QueryOptionsSupplier;
|
||||
import me.lucko.luckperms.sponge.service.CompatibilityUtil;
|
||||
import me.lucko.luckperms.sponge.service.model.LPPermissionService;
|
||||
import me.lucko.luckperms.sponge.service.model.LPProxiedServiceObject;
|
||||
import me.lucko.luckperms.sponge.service.model.LPProxiedSubject;
|
||||
import me.lucko.luckperms.sponge.service.model.LPSubject;
|
||||
import me.lucko.luckperms.sponge.service.model.LPSubjectReference;
|
||||
import me.lucko.luckperms.sponge.service.model.LPSubjectUser;
|
||||
import me.lucko.luckperms.sponge.service.model.ProxiedServiceObject;
|
||||
import me.lucko.luckperms.sponge.service.model.ProxiedSubject;
|
||||
|
||||
import net.luckperms.api.query.QueryOptions;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.spongepowered.api.entity.living.player.server.ServerPlayer;
|
||||
import org.spongepowered.api.event.Cause;
|
||||
import org.spongepowered.api.command.CommandSource;
|
||||
import org.spongepowered.api.service.context.Context;
|
||||
import org.spongepowered.api.service.permission.PermissionService;
|
||||
import org.spongepowered.api.service.permission.Subject;
|
||||
import org.spongepowered.api.service.permission.SubjectCollection;
|
||||
import org.spongepowered.api.service.permission.SubjectData;
|
||||
@@ -52,10 +50,12 @@ import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public final class SubjectProxy implements Subject, LPProxiedSubject, LPProxiedServiceObject {
|
||||
public final class SubjectProxy implements Subject, ProxiedSubject, ProxiedServiceObject {
|
||||
private final LPPermissionService service;
|
||||
private final LPSubjectReference ref;
|
||||
|
||||
private QueryOptionsSupplier queryOptionsSupplier;
|
||||
|
||||
public SubjectProxy(LPPermissionService service, LPSubjectReference ref) {
|
||||
this.service = service;
|
||||
this.ref = ref;
|
||||
@@ -65,6 +65,14 @@ public final class SubjectProxy implements Subject, LPProxiedSubject, LPProxiedS
|
||||
return this.ref.resolveLp();
|
||||
}
|
||||
|
||||
// lazy init
|
||||
private QueryOptionsSupplier queryOptionsCache() {
|
||||
if (this.queryOptionsSupplier == null) {
|
||||
this.queryOptionsSupplier = this.service.getContextManager().getCacheFor(this);
|
||||
}
|
||||
return this.queryOptionsSupplier;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull LPSubjectReference asSubjectReference() {
|
||||
return this.ref;
|
||||
@@ -72,12 +80,17 @@ public final class SubjectProxy implements Subject, LPProxiedSubject, LPProxiedS
|
||||
|
||||
@Override
|
||||
public @NonNull QueryOptions getQueryOptions() {
|
||||
return this.service.getContextManager().getQueryOptions(this);
|
||||
return queryOptionsCache().getQueryOptions();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull SubjectCollection containingCollection() {
|
||||
return this.service.getCollection(this.ref.collectionIdentifier()).sponge();
|
||||
public @NonNull Optional<CommandSource> getCommandSource() {
|
||||
return handle().thenApply(LPSubject::getCommandSource).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull SubjectCollection getContainingCollection() {
|
||||
return this.service.getCollection(this.ref.getCollectionIdentifier()).sponge();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -86,77 +99,75 @@ public final class SubjectProxy implements Subject, LPProxiedSubject, LPProxiedS
|
||||
}
|
||||
|
||||
@Override
|
||||
public SubjectData subjectData() {
|
||||
public SubjectData getSubjectData() {
|
||||
return new SubjectDataProxy(this.service, this.ref, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SubjectData transientSubjectData() {
|
||||
public SubjectData getTransientSubjectData() {
|
||||
return new SubjectDataProxy(this.service, this.ref, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Tristate permissionValue(@NonNull String permission, @NonNull Cause cause) {
|
||||
return handle().thenApply(handle -> CompatibilityUtil.convertTristate(handle.getPermissionValue(this.service.getContextsForCause(cause), permission))).join();
|
||||
public boolean hasPermission(@NonNull Set<Context> contexts, @NonNull String permission) {
|
||||
return handle().thenApply(handle -> handle.getPermissionValue(CompatibilityUtil.convertContexts(contexts), permission).asBoolean()).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Tristate permissionValue(@NonNull String permission, @NonNull Set<Context> contexts) {
|
||||
public boolean hasPermission(@NonNull String permission) {
|
||||
return handle().thenApply(handle -> handle.getPermissionValue(queryOptionsCache().getContextSet(), permission).asBoolean()).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Tristate getPermissionValue(@NonNull Set<Context> contexts, @NonNull String permission) {
|
||||
return handle().thenApply(handle -> CompatibilityUtil.convertTristate(handle.getPermissionValue(CompatibilityUtil.convertContexts(contexts), permission))).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isChildOf(@NonNull SubjectReference parent, @NonNull Cause cause) {
|
||||
return handle().thenApply(handle -> handle.isChildOf(this.service.getContextsForCause(cause), this.service.getReferenceFactory().obtain(parent))).join();
|
||||
public boolean isChildOf(@NonNull SubjectReference parent) {
|
||||
return handle().thenApply(handle -> handle.isChildOf(queryOptionsCache().getContextSet(), this.service.getReferenceFactory().obtain(parent))).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isChildOf(@NonNull SubjectReference parent, @NonNull Set<Context> contexts) {
|
||||
public boolean isChildOf(@NonNull Set<Context> contexts, @NonNull SubjectReference parent) {
|
||||
return handle().thenApply(handle -> handle.isChildOf(CompatibilityUtil.convertContexts(contexts), this.service.getReferenceFactory().obtain(parent))).join();
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
@Override
|
||||
public List<? extends SubjectReference> parents(@NonNull Cause cause) {
|
||||
return handle().thenApply(handle -> handle.getParents(this.service.getContextsForCause(cause))).join();
|
||||
public @NonNull List<SubjectReference> getParents() {
|
||||
return (List) handle().thenApply(handle -> handle.getParents(queryOptionsCache().getContextSet())).join();
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
@Override
|
||||
public @NonNull List<SubjectReference> getParents(@NonNull Set<Context> contexts) {
|
||||
return (List) handle().thenApply(handle -> handle.getParents(CompatibilityUtil.convertContexts(contexts))).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull List<? extends SubjectReference> parents(@NonNull Set<Context> contexts) {
|
||||
return handle().thenApply(handle -> handle.getParents(CompatibilityUtil.convertContexts(contexts))).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> option(@NonNull String key, @NonNull Cause cause) {
|
||||
return handle().thenApply(handle -> handle.getOption(this.service.getContextsForCause(cause), key)).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Optional<String> option(@NonNull String key, @NonNull Set<Context> contexts) {
|
||||
public @NonNull Optional<String> getOption(@NonNull Set<Context> contexts, @NonNull String key) {
|
||||
return handle().thenApply(handle -> handle.getOption(CompatibilityUtil.convertContexts(contexts), key)).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String identifier() {
|
||||
return this.ref.subjectIdentifier();
|
||||
public @NonNull Optional<String> getOption(@NonNull String key) {
|
||||
return handle().thenApply(handle -> handle.getOption(queryOptionsCache().getContextSet(), key)).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Optional<String> friendlyIdentifier() {
|
||||
public String getIdentifier() {
|
||||
return this.ref.getSubjectIdentifier();
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull Optional<String> getFriendlyIdentifier() {
|
||||
return handle().thenApply(LPSubject::getFriendlyIdentifier).join();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<?> associatedObject() {
|
||||
if (this.ref.collectionIdentifier().equals(PermissionService.SUBJECTS_USER)) {
|
||||
LPSubject lpSubject = handle().join();
|
||||
if (lpSubject instanceof LPSubjectUser) {
|
||||
ServerPlayer player = ((LPSubjectUser) lpSubject).resolvePlayer().orElse(null);
|
||||
if (player != null) {
|
||||
return Optional.of(player);
|
||||
}
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
public @NonNull Set<Context> getActiveContexts() {
|
||||
return CompatibilityUtil.convertContexts(queryOptionsCache().getContextSet());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -171,6 +182,6 @@ public final class SubjectProxy implements Subject, LPProxiedSubject, LPProxiedS
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "luckperms.api8.SubjectProxy(ref=" + this.ref + ")";
|
||||
return "luckperms.api7.SubjectProxy(ref=" + this.ref + ")";
|
||||
}
|
||||
}
|
||||
+7
-7
@@ -23,14 +23,14 @@
|
||||
* SOFTWARE.
|
||||
*/
|
||||
|
||||
package me.lucko.luckperms.sponge.service.model;
|
||||
package org.spongepowered.api.event.permission;
|
||||
|
||||
import org.spongepowered.api.entity.living.player.server.ServerPlayer;
|
||||
import org.spongepowered.api.event.Event;
|
||||
import org.spongepowered.api.service.permission.SubjectData;
|
||||
|
||||
import java.util.Optional;
|
||||
// Copy of https://github.com/SpongePowered/SpongeAPI/blob/api-8/src/main/java/org/spongepowered/api/event/permission/SubjectDataUpdateEvent.java
|
||||
public interface SubjectDataUpdateEvent extends Event {
|
||||
|
||||
public interface LPSubjectUser extends LPSubject {
|
||||
SubjectData getUpdatedData();
|
||||
|
||||
Optional<ServerPlayer> resolvePlayer();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
repositories {
|
||||
maven { url 'https://repo.spongepowered.org/repository/maven-public/' }
|
||||
maven { url 'https://repo.spongepowered.org/maven' }
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation project(':common')
|
||||
|
||||
compileOnly('org.spongepowered:spongeapi:8.0.0') {
|
||||
compileOnly('org.spongepowered:spongeapi:7.2.0') {
|
||||
exclude(module: 'configurate-core')
|
||||
exclude(module: 'configurate-hocon')
|
||||
exclude(module: 'configurate-gson')
|
||||
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
/*
|
||||
* This file is part of LuckPerms, licensed under the MIT License.
|
||||
*
|
||||
* Copyright (c) lucko (Luck) <luck@lucko.me>
|
||||
* Copyright (c) contributors
|
||||
*
|
||||
* 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.sponge.service;
|
||||
|
||||
import org.spongepowered.api.service.context.ContextService;
|
||||
import org.spongepowered.api.service.permission.PermissionService;
|
||||
|
||||
public interface PermissionAndContextService extends PermissionService, ContextService {
|
||||
|
||||
}
|
||||
+3
-4
@@ -25,10 +25,9 @@
|
||||
|
||||
package me.lucko.luckperms.sponge.service.model;
|
||||
|
||||
import net.kyori.adventure.text.Component;
|
||||
|
||||
import org.spongepowered.api.plugin.PluginContainer;
|
||||
import org.spongepowered.api.service.permission.PermissionDescription;
|
||||
import org.spongepowered.plugin.PluginContainer;
|
||||
import org.spongepowered.api.text.Text;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -45,7 +44,7 @@ public interface LPPermissionDescription {
|
||||
|
||||
String getId();
|
||||
|
||||
Optional<Component> getDescription();
|
||||
Optional<Text> getDescription();
|
||||
|
||||
Optional<PluginContainer> getOwner();
|
||||
|
||||
|
||||
+7
-17
@@ -30,18 +30,14 @@ import com.google.common.collect.ImmutableMap;
|
||||
|
||||
import me.lucko.luckperms.common.context.manager.ContextManager;
|
||||
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
|
||||
import me.lucko.luckperms.sponge.service.PermissionAndContextService;
|
||||
import me.lucko.luckperms.sponge.service.reference.SubjectReferenceFactory;
|
||||
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.luckperms.api.context.ImmutableContextSet;
|
||||
|
||||
import org.spongepowered.api.entity.living.player.server.ServerPlayer;
|
||||
import org.spongepowered.api.event.Cause;
|
||||
import org.spongepowered.api.entity.living.player.Player;
|
||||
import org.spongepowered.api.plugin.PluginContainer;
|
||||
import org.spongepowered.api.service.context.ContextCalculator;
|
||||
import org.spongepowered.api.service.permission.PermissionService;
|
||||
import org.spongepowered.api.service.permission.Subject;
|
||||
import org.spongepowered.plugin.PluginContainer;
|
||||
import org.spongepowered.api.text.Text;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.function.Predicate;
|
||||
@@ -53,11 +49,11 @@ public interface LPPermissionService {
|
||||
|
||||
LuckPermsPlugin getPlugin();
|
||||
|
||||
ContextManager<Subject, ServerPlayer> getContextManager();
|
||||
ContextManager<Subject, Player> getContextManager();
|
||||
|
||||
SubjectReferenceFactory getReferenceFactory();
|
||||
|
||||
PermissionAndContextService sponge();
|
||||
PermissionService sponge();
|
||||
|
||||
LPSubjectCollection getUserSubjects();
|
||||
|
||||
@@ -73,19 +69,13 @@ public interface LPPermissionService {
|
||||
|
||||
ImmutableMap<String, LPSubjectCollection> getLoadedCollections();
|
||||
|
||||
LPPermissionDescription registerPermissionDescription(String id, Component description, PluginContainer owner);
|
||||
LPPermissionDescription registerPermissionDescription(String id, Text description, PluginContainer owner);
|
||||
|
||||
Optional<LPPermissionDescription> getDescription(String permission);
|
||||
|
||||
ImmutableCollection<LPPermissionDescription> getDescriptions();
|
||||
|
||||
void registerContextCalculator(ContextCalculator calculator);
|
||||
|
||||
ImmutableContextSet getContextsForCause(Cause cause);
|
||||
|
||||
ImmutableContextSet getContextsForCurrentCause();
|
||||
|
||||
void fireUpdateEvent(LPSubjectData subjectData);
|
||||
void registerContextCalculator(ContextCalculator<Subject> calculator);
|
||||
|
||||
void invalidateAllCaches();
|
||||
}
|
||||
+6
-1
@@ -33,6 +33,7 @@ import net.luckperms.api.context.ImmutableContextSet;
|
||||
import net.luckperms.api.query.QueryOptions;
|
||||
import net.luckperms.api.util.Tristate;
|
||||
|
||||
import org.spongepowered.api.command.CommandSource;
|
||||
import org.spongepowered.api.service.permission.Subject;
|
||||
|
||||
import java.util.Optional;
|
||||
@@ -42,7 +43,7 @@ import java.util.Optional;
|
||||
*/
|
||||
public interface LPSubject {
|
||||
|
||||
LPProxiedSubject sponge();
|
||||
ProxiedSubject sponge();
|
||||
|
||||
LPPermissionService getService();
|
||||
|
||||
@@ -58,6 +59,10 @@ public interface LPSubject {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
default Optional<CommandSource> getCommandSource() {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
LPSubjectCollection getParentCollection();
|
||||
|
||||
LPSubjectData getSubjectData();
|
||||
|
||||
+2
-1
@@ -35,6 +35,7 @@ import net.luckperms.api.query.dataorder.DataQueryOrder;
|
||||
import org.spongepowered.api.service.permission.SubjectCollection;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
@@ -70,7 +71,7 @@ public interface LPSubjectCollection {
|
||||
|
||||
CompletableFuture<Boolean> hasRegistered(String identifier);
|
||||
|
||||
CompletableFuture<ImmutableCollection<LPSubject>> loadSubjects(Iterable<String> identifiers);
|
||||
CompletableFuture<ImmutableCollection<LPSubject>> loadSubjects(Set<String> identifiers);
|
||||
|
||||
ImmutableCollection<LPSubject> getLoadedSubjects();
|
||||
|
||||
|
||||
+1
-1
@@ -28,6 +28,6 @@ package me.lucko.luckperms.sponge.service.model;
|
||||
/**
|
||||
* Marks that an object is a proxy implementation for a PermissionService related class.
|
||||
*/
|
||||
public interface LPProxiedServiceObject {
|
||||
public interface ProxiedServiceObject {
|
||||
|
||||
}
|
||||
+1
-1
@@ -33,7 +33,7 @@ import org.spongepowered.api.service.permission.Subject;
|
||||
/**
|
||||
* Marks that an object is a proxied representation of a {@link Subject}.
|
||||
*/
|
||||
public interface LPProxiedSubject extends Subject, LPProxiedServiceObject {
|
||||
public interface ProxiedSubject extends Subject, ProxiedServiceObject {
|
||||
|
||||
@Override
|
||||
@NonNull LPSubjectReference asSubjectReference();
|
||||
+4
-4
@@ -76,12 +76,12 @@ final class CachedSubjectReference implements LPSubjectReference {
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull String collectionIdentifier() {
|
||||
public @NonNull String getCollectionIdentifier() {
|
||||
return this.collectionIdentifier;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NonNull String subjectIdentifier() {
|
||||
public @NonNull String getSubjectIdentifier() {
|
||||
return this.subjectIdentifier;
|
||||
}
|
||||
|
||||
@@ -158,8 +158,8 @@ final class CachedSubjectReference implements LPSubjectReference {
|
||||
if (o == this) return true;
|
||||
if (!(o instanceof LPSubjectReference)) return false;
|
||||
final LPSubjectReference other = (LPSubjectReference) o;
|
||||
return this.collectionIdentifier.equals(other.collectionIdentifier()) &&
|
||||
this.subjectIdentifier.equals(other.subjectIdentifier());
|
||||
return this.collectionIdentifier.equals(other.getCollectionIdentifier()) &&
|
||||
this.subjectIdentifier.equals(other.getSubjectIdentifier());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+16
-8
@@ -30,9 +30,9 @@ import com.google.common.base.Splitter;
|
||||
|
||||
import me.lucko.luckperms.common.util.CaffeineFactory;
|
||||
import me.lucko.luckperms.sponge.service.model.LPPermissionService;
|
||||
import me.lucko.luckperms.sponge.service.model.LPProxiedSubject;
|
||||
import me.lucko.luckperms.sponge.service.model.LPSubject;
|
||||
import me.lucko.luckperms.sponge.service.model.LPSubjectReference;
|
||||
import me.lucko.luckperms.sponge.service.model.ProxiedSubject;
|
||||
|
||||
import org.spongepowered.api.service.permission.Subject;
|
||||
import org.spongepowered.api.service.permission.SubjectReference;
|
||||
@@ -86,11 +86,11 @@ public final class SubjectReferenceFactory {
|
||||
|
||||
public LPSubjectReference obtain(Subject subject) {
|
||||
Objects.requireNonNull(subject, "subject");
|
||||
if (subject instanceof LPProxiedSubject) {
|
||||
return ((LPProxiedSubject) subject).asSubjectReference();
|
||||
if (subject instanceof ProxiedSubject) {
|
||||
return ((ProxiedSubject) subject).asSubjectReference();
|
||||
}
|
||||
|
||||
return obtain(subject.containingCollection().identifier(), subject.identifier());
|
||||
return obtain(subject.getContainingCollection().getIdentifier(), subject.getIdentifier());
|
||||
}
|
||||
|
||||
public LPSubjectReference obtain(SubjectReference reference) {
|
||||
@@ -98,7 +98,7 @@ public final class SubjectReferenceFactory {
|
||||
if (reference instanceof LPSubjectReference) {
|
||||
return (LPSubjectReference) reference;
|
||||
} else {
|
||||
return obtain(reference.collectionIdentifier(), reference.subjectIdentifier());
|
||||
return obtain(reference.getCollectionIdentifier(), reference.getSubjectIdentifier());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,15 +119,23 @@ public final class SubjectReferenceFactory {
|
||||
private SubjectReferenceAttributes(String collectionId, String id) {
|
||||
this.collectionId = collectionId.toLowerCase(Locale.ROOT);
|
||||
this.id = id.toLowerCase(Locale.ROOT);
|
||||
this.hashCode = Objects.hash(this.collectionId, this.id);
|
||||
this.hashCode = calculateHashCode();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (o == this) return true;
|
||||
if (!(o instanceof SubjectReferenceAttributes)) return false;
|
||||
final SubjectReferenceAttributes that = (SubjectReferenceAttributes) o;
|
||||
return this.collectionId.equals(that.collectionId) && this.id.equals(that.id);
|
||||
final SubjectReferenceAttributes other = (SubjectReferenceAttributes) o;
|
||||
return this.collectionId.equals(other.collectionId) && this.id.equals(other.id);
|
||||
}
|
||||
|
||||
private int calculateHashCode() {
|
||||
final int PRIME = 59;
|
||||
int result = 1;
|
||||
result = result * PRIME + this.collectionId.hashCode();
|
||||
result = result * PRIME + this.id.hashCode();
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -29,30 +29,33 @@ import com.google.inject.Inject;
|
||||
|
||||
import me.lucko.luckperms.common.plugin.bootstrap.LuckPermsBootstrap;
|
||||
import me.lucko.luckperms.common.plugin.classpath.ClassPathAppender;
|
||||
import me.lucko.luckperms.common.plugin.logging.Log4jPluginLogger;
|
||||
import me.lucko.luckperms.common.plugin.classpath.ReflectionClassPathAppender;
|
||||
import me.lucko.luckperms.common.plugin.logging.PluginLogger;
|
||||
import me.lucko.luckperms.common.plugin.logging.Slf4jPluginLogger;
|
||||
import me.lucko.luckperms.common.plugin.scheduler.SchedulerAdapter;
|
||||
import me.lucko.luckperms.common.util.MoreFiles;
|
||||
|
||||
import net.luckperms.api.platform.Platform;
|
||||
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.slf4j.Logger;
|
||||
import org.spongepowered.api.Game;
|
||||
import org.spongepowered.api.Platform.Component;
|
||||
import org.spongepowered.api.Platform;
|
||||
import org.spongepowered.api.Server;
|
||||
import org.spongepowered.api.Sponge;
|
||||
import org.spongepowered.api.config.ConfigDir;
|
||||
import org.spongepowered.api.entity.living.player.Player;
|
||||
import org.spongepowered.api.entity.living.player.server.ServerPlayer;
|
||||
import org.spongepowered.api.event.Listener;
|
||||
import org.spongepowered.api.event.Order;
|
||||
import org.spongepowered.api.event.lifecycle.ConstructPluginEvent;
|
||||
import org.spongepowered.api.event.lifecycle.StoppingEngineEvent;
|
||||
import org.spongepowered.api.event.game.state.GamePreInitializationEvent;
|
||||
import org.spongepowered.api.event.game.state.GameStoppingServerEvent;
|
||||
import org.spongepowered.api.plugin.Dependency;
|
||||
import org.spongepowered.api.plugin.Plugin;
|
||||
import org.spongepowered.api.plugin.PluginContainer;
|
||||
import org.spongepowered.api.profile.GameProfile;
|
||||
import org.spongepowered.plugin.PluginContainer;
|
||||
import org.spongepowered.plugin.builtin.jvm.Plugin;
|
||||
import org.spongepowered.plugin.metadata.PluginMetadata;
|
||||
import org.spongepowered.api.scheduler.AsynchronousExecutor;
|
||||
import org.spongepowered.api.scheduler.Scheduler;
|
||||
import org.spongepowered.api.scheduler.SpongeExecutorService;
|
||||
import org.spongepowered.api.scheduler.SynchronousExecutor;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
@@ -66,7 +69,18 @@ import java.util.concurrent.CountDownLatch;
|
||||
/**
|
||||
* Bootstrap plugin for LuckPerms running on Sponge.
|
||||
*/
|
||||
@Plugin("luckperms")
|
||||
@Plugin(
|
||||
id = "luckperms",
|
||||
name = "LuckPerms",
|
||||
version = "@version@",
|
||||
authors = "Luck",
|
||||
description = "A permissions plugin",
|
||||
url = "https://luckperms.net",
|
||||
dependencies = {
|
||||
// explicit dependency on spongeapi with no defined API version
|
||||
@Dependency(id = "spongeapi")
|
||||
}
|
||||
)
|
||||
public class LPSpongeBootstrap implements LuckPermsBootstrap {
|
||||
|
||||
/**
|
||||
@@ -77,7 +91,7 @@ public class LPSpongeBootstrap implements LuckPermsBootstrap {
|
||||
/**
|
||||
* A scheduler adapter for the platform
|
||||
*/
|
||||
private final SpongeSchedulerAdapter schedulerAdapter;
|
||||
private final SchedulerAdapter schedulerAdapter;
|
||||
|
||||
/**
|
||||
* The plugin class path appender
|
||||
@@ -101,27 +115,33 @@ public class LPSpongeBootstrap implements LuckPermsBootstrap {
|
||||
/**
|
||||
* Reference to the central {@link Game} instance in the API
|
||||
*/
|
||||
private final Game game;
|
||||
@Inject
|
||||
private Game game;
|
||||
|
||||
/**
|
||||
* Injected plugin container for the plugin
|
||||
* Reference to the sponge scheduler
|
||||
*/
|
||||
private final PluginContainer pluginContainer;
|
||||
private final Scheduler spongeScheduler;
|
||||
|
||||
/**
|
||||
* Injected configuration directory for the plugin
|
||||
*/
|
||||
private final Path configDirectory;
|
||||
@Inject
|
||||
@ConfigDir(sharedRoot = false)
|
||||
private Path configDirectory;
|
||||
|
||||
/**
|
||||
* Injected plugin container for the plugin
|
||||
*/
|
||||
@Inject
|
||||
private PluginContainer pluginContainer;
|
||||
|
||||
@Inject
|
||||
public LPSpongeBootstrap(Logger logger, Game game, PluginContainer pluginContainer, @ConfigDir(sharedRoot = false) Path configDirectory) {
|
||||
this.logger = new Log4jPluginLogger(logger);
|
||||
this.game = game;
|
||||
this.pluginContainer = pluginContainer;
|
||||
this.configDirectory = configDirectory;
|
||||
|
||||
this.schedulerAdapter = new SpongeSchedulerAdapter(this.game, this.pluginContainer);
|
||||
this.classPathAppender = new SpongeClassPathAppender(this);
|
||||
public LPSpongeBootstrap(Logger logger, @SynchronousExecutor SpongeExecutorService syncExecutor, @AsynchronousExecutor SpongeExecutorService asyncExecutor) {
|
||||
this.logger = new Slf4jPluginLogger(logger);
|
||||
this.spongeScheduler = Sponge.getScheduler();
|
||||
this.schedulerAdapter = new SpongeSchedulerAdapter(this, this.spongeScheduler, syncExecutor, asyncExecutor);
|
||||
this.classPathAppender = new ReflectionClassPathAppender(this);
|
||||
this.plugin = new LPSpongePlugin(this);
|
||||
}
|
||||
|
||||
@@ -133,7 +153,7 @@ public class LPSpongeBootstrap implements LuckPermsBootstrap {
|
||||
}
|
||||
|
||||
@Override
|
||||
public SpongeSchedulerAdapter getScheduler() {
|
||||
public SchedulerAdapter getScheduler() {
|
||||
return this.schedulerAdapter;
|
||||
}
|
||||
|
||||
@@ -143,8 +163,9 @@ public class LPSpongeBootstrap implements LuckPermsBootstrap {
|
||||
}
|
||||
|
||||
// lifecycle
|
||||
|
||||
@Listener(order = Order.FIRST)
|
||||
public void onEnable(ConstructPluginEvent event) {
|
||||
public void onEnable(GamePreInitializationEvent event) {
|
||||
this.startTime = Instant.now();
|
||||
try {
|
||||
this.plugin.load();
|
||||
@@ -159,8 +180,13 @@ public class LPSpongeBootstrap implements LuckPermsBootstrap {
|
||||
}
|
||||
}
|
||||
|
||||
@Listener(order = Order.LATE)
|
||||
public void onLateEnable(GamePreInitializationEvent event) {
|
||||
this.plugin.lateEnable();
|
||||
}
|
||||
|
||||
@Listener
|
||||
public void onDisable(StoppingEngineEvent<Server> event) {
|
||||
public void onDisable(GameStoppingServerEvent event) {
|
||||
this.plugin.disable();
|
||||
}
|
||||
|
||||
@@ -181,22 +207,22 @@ public class LPSpongeBootstrap implements LuckPermsBootstrap {
|
||||
}
|
||||
|
||||
public Optional<Server> getServer() {
|
||||
return this.game.isServerAvailable() ? Optional.of(this.game.server()) : Optional.empty();
|
||||
return this.game.isServerAvailable() ? Optional.of(this.game.getServer()) : Optional.empty();
|
||||
}
|
||||
|
||||
public Scheduler getSpongeScheduler() {
|
||||
return this.spongeScheduler;
|
||||
}
|
||||
|
||||
public PluginContainer getPluginContainer() {
|
||||
return this.pluginContainer;
|
||||
}
|
||||
|
||||
public void registerListeners(Object obj) {
|
||||
this.game.eventManager().registerListeners(this.pluginContainer, obj);
|
||||
}
|
||||
|
||||
// provide information about the plugin
|
||||
|
||||
@Override
|
||||
public String getVersion() {
|
||||
return this.pluginContainer.metadata().version().toString();
|
||||
return "@version@";
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -207,26 +233,25 @@ public class LPSpongeBootstrap implements LuckPermsBootstrap {
|
||||
// provide information about the platform
|
||||
|
||||
@Override
|
||||
public Platform.Type getType() {
|
||||
return Platform.Type.SPONGE;
|
||||
public net.luckperms.api.platform.Platform.Type getType() {
|
||||
return net.luckperms.api.platform.Platform.Type.SPONGE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getServerBrand() {
|
||||
PluginMetadata brandMetadata = this.game.platform().container(Component.IMPLEMENTATION).metadata();
|
||||
return brandMetadata.name().orElseGet(brandMetadata::id);
|
||||
return this.game.getPlatform().getContainer(Platform.Component.IMPLEMENTATION).getName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getServerVersion() {
|
||||
PluginMetadata api = this.game.platform().container(Component.API).metadata();
|
||||
PluginMetadata impl = this.game.platform().container(Component.IMPLEMENTATION).metadata();
|
||||
return api.name().orElse("API") + ": " + api.version() + " - " + impl.name().orElse("Impl") + ": " + impl.version();
|
||||
PluginContainer api = this.game.getPlatform().getContainer(Platform.Component.API);
|
||||
PluginContainer impl = this.game.getPlatform().getContainer(Platform.Component.IMPLEMENTATION);
|
||||
return api.getName() + ": " + api.getVersion().orElse("null") + " - " + impl.getName() + ": " + impl.getVersion().orElse("null");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Path getDataDirectory() {
|
||||
Path dataDirectory = this.game.gameDirectory().toAbsolutePath().resolve("luckperms");
|
||||
Path dataDirectory = this.game.getGameDirectory().toAbsolutePath().resolve("luckperms");
|
||||
try {
|
||||
MoreFiles.createDirectoriesIfNotExists(dataDirectory);
|
||||
} catch (IOException e) {
|
||||
@@ -241,19 +266,14 @@ public class LPSpongeBootstrap implements LuckPermsBootstrap {
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream getResourceStream(String path) {
|
||||
return getClass().getClassLoader().getResourceAsStream(path);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<ServerPlayer> getPlayer(UUID uniqueId) {
|
||||
return getServer().flatMap(s -> s.player(uniqueId));
|
||||
public Optional<Player> getPlayer(UUID uniqueId) {
|
||||
return getServer().flatMap(s -> s.getPlayer(uniqueId));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<UUID> lookupUniqueId(String username) {
|
||||
return getServer().flatMap(server -> server.gameProfileManager().profile(username)
|
||||
.thenApply(p -> Optional.of(p.uniqueId()))
|
||||
return getServer().flatMap(server -> server.getGameProfileManager().get(username)
|
||||
.thenApply(p -> Optional.of(p.getUniqueId()))
|
||||
.exceptionally(x -> Optional.empty())
|
||||
.join()
|
||||
);
|
||||
@@ -261,8 +281,8 @@ public class LPSpongeBootstrap implements LuckPermsBootstrap {
|
||||
|
||||
@Override
|
||||
public Optional<String> lookupUsername(UUID uniqueId) {
|
||||
return getServer().flatMap(server -> server.gameProfileManager().profile(uniqueId)
|
||||
.thenApply(GameProfile::name)
|
||||
return getServer().flatMap(server -> server.getGameProfileManager().get(uniqueId)
|
||||
.thenApply(GameProfile::getName)
|
||||
.exceptionally(x -> Optional.empty())
|
||||
.join()
|
||||
);
|
||||
@@ -270,16 +290,16 @@ public class LPSpongeBootstrap implements LuckPermsBootstrap {
|
||||
|
||||
@Override
|
||||
public int getPlayerCount() {
|
||||
return getServer().map(server -> server.onlinePlayers().size()).orElse(0);
|
||||
return getServer().map(server -> server.getOnlinePlayers().size()).orElse(0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<String> getPlayerList() {
|
||||
return getServer().map(server -> {
|
||||
Collection<ServerPlayer> players = server.onlinePlayers();
|
||||
Collection<Player> players = server.getOnlinePlayers();
|
||||
List<String> list = new ArrayList<>(players.size());
|
||||
for (Player player : players) {
|
||||
list.add(player.name());
|
||||
list.add(player.getName());
|
||||
}
|
||||
return list;
|
||||
}).orElse(Collections.emptyList());
|
||||
@@ -288,10 +308,10 @@ public class LPSpongeBootstrap implements LuckPermsBootstrap {
|
||||
@Override
|
||||
public Collection<UUID> getOnlinePlayers() {
|
||||
return getServer().map(server -> {
|
||||
Collection<ServerPlayer> players = server.onlinePlayers();
|
||||
Collection<Player> players = server.getOnlinePlayers();
|
||||
List<UUID> list = new ArrayList<>(players.size());
|
||||
for (Player player : players) {
|
||||
list.add(player.uniqueId());
|
||||
list.add(player.getUniqueId());
|
||||
}
|
||||
return list;
|
||||
}).orElse(Collections.emptyList());
|
||||
@@ -299,7 +319,7 @@ public class LPSpongeBootstrap implements LuckPermsBootstrap {
|
||||
|
||||
@Override
|
||||
public boolean isPlayerOnline(UUID uniqueId) {
|
||||
return getServer().map(server -> server.player(uniqueId).isPresent()).orElse(false);
|
||||
return getServer().flatMap(server -> server.getPlayer(uniqueId).map(Player::isOnline)).orElse(false);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -27,6 +27,7 @@ package me.lucko.luckperms.sponge;
|
||||
|
||||
import me.lucko.luckperms.common.api.LuckPermsApiProvider;
|
||||
import me.lucko.luckperms.common.calculator.CalculatorFactory;
|
||||
import me.lucko.luckperms.common.command.abstraction.Command;
|
||||
import me.lucko.luckperms.common.command.access.CommandPermission;
|
||||
import me.lucko.luckperms.common.config.ConfigKeys;
|
||||
import me.lucko.luckperms.common.config.generic.adapter.ConfigurationAdapter;
|
||||
@@ -37,42 +38,34 @@ import me.lucko.luckperms.common.messaging.MessagingFactory;
|
||||
import me.lucko.luckperms.common.model.User;
|
||||
import me.lucko.luckperms.common.model.manager.track.StandardTrackManager;
|
||||
import me.lucko.luckperms.common.plugin.AbstractLuckPermsPlugin;
|
||||
import me.lucko.luckperms.common.sender.AbstractSender;
|
||||
import me.lucko.luckperms.common.sender.DummyConsoleSender;
|
||||
import me.lucko.luckperms.common.sender.Sender;
|
||||
import me.lucko.luckperms.common.util.MoreFiles;
|
||||
import me.lucko.luckperms.sponge.calculator.SpongeCalculatorFactory;
|
||||
import me.lucko.luckperms.sponge.commands.SpongeParentCommand;
|
||||
import me.lucko.luckperms.sponge.context.SpongeContextManager;
|
||||
import me.lucko.luckperms.sponge.context.SpongePlayerCalculator;
|
||||
import me.lucko.luckperms.sponge.listeners.SpongeCommandListUpdater;
|
||||
import me.lucko.luckperms.sponge.listeners.SpongeConnectionListener;
|
||||
import me.lucko.luckperms.sponge.listeners.SpongePlatformListener;
|
||||
import me.lucko.luckperms.sponge.messaging.SpongeMessagingFactory;
|
||||
import me.lucko.luckperms.sponge.model.manager.SpongeGroupManager;
|
||||
import me.lucko.luckperms.sponge.model.manager.SpongeUserManager;
|
||||
import me.lucko.luckperms.sponge.service.LuckPermsService;
|
||||
import me.lucko.luckperms.sponge.service.ProxyFactory;
|
||||
import me.lucko.luckperms.sponge.service.model.LPPermissionService;
|
||||
import me.lucko.luckperms.sponge.service.model.LPSubjectCollection;
|
||||
import me.lucko.luckperms.sponge.service.model.ProxiedServiceObject;
|
||||
import me.lucko.luckperms.sponge.service.model.persisted.PersistedCollection;
|
||||
import me.lucko.luckperms.sponge.tasks.ServiceCacheHousekeepingTask;
|
||||
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
|
||||
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
|
||||
import net.luckperms.api.LuckPerms;
|
||||
import net.luckperms.api.query.QueryOptions;
|
||||
|
||||
import org.spongepowered.api.command.Command;
|
||||
import org.spongepowered.api.event.Listener;
|
||||
import org.spongepowered.api.event.lifecycle.ProvideServiceEvent;
|
||||
import org.spongepowered.api.event.lifecycle.RegisterCommandEvent;
|
||||
import org.spongepowered.api.service.context.ContextService;
|
||||
import org.spongepowered.api.service.permission.PermissionDescription;
|
||||
import org.spongepowered.api.service.permission.PermissionService;
|
||||
import org.spongepowered.plugin.PluginContainer;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
@@ -95,6 +88,8 @@ public class LPSpongePlugin extends AbstractLuckPermsPlugin {
|
||||
private SpongeContextManager contextManager;
|
||||
private LuckPermsService service;
|
||||
|
||||
private boolean lateLoad = false;
|
||||
|
||||
public LPSpongePlugin(LPSpongeBootstrap bootstrap) {
|
||||
this.bootstrap = bootstrap;
|
||||
}
|
||||
@@ -112,11 +107,8 @@ public class LPSpongePlugin extends AbstractLuckPermsPlugin {
|
||||
@Override
|
||||
protected Set<Dependency> getGlobalDependencies() {
|
||||
Set<Dependency> dependencies = super.getGlobalDependencies();
|
||||
|
||||
//dependencies.add(Dependency.ADVENTURE_PLATFORM);
|
||||
dependencies.add(Dependency.ADVENTURE_PLATFORM);
|
||||
//dependencies.add(Dependency.ADVENTURE_PLATFORM_SPONGEAPI);
|
||||
dependencies.remove(Dependency.ADVENTURE);
|
||||
|
||||
dependencies.add(Dependency.CONFIGURATE_CORE);
|
||||
dependencies.add(Dependency.CONFIGURATE_HOCON);
|
||||
dependencies.add(Dependency.HOCON_CONFIG);
|
||||
@@ -125,14 +117,14 @@ public class LPSpongePlugin extends AbstractLuckPermsPlugin {
|
||||
|
||||
@Override
|
||||
protected ConfigurationAdapter provideConfigurationAdapter() {
|
||||
return new SpongeConfigAdapter(this, resolveConfig());
|
||||
return new SpongeConfigAdapter(this, resolveConfig("luckperms.conf"));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void registerPlatformListeners() {
|
||||
this.connectionListener = new SpongeConnectionListener(this);
|
||||
this.bootstrap.registerListeners(this.connectionListener);
|
||||
this.bootstrap.registerListeners(new SpongePlatformListener(this));
|
||||
this.bootstrap.getGame().getEventManager().registerListeners(this.bootstrap, this.connectionListener);
|
||||
this.bootstrap.getGame().getEventManager().registerListeners(this.bootstrap, new SpongePlatformListener(this));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -143,22 +135,7 @@ public class LPSpongePlugin extends AbstractLuckPermsPlugin {
|
||||
@Override
|
||||
protected void registerCommands() {
|
||||
this.commandManager = new SpongeCommandExecutor(this);
|
||||
this.bootstrap.registerListeners(new RegisterCommandsListener(this.bootstrap.getPluginContainer(), this.commandManager));
|
||||
}
|
||||
|
||||
public static final class RegisterCommandsListener {
|
||||
private final PluginContainer pluginContainer;
|
||||
private final Command.Raw command;
|
||||
|
||||
RegisterCommandsListener(PluginContainer pluginContainer, Command.Raw command) {
|
||||
this.pluginContainer = pluginContainer;
|
||||
this.command = command;
|
||||
}
|
||||
|
||||
@Listener
|
||||
public void onCommandRegister(RegisterCommandEvent<Command.Raw> event) {
|
||||
event.register(this.pluginContainer, this.command, "luckperms", "lp", "perm", "perms", "permission", "permissions");
|
||||
}
|
||||
this.bootstrap.getGame().getCommandManager().register(this.bootstrap, this.commandManager, "luckperms", "lp", "perm", "perms", "permission", "permissions");
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -177,46 +154,36 @@ public class LPSpongePlugin extends AbstractLuckPermsPlugin {
|
||||
protected void setupContextManager() {
|
||||
this.contextManager = new SpongeContextManager(this);
|
||||
|
||||
SpongePlayerCalculator playerCalculator = new SpongePlayerCalculator(this);
|
||||
this.bootstrap.registerListeners(playerCalculator);
|
||||
SpongePlayerCalculator playerCalculator = new SpongePlayerCalculator(this, getConfiguration().get(ConfigKeys.DISABLED_CONTEXTS));
|
||||
this.bootstrap.getGame().getEventManager().registerListeners(this.bootstrap, playerCalculator);
|
||||
this.contextManager.registerCalculator(playerCalculator);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setupPlatformHooks() {
|
||||
getLogger().info("Registering PermissionService...");
|
||||
this.service = new LuckPermsService(this);
|
||||
|
||||
//PermissionService oldService = this.bootstrap.getGame().getServiceManager().provide(PermissionService.class).orElse(null);
|
||||
//if (oldService != null && !(oldService instanceof ProxiedServiceObject)) {
|
||||
//
|
||||
// // before registering our permission service, copy any existing permission descriptions
|
||||
// Collection<PermissionDescription> permissionDescriptions = oldService.getDescriptions();
|
||||
// for (PermissionDescription description : permissionDescriptions) {
|
||||
// if (description instanceof ProxiedServiceObject) {
|
||||
// continue;
|
||||
// }
|
||||
// ProxyFactory.registerDescription(this.service, description);
|
||||
// }
|
||||
//}
|
||||
PermissionService oldService = this.bootstrap.getGame().getServiceManager().provide(PermissionService.class).orElse(null);
|
||||
if (oldService != null && !(oldService instanceof ProxiedServiceObject)) {
|
||||
|
||||
this.bootstrap.registerListeners(new RegisterServiceListener(this.service));
|
||||
}
|
||||
|
||||
public static final class RegisterServiceListener {
|
||||
private final LuckPermsService service;
|
||||
|
||||
RegisterServiceListener(LuckPermsService service) {
|
||||
this.service = service;
|
||||
// before registering our permission service, copy any existing permission descriptions
|
||||
Collection<PermissionDescription> permissionDescriptions = oldService.getDescriptions();
|
||||
for (PermissionDescription description : permissionDescriptions) {
|
||||
if (description instanceof ProxiedServiceObject) {
|
||||
continue;
|
||||
}
|
||||
ProxyFactory.registerDescription(this.service, description);
|
||||
}
|
||||
}
|
||||
|
||||
@Listener
|
||||
public void onPermissionServiceProvide(ProvideServiceEvent.EngineScoped<PermissionService> event) {
|
||||
event.suggest(this.service::sponge);
|
||||
}
|
||||
|
||||
@Listener
|
||||
public void onContextServiceProvide(ProvideServiceEvent.EngineScoped<ContextService> event) {
|
||||
event.suggest(this.service::sponge);
|
||||
if (this.bootstrap.getGame().getPluginManager().getPlugin("permissionsex").isPresent()) {
|
||||
getLogger().warn("Detected PermissionsEx - assuming it's loaded for migration.");
|
||||
getLogger().warn("Delaying LuckPerms PermissionService registration.");
|
||||
this.lateLoad = true;
|
||||
} else {
|
||||
this.bootstrap.getGame().getServiceManager().setProvider(this.bootstrap, LPPermissionService.class, this.service);
|
||||
this.bootstrap.getGame().getServiceManager().setProvider(this.bootstrap, PermissionService.class, this.service.sponge());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -227,20 +194,7 @@ public class LPSpongePlugin extends AbstractLuckPermsPlugin {
|
||||
|
||||
@Override
|
||||
protected void registerApiOnPlatform(LuckPerms api) {
|
||||
this.bootstrap.registerListeners(new RegisterApiListener(api));
|
||||
}
|
||||
|
||||
public static final class RegisterApiListener {
|
||||
private final LuckPerms api;
|
||||
|
||||
RegisterApiListener(LuckPerms api) {
|
||||
this.api = api;
|
||||
}
|
||||
|
||||
@Listener
|
||||
public void onLuckPermsServiceProvide(ProvideServiceEvent<LuckPerms> event) {
|
||||
event.suggest(() -> this.api);
|
||||
}
|
||||
this.bootstrap.getGame().getServiceManager().setProvider(this.bootstrap, LuckPerms.class, api);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -255,10 +209,13 @@ public class LPSpongePlugin extends AbstractLuckPermsPlugin {
|
||||
for (CommandPermission perm : CommandPermission.values()) {
|
||||
this.service.registerPermissionDescription(perm.getPermission(), null, this.bootstrap.getPluginContainer());
|
||||
}
|
||||
}
|
||||
|
||||
// register sponge command list updater
|
||||
if (getConfiguration().get(ConfigKeys.UPDATE_CLIENT_COMMAND_LIST)) {
|
||||
getApiProvider().getEventBus().subscribe(new SpongeCommandListUpdater(this));
|
||||
public void lateEnable() {
|
||||
if (this.lateLoad) {
|
||||
getLogger().info("Providing late registration of PermissionService...");
|
||||
this.bootstrap.getGame().getServiceManager().setProvider(this.bootstrap, LPPermissionService.class, this.service);
|
||||
this.bootstrap.getGame().getServiceManager().setProvider(this.bootstrap, PermissionService.class, this.service.sponge());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,22 +229,6 @@ public class LPSpongePlugin extends AbstractLuckPermsPlugin {
|
||||
this.service.invalidateAllCaches();
|
||||
}
|
||||
|
||||
private Path resolveConfig() {
|
||||
Path path = this.bootstrap.getConfigDirectory().resolve("luckperms.conf");
|
||||
if (!Files.exists(path)) {
|
||||
try {
|
||||
MoreFiles.createDirectoriesIfNotExists(this.bootstrap.getConfigDirectory());
|
||||
try (InputStream is = getClass().getClassLoader().getResourceAsStream("luckperms.conf")) {
|
||||
Files.copy(is, path);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<QueryOptions> getQueryOptionsForUser(User user) {
|
||||
return this.bootstrap.getPlayer(user.getUniqueId()).map(player -> this.contextManager.getQueryOptions(player));
|
||||
@@ -297,28 +238,26 @@ public class LPSpongePlugin extends AbstractLuckPermsPlugin {
|
||||
public Stream<Sender> getOnlineSenders() {
|
||||
return Stream.concat(
|
||||
Stream.of(getConsoleSender()),
|
||||
this.bootstrap.getServer().map(server -> server.onlinePlayers().stream().map(s -> this.senderFactory.wrap(s))).orElseGet(Stream::empty)
|
||||
this.bootstrap.getServer().map(server -> server.getOnlinePlayers().stream().map(s -> this.senderFactory.wrap(s))).orElseGet(Stream::empty)
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Sender getConsoleSender() {
|
||||
if (this.bootstrap.getGame().isServerAvailable()) {
|
||||
return this.senderFactory.wrap(this.bootstrap.getGame().systemSubject());
|
||||
return this.senderFactory.wrap(this.bootstrap.getGame().getServer().getConsole());
|
||||
} else {
|
||||
return new DummyConsoleSender(this) {
|
||||
@Override
|
||||
public void sendMessage(Component message) {
|
||||
for (Component line : AbstractSender.splitNewlines(TranslationManager.render(message))) {
|
||||
LPSpongePlugin.this.bootstrap.getPluginLogger().info(PlainTextComponentSerializer.plainText().serialize(line));
|
||||
}
|
||||
LPSpongePlugin.this.getLogger().info(LegacyComponentSerializer.legacySection().serialize(TranslationManager.render(message)));
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<me.lucko.luckperms.common.command.abstraction.Command<?>> getExtraCommands() {
|
||||
public List<Command<?>> getExtraCommands() {
|
||||
return Collections.singletonList(new SpongeParentCommand(this));
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 133 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user