Compare commits

...
Author SHA1 Message Date
Luck 5ecbc473e9 Add API methods and command tests for new ActionLog system 2024-06-16 21:11:07 +01:00
Luck 73abf64aa3 Integrate log commands with new log backend method 2024-06-16 20:45:05 +01:00
Luck 3b5a936674 Implement paginated logs for all storage backends 2024-06-16 20:45:05 +01:00
Luck 23575d788a Implement more efficient actionlog reads 2024-06-16 20:45:04 +01:00
Luck 137775a3de Tidy up bulk update SQL generation 2024-06-16 20:45:04 +01:00
Luck d748817351 Update Forge to MC 1.21 2024-06-16 10:45:47 +01:00
Wolfdv1andWolfdv1 f984ebbb46 Update Fabric to MC 1.21 (#3918)
Co-authored-by: Wolfdv1 <Wolfdv1@github.com>
2024-06-16 10:45:09 +01:00
Luck 9805f8b2c4 Bump adventure-platform to 4.3.3 2024-06-02 22:17:12 +01:00
Luckandpowercas_gamer c3802c2a5a Fix Forge plugin msg messenger (#3894)
Co-authored-by: powercas_gamer <cas@mizule.dev>
2024-05-26 14:19:36 +01:00
Ossi Erkkilä b5400f885b Add support for Sponge API 11 (#3896) 2024-05-26 13:58:39 +01:00
bloodmc 5c1ea5633e Update Forge to MC 1.20.6 (#3883) 2024-05-08 23:09:02 +01:00
bloodmc 484b04c17b Add support for Sponge API 9+ (#3885) 2024-05-06 18:20:47 +01:00
Jason Penilla d74a4dcb7e Set mappings namespace to skip remapping on Paper 1.20.5+ (#3881) 2024-04-30 10:31:16 +01:00
Luck 2361ea43ee Update Fabric to MC 1.20.6 2024-04-29 20:05:54 +01:00
Luck f86585c3cc Update Dockerfile to use Java 21 2024-04-25 22:57:03 +01:00
Drex 7cb60f59fe Update Fabric to MC 1.20.5 (#3824) 2024-04-23 21:57:20 +01:00
Luck a43f4a11b0 Update Fabric dependencies 2024-04-17 21:25:15 +01:00
powercas_gamer 1dffd462a5 Fix mongodb secrets being logged (#3850, #3851) 2024-03-15 20:23:32 +00:00
lucko 8c6586f008 Add custom payload message to API (#3840) 2024-03-06 21:12:33 +00:00
Luck 79273a8bcc Add PostNetworkSyncEvent 2024-02-18 22:40:58 +00:00
Gilberto Garcia 7d89c97907 Don't read nodes twice in SqlStorage (#3836) 2024-02-15 20:03:02 +00:00
Emilia Kond 96008f6338 Add modifyTrack method to TrackManager (#3823) 2024-01-23 17:44:20 +00:00
powercas_gamer e6599a2662 Fix MongoDB uri showing in logs if set using system property (#3808) 2024-01-06 11:31:59 +00:00
AoElite 0703b9856f Small performance optimization in BukkitPlatformListener (#3806) 2024-01-06 11:24:44 +00:00
Luck 5f95b386cb Update adventure-platform for MC 1.20.4 support 2024-01-06 11:23:43 +00:00
Luck 754283c053 Fix Fabric command manager mixin (#3791) 2023-12-12 18:57:44 +00:00
Luck 5f87de3569 Upgrade Fabric/Forge to MC 1.20.4 2023-12-11 19:29:39 +00:00
Luck 43f4d490bb Upgrade Fabric to MC 1.20.3 2023-12-06 20:55:25 +00:00
Luck f14798b368 Upgrade gradle version 2023-12-06 20:35:01 +00:00
bloodmc 00ed76cfc0 Update Forge to 1.20.2 (#3787) 2023-12-06 08:27:08 +00:00
Misode f78e2d6c52 Update Minecraft wiki links in config file comments (#3758) 2023-11-06 22:00:47 +00:00
huanmeng_qwq f999f9f234 Fix duplicate UUID delete with Mongo storage (#3777) 2023-11-06 21:57:08 +00:00
Luck 84fce987d5 Change healthcheck details return type 2023-10-22 21:08:45 +01:00
Luck 3707d2f03c Add healthcheck functionality to API 2023-10-22 20:17:37 +01:00
Luck 822c796e1c Update adventure-platform for MC 1.20.2 support 2023-10-02 19:30:17 +01:00
Luck 331a328771 Upgrade Fabric to MC 1.20.2 2023-10-02 19:28:19 +01:00
181 changed files with 5645 additions and 2103 deletions

No files matched your search

+4 -1
View File
@@ -29,7 +29,7 @@ jobs:
- uses: actions/setup-java@v3
with:
distribution: 'temurin'
java-version: '17'
java-version: '21'
- name: Setup Gradle
uses: gradle/gradle-build-action@v2
@@ -86,6 +86,9 @@ jobs:
name: standalone-binary
path: standalone/docker/
- name: Remove version number from jar artifact name
run: mv standalone/docker/LuckPerms-Standalone-*.jar standalone/docker/luckperms-standalone.jar
- name: Set up QEMU
uses: docker/setup-qemu-action@v1
+1 -1
View File
@@ -24,7 +24,7 @@ For more information, see the wiki article on [Why LuckPerms?](https://luckperms
LuckPerms uses Gradle to handle dependencies & building.
#### Requirements
* Java 17 JDK or newer
* Java 21 JDK or newer
* Git
#### Compiling from source
+4 -17
View File
@@ -27,7 +27,7 @@ if (project.hasProperty('sonatypeUsername') && project.hasProperty('sonatypePass
'https://javadoc.io/static/org.jetbrains/annotations/23.0.0/'
)
options.addStringOption('Xdoclint:none', '-quiet')
options.addStringOption('-since', '5.0,5.1,5.2,5.3,5.4')
options.addStringOption('-since', '5.0,5.1,5.2,5.3,5.4,5.5')
if (JavaVersion.current() > JavaVersion.VERSION_1_8) {
options.links.add('https://docs.oracle.com/en/java/javase/11/docs/api/')
@@ -36,19 +36,9 @@ if (project.hasProperty('sonatypeUsername') && project.hasProperty('sonatypePass
}
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier 'javadoc'
from javadoc.destinationDir
}
task sourcesJar(type: Jar) {
classifier 'sources'
from sourceSets.main.allSource
}
artifacts {
archives javadocJar
archives sourcesJar
java {
withJavadocJar()
withSourcesJar()
}
publishing {
@@ -70,8 +60,6 @@ if (project.hasProperty('sonatypeUsername') && project.hasProperty('sonatypePass
artifactId = 'api'
from components.java
artifact sourcesJar
artifact javadocJar
pom {
name = 'LuckPerms API'
@@ -111,7 +99,6 @@ if (project.hasProperty('sonatypeUsername') && project.hasProperty('sonatypePass
signing {
useGpgCmd()
sign configurations.archives
sign publishing.publications.mavenJava
required = true
}
@@ -26,6 +26,7 @@
package net.luckperms.api;
import net.luckperms.api.actionlog.ActionLogger;
import net.luckperms.api.actionlog.filter.ActionFilterFactory;
import net.luckperms.api.context.ContextCalculator;
import net.luckperms.api.context.ContextManager;
import net.luckperms.api.event.EventBus;
@@ -40,6 +41,7 @@ import net.luckperms.api.model.user.User;
import net.luckperms.api.model.user.UserManager;
import net.luckperms.api.node.NodeBuilderRegistry;
import net.luckperms.api.node.matcher.NodeMatcherFactory;
import net.luckperms.api.platform.Health;
import net.luckperms.api.platform.Platform;
import net.luckperms.api.platform.PlayerAdapter;
import net.luckperms.api.platform.PluginMetadata;
@@ -219,6 +221,17 @@ public interface LuckPerms {
*/
@NonNull CompletableFuture<Void> runUpdateTask();
/**
* Executes a health check.
*
* <p>This task checks if the LuckPerms implementation is running and
* whether it has a connection to the database (if applicable).</p>
*
* @return the health status
* @since 5.5
*/
@NonNull Health runHealthCheck();
/**
* Registers a {@link MessengerProvider} for use by the platform.
*
@@ -255,4 +268,14 @@ public interface LuckPerms {
@Internal
@NonNull NodeMatcherFactory getNodeMatcherFactory();
/**
* Gets the {@link ActionFilterFactory}.
*
* @return the action filter factory
* @since 5.5
*/
@Internal
@NonNull
ActionFilterFactory getActionFilterFactory();
}
@@ -28,6 +28,7 @@ package net.luckperms.api.actionlog;
import net.luckperms.api.LuckPermsProvider;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.jetbrains.annotations.ApiStatus.NonExtendable;
import java.time.Instant;
import java.util.Optional;
@@ -35,7 +36,10 @@ import java.util.UUID;
/**
* Represents a logged action.
*
* <p>API users should not implement this interface directly.</p>
*/
@NonExtendable
public interface Action extends Comparable<Action> {
/**
@@ -81,6 +85,7 @@ public interface Action extends Comparable<Action> {
/**
* Represents the source of an action.
*/
@NonExtendable
interface Source {
/**
@@ -102,6 +107,7 @@ public interface Action extends Comparable<Action> {
/**
* Represents the target of an action.
*/
@NonExtendable
interface Target {
/**
@@ -126,7 +132,7 @@ public interface Action extends Comparable<Action> {
@NonNull Type getType();
/**
* Represents the type of a {@link Target}.
* Represents the type of {@link Target}.
*/
enum Type {
USER, GROUP, TRACK
@@ -25,6 +25,7 @@
package net.luckperms.api.actionlog;
import net.luckperms.api.actionlog.filter.ActionFilter;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.jetbrains.annotations.Unmodifiable;
@@ -40,7 +41,11 @@ import java.util.UUID;
* You can add to the log using the {@link ActionLogger}, and then request an updated copy.</p>
*
* <p>All methods are thread safe, and return immutable and thread safe collections.</p>
*
* @deprecated Use {@link ActionLogger#queryActions(ActionFilter)} or
* {@link ActionLogger#queryActions(ActionFilter, int, int)} instead.
*/
@Deprecated
public interface ActionLog {
/**
@@ -25,9 +25,11 @@
package net.luckperms.api.actionlog;
import net.luckperms.api.messaging.MessagingService;
import net.luckperms.api.actionlog.filter.ActionFilter;
import net.luckperms.api.util.Page;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.List;
import java.util.concurrent.CompletableFuture;
/**
@@ -46,43 +48,78 @@ public interface ActionLogger {
* Gets a {@link ActionLog} instance from the plugin storage.
*
* @return a log instance
* @deprecated Use {@link #queryActions(ActionFilter)} or {@link #queryActions(ActionFilter, int, int)} instead. These methods
* are more efficient (they don't load the full action log into memory) and allow for pagination.
*/
@Deprecated
@NonNull CompletableFuture<ActionLog> getLog();
/**
* Submits a log entry to the plugin to be handled.
* Gets all actions from the action log matching the given {@code filter}.
*
* <p>This method submits the log to the storage provider and broadcasts
* it.</p>
* <p>If the filter is {@code null}, all actions will be returned.</p>
*
* <p>It is therefore roughly equivalent to calling
* {@link #submitToStorage(Action)} and {@link #broadcastAction(Action)},
* however, using this method is preferred to making the calls individually.</p>
* <p>Unlike {@link #queryActions(ActionFilter, int, int)}, this method does not implement any pagination and will return
* all entries at once.</p>
*
* <p>If you want to submit a log entry but don't know which method to pick,
* @param filter the filter, optional
* @return the actions
* @since 5.5
*/
@NonNull CompletableFuture<List<Action>> queryActions(@NonNull ActionFilter filter);
/**
* Gets a page of actions from the action log matching the given {@code filter}.
*
* <p>If the filter is {@code null}, all actions will be returned.</p>
*
* @param filter the filter, optional
* @param pageSize the size of the page
* @param pageNumber the page number
* @return the page of actions
* @since 5.5
*/
@NonNull CompletableFuture<Page<Action>> queryActions(@NonNull ActionFilter filter, int pageSize, int pageNumber);
/**
* Submits a logged action to LuckPerms.
*
* <p>This method submits the action to the storage provider to be persisted in the action log.
* It also broadcasts it to administrator players on the current instance and to admins on other
* connected servers if a messaging service is configured.</p>
*
* <p>It is roughly equivalent to calling
* {@link #submitToStorage(Action)} followed by {@link #broadcastAction(Action)},
* however using this method is preferred to making the calls individually.</p>
*
* <p>If you want to submit an action log entry but don't know which method to pick,
* use this one.</p>
*
* @param entry the entry to submit
* @return a future which will complete when the action is done
* @return a future which will complete when the action is submitted
*/
@NonNull CompletableFuture<Void> submit(@NonNull Action entry);
/**
* Submits a log entry to the plugins storage handler.
* Submits a logged action to LuckPerms and persists it in the storage backend.
*
* <p>This method does not broadcast the action or send it through the messaging service.</p>
*
* @param entry the entry to submit
* @return a future which will complete when the action is done
* @return a future which will complete when the action is submitted
*/
@NonNull CompletableFuture<Void> submitToStorage(@NonNull Action entry);
/**
* Submits a log entry to the plugins log broadcasting handler.
* Submits a logged action to LuckPerms and broadcasts it to administrators.
*
* <p>If enabled, this method will also dispatch the log entry via the
* plugins {@link MessagingService}.</p>
* <p>The broadcast is made to administrator players on the current instance
* and to admins on other connected servers if a messaging service is configured.</p>
*
* <p>This method does not save the action to the plugin storage backend.</p>
*
* @param entry the entry to submit
* @return a future which will complete when the action is done
* @return a future which will complete when the action is broadcasted
*/
@NonNull CompletableFuture<Void> broadcastAction(@NonNull Action entry);
@@ -0,0 +1,114 @@
/*
* 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 net.luckperms.api.actionlog.filter;
import net.luckperms.api.LuckPermsProvider;
import net.luckperms.api.actionlog.Action;
import org.jetbrains.annotations.ApiStatus.NonExtendable;
import java.util.UUID;
import java.util.function.Predicate;
/**
* A predicate filter which matches certain {@link Action}s.
*
* <p>API users should not implement this interface directly.</p>
*
* @since 5.5
*/
@NonExtendable
public interface ActionFilter extends Predicate<Action> {
/**
* Gets an {@link ActionFilter} which matches any action.
*
* @return the matcher
*/
static ActionFilter any() {
return LuckPermsProvider.get().getActionFilterFactory().any();
}
/**
* Gets an {@link ActionFilter} which matches actions with a specific source user.
*
* @param uniqueId the source user unique id
* @return the matcher
*/
static ActionFilter source(UUID uniqueId) {
return LuckPermsProvider.get().getActionFilterFactory().source(uniqueId);
}
/**
* Gets an {@link ActionFilter} which matches actions which target a specific user.
*
* @param uniqueId the target user unique id
* @return the matcher
*/
static ActionFilter user(UUID uniqueId) {
return LuckPermsProvider.get().getActionFilterFactory().user(uniqueId);
}
/**
* Gets an {@link ActionFilter} which matches actions which target a specific group.
*
* @param name the target group name
* @return the matcher
*/
static ActionFilter group(String name) {
return LuckPermsProvider.get().getActionFilterFactory().group(name);
}
/**
* Gets an {@link ActionFilter} which matches actions which target a specific track.
*
* @param name the target track name
* @return the matcher
*/
static ActionFilter track(String name) {
return LuckPermsProvider.get().getActionFilterFactory().track(name);
}
/**
* Gets an {@link ActionFilter} which matches actions which contain a specific search query in the source name,
* target name or description.
*
* @param query the search query
* @return the matcher
*/
static ActionFilter search(String query) {
return LuckPermsProvider.get().getActionFilterFactory().search(query);
}
/**
* Tests to see if the given {@link Action} matches the filter.
*
* @param action the action to test
* @return true if the action matched
*/
@Override
boolean test(Action action);
}
@@ -0,0 +1,88 @@
/*
* 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 net.luckperms.api.actionlog.filter;
import org.jetbrains.annotations.ApiStatus.Internal;
import java.util.UUID;
/**
* A factory which creates {@link ActionFilter}s.
*
* @since 5.5
*/
@Internal
public interface ActionFilterFactory {
/**
* Gets an {@link ActionFilter} which matches any action.
*
* @return the matcher
*/
ActionFilter any();
/**
* Gets an {@link ActionFilter} which matches actions with a specific source user.
*
* @param uniqueId the source user unique id
* @return the matcher
*/
ActionFilter source(UUID uniqueId);
/**
* Gets an {@link ActionFilter} which matches actions which target a specific user.
*
* @param uniqueId the target user unique id
* @return the matcher
*/
ActionFilter user(UUID uniqueId);
/**
* Gets an {@link ActionFilter} which matches actions which target a specific group.
*
* @param name the target group name
* @return the matcher
*/
ActionFilter group(String name);
/**
* Gets an {@link ActionFilter} which matches actions which target a specific track.
*
* @param name the target track name
* @return the matcher
*/
ActionFilter track(String name);
/**
* Gets an {@link ActionFilter} which matches actions which contain a specific search query in the source name,
* target name or description.
*
* @param query the search query
* @return the matcher
*/
ActionFilter search(String query);
}
@@ -0,0 +1,29 @@
/*
* 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.
*/
/**
* {@link net.luckperms.api.actionlog.Action} filters.
*/
package net.luckperms.api.actionlog.filter;
@@ -33,7 +33,11 @@ import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.UUID;
/**
* Called when a log entry is received via the MessagingService
* Called when a log entry is received via the MessagingService.
*
* <p>Note: listening to this event is the same as listening to the {@link LogBroadcastEvent}
* and filtering for {@link LogBroadcastEvent#getOrigin() origin} =
* {@link net.luckperms.api.event.log.LogBroadcastEvent.Origin#REMOTE REMOTE}.</p>
*/
public interface LogReceiveEvent extends LuckPermsEvent {
@@ -0,0 +1,59 @@
/*
* 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 net.luckperms.api.event.messaging;
import net.luckperms.api.event.LuckPermsEvent;
import net.luckperms.api.event.util.Param;
import net.luckperms.api.messaging.MessagingService;
import org.checkerframework.checker.nullness.qual.NonNull;
/**
* Called when a custom payload message is received via the {@link MessagingService}.
*
* <p>This event is effectively the 'other end' of
* {@link MessagingService#sendCustomMessage(String, String)}.</p>
*
* @since 5.5
*/
public interface CustomMessageReceiveEvent extends LuckPermsEvent {
/**
* Gets the channel id.
*
* @return the channel id
*/
@Param(0)
@NonNull String getChannelId();
/**
* Gets the custom payload that was sent.
*
* @return the custom payload
*/
@Param(1)
@NonNull String getPayload();
}
@@ -0,0 +1,29 @@
/*
* 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.
*/
/**
* Events relating to the {@link net.luckperms.api.messaging.MessagingService}.
*/
package net.luckperms.api.event.messaging;
@@ -0,0 +1,81 @@
/*
* 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 net.luckperms.api.event.sync;
import net.luckperms.api.event.LuckPermsEvent;
import net.luckperms.api.event.util.Param;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.UUID;
/**
* Called after a network synchronisation task has been completed.
*
* <p>Note: the generic {@link PostSyncEvent} will also be called for {@link SyncType#FULL full syncs}.</p>
*
* @since 5.5
*/
public interface PostNetworkSyncEvent extends LuckPermsEvent {
/**
* Gets the ID of the sync request
*
* @return the id of the sync request
*/
@Param(0)
@NonNull UUID getSyncId();
/**
* Gets the sync type.
*
* @return the sync type
*/
@Param(1)
@NonNull SyncType getType();
/**
* Gets if a sync occurred.
*
* <p>For {@link SyncType} = {@link SyncType#FULL FULL}, this method always returns true.</p>
*
* <p>For {@link SyncType} = {@link SyncType#SPECIFIC_USER SPECIFIC_USER}, this method returns true if the
* user in question was online/loaded in memory at the time, and false otherwise.</p>
*
* @return if a sync occurred
*/
@Param(2)
boolean didSyncOccur();
/**
* Gets the unique id of the specific user that has been synced, if applicable.
*
* @return the unique id of the specific user
*/
@Param(3)
@Nullable UUID getSpecificUserUniqueId();
}
@@ -28,7 +28,10 @@ package net.luckperms.api.event.sync;
import net.luckperms.api.event.LuckPermsEvent;
/**
* Called when an sync task has been completed
* Called after a full synchronisation task has been completed.
*
* <p>Note: this event is also called after synchronisations that were triggered over the network.
* In other words, this event will be called in addition to {@link PostNetworkSyncEvent}.</p>
*/
public interface PostSyncEvent extends LuckPermsEvent {
@@ -29,11 +29,15 @@ import net.luckperms.api.event.LuckPermsEvent;
import net.luckperms.api.event.type.Cancellable;
import net.luckperms.api.event.util.Param;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.UUID;
/**
* Called before a received network sync task runs
* Called after a request for synchronisation has been received via the messaging service,
* but before it has actually been completed.
*
* <p>Note: the generic {@link PreSyncEvent} will also be called for {@link SyncType#FULL full syncs}.</p>
*/
public interface PreNetworkSyncEvent extends LuckPermsEvent, Cancellable {
@@ -45,4 +49,22 @@ public interface PreNetworkSyncEvent extends LuckPermsEvent, Cancellable {
@Param(0)
@NonNull UUID getSyncId();
/**
* Gets the sync type.
*
* @return the sync type
* @since 5.5
*/
@Param(1)
@NonNull SyncType getType();
/**
* Gets the unique id of the specific user that will be synced, if applicable.
*
* @return the unique id of the specific user
* @since 5.5
*/
@Param(2)
@Nullable UUID getSpecificUserUniqueId();
}
@@ -29,7 +29,10 @@ import net.luckperms.api.event.LuckPermsEvent;
import net.luckperms.api.event.type.Cancellable;
/**
* Called before a sync task runs
* Called just before a full synchronisation task runs.
*
* <p>Note: this event is also called before synchronisations that were triggered over the network.
* In other words, this event will be called in addition to {@link PreNetworkSyncEvent}.</p>
*/
public interface PreSyncEvent extends LuckPermsEvent, Cancellable {
@@ -0,0 +1,45 @@
/*
* 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 net.luckperms.api.event.sync;
/**
* Represents the type of synchronisation task.
*
* @since 5.5
*/
public enum SyncType {
/**
* A full sync will be performed - all groups, users and tracks
*/
FULL,
/**
* Only a specific user will be synced
*/
SPECIFIC_USER
}
@@ -26,11 +26,12 @@
package net.luckperms.api.messaging;
import net.luckperms.api.LuckPerms;
import net.luckperms.api.event.messaging.CustomMessageReceiveEvent;
import net.luckperms.api.model.user.User;
import org.checkerframework.checker.nullness.qual.NonNull;
/**
* A means to push changes to other servers using the platforms networking
* A means to send messages to other servers using the platforms networking
*/
public interface MessagingService {
@@ -71,4 +72,44 @@ public interface MessagingService {
*/
void pushUserUpdate(@NonNull User user);
/**
* Uses the messaging service to send a message with a custom payload.
*
* <p>The intended use case of this functionality is to allow plugins/mods
* to send <b>lightweight</b> and <b>permissions-related</b> custom messages
* between instances, piggy-backing on top of the messenger abstraction
* already built into LuckPerms.</p>
*
* <p>It is <b>not</b> intended as a full message broker replacement/abstraction.
* Note that some of the messenger implementations in LuckPerms cannot handle
* a high volume of messages being sent (for example the SQL messenger).
* Additionally, some implementations do not give any guarantees that a message
* will be delivered on time or even at all (for example the plugin message
* messengers).</p>
*
* <p>With all of that in mind, please consider that if you are using this
* functionality to send messages that have nothing to do with LuckPerms or
* permissions, or that require guarantees around delivery reliability, you
* are most likely misusing the API and would be better off building your own
* integration with a message broker.</p>
*
* <p>Whilst there is (currently) no strict validation, it is recommended
* that the channel id should use the same format as Minecraft resource locations /
* namespaced keys. For example, a plugin called "SuperRanks" sending rank-up
* notifications using custom payload messages might use the channel id
* {@code "superranks:notifications"} for this purpose.</p>
*
* <p>The payload can be any valid UTF-8 string.</p>
*
* <p>The message will be delivered asynchronously.</p>
*
* <p>Other LuckPerms instances that receive the message will publish it to API
* consumers using the {@link CustomMessageReceiveEvent}.</p>
*
* @param channelId the channel id
* @param payload the message payload
* @since 5.5
*/
void sendCustomMessage(@NonNull String channelId, @NonNull String payload);
}
@@ -0,0 +1,56 @@
/*
* 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 net.luckperms.api.messenger.message.type;
import net.luckperms.api.messenger.message.Message;
import org.checkerframework.checker.nullness.qual.NonNull;
/**
* Represents a "custom payload" message.
*
* <p>Used by API consumers to send custom messages between servers.</p>
*
* @see net.luckperms.api.messaging.MessagingService#sendCustomMessage(String, String)
* @see net.luckperms.api.event.messaging.CustomMessageReceiveEvent
* @since 5.5
*/
public interface CustomMessage extends Message {
/**
* Gets the channel identifier.
*
* @return the namespace
*/
@NonNull String getChannelId();
/**
* Gets the payload.
*
* @return the payload
*/
@NonNull String getPayload();
}
@@ -0,0 +1,51 @@
/*
* 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 net.luckperms.api.platform;
import java.util.Map;
/**
* Represents the "health" status (healthcheck) of a LuckPerms implementation.
*
* @since 5.5
*/
public interface Health {
/**
* Gets if LuckPerms is healthy.
*
* @return if LuckPerms is healthy
*/
boolean isHealthy();
/**
* Gets extra metadata/details about the healthcheck result.
*
* @return details about the healthcheck status
*/
Map<String, Object> getDetails();
}
@@ -96,6 +96,27 @@ public interface TrackManager {
*/
@NonNull CompletableFuture<Void> deleteTrack(@NonNull Track track);
/**
* Loads (or creates) a track from the plugin's storage provider, applies the given {@code action},
* then saves the track's data back to storage.
*
* <p>This method effectively calls {@link #createAndLoadTrack(String)}, followed by the
* {@code action}, then {@link #saveTrack(Track)}, and returns an encapsulation of the whole
* process as a {@link CompletableFuture}. </p>
*
* @param name the name of the track
* @param action the action to apply to the track
* @return a future to encapsulate the operation
* @since 5.5
*/
default @NonNull CompletableFuture<Void> modifyTrack(@NonNull String name, @NonNull Consumer<? super Track> action) {
/* This default method is overridden in the implementation, and is just here
to demonstrate what this method does in the API sources. */
return createAndLoadTrack(name)
.thenApplyAsync(track -> { action.accept(track); return track; })
.thenCompose(this::saveTrack);
}
/**
* Loads all tracks into memory.
*
@@ -0,0 +1,53 @@
/*
* 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 net.luckperms.api.util;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.List;
/**
* Represents a page of entries.
*
* @since 5.5
*/
public interface Page<T> {
/**
* Gets the entries on this page.
*
* @return the entries
*/
@NonNull List<T> entries();
/**
* Gets the total/overall number of entries (not just the number of entries on this page).
*
* @return the total number of entries
*/
int overallSize();
}
+10
View File
@@ -64,6 +64,16 @@ subprojects {
}
repositories {
// Fix issue with lwjgl-freetype not being found on macOS / ForgeGradle issue
//
// Could not resolve all files for configuration ':_compileJava_1'.
// Could not find lwjgl-freetype-3.3.3-natives-macos-patch.jar (org.lwjgl:lwjgl-freetype:3.3.3).
maven {
url "https://libraries.minecraft.net"
content {
includeModule("org.lwjgl", "lwjgl-freetype")
}
}
mavenCentral()
maven { url 'https://s01.oss.sonatype.org/content/repositories/snapshots/' }
maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' }
+1 -1
View File
@@ -11,7 +11,7 @@ dependencies {
compileOnly project(':common:loader-utils')
compileOnly 'com.destroystokyo.paper:paper-api:1.15.2-R0.1-SNAPSHOT'
compileOnly('net.kyori:adventure-platform-bukkit:4.1.0') {
compileOnly('net.kyori:adventure-platform-bukkit:4.3.3') {
exclude(module: 'adventure-bom')
exclude(module: 'adventure-api')
exclude(module: 'adventure-nbt')
+4
View File
@@ -25,6 +25,10 @@ shadowJar {
from {
project(':bukkit').tasks.shadowJar.archiveFile
}
manifest {
attributes(["paperweight-mappings-namespace": "mojang"])
}
}
artifacts {
@@ -37,11 +37,10 @@ import org.bukkit.event.server.PluginEnableEvent;
import org.bukkit.event.server.RemoteServerCommandEvent;
import org.bukkit.event.server.ServerCommandEvent;
import java.util.Locale;
import java.util.regex.Pattern;
public class BukkitPlatformListener implements Listener {
private static final Pattern OP_COMMAND_PATTERN = Pattern.compile("^/?(\\w+:)?(deop|op)( .*)?$");
private static final Pattern OP_COMMAND_PATTERN = Pattern.compile("^/?(\\w+:)?(deop|op)( .*)?$", Pattern.CASE_INSENSITIVE);
private final LPBukkitPlugin plugin;
@@ -51,17 +50,17 @@ public class BukkitPlatformListener implements Listener {
@EventHandler(ignoreCancelled = true)
public void onPlayerCommand(PlayerCommandPreprocessEvent e) {
handleCommand(e.getPlayer(), e.getMessage().toLowerCase(Locale.ROOT), e);
handleCommand(e.getPlayer(), e.getMessage(), e);
}
@EventHandler(ignoreCancelled = true)
public void onServerCommand(ServerCommandEvent e) {
handleCommand(e.getSender(), e.getCommand().toLowerCase(Locale.ROOT), e);
handleCommand(e.getSender(), e.getCommand(), e);
}
@EventHandler(ignoreCancelled = true)
public void onRemoteServerCommand(RemoteServerCommandEvent e) {
handleCommand(e.getSender(), e.getCommand().toLowerCase(Locale.ROOT), e);
handleCommand(e.getSender(), e.getCommand(), e);
}
private void handleCommand(CommandSender sender, String cmdLine, Cancellable event) {
+1 -1
View File
@@ -717,5 +717,5 @@ update-client-command-list: true
register-command-list-data: true
# If LuckPerms should attempt to resolve Vanilla command target selectors for LP commands.
# See here for more info: https://minecraft.gamepedia.com/Commands#Target_selectors
# See here for more info: https://minecraft.wiki/w/Target_selectors
resolve-command-selectors: false
+1 -1
View File
@@ -7,7 +7,7 @@ dependencies {
compileOnly project(':common:loader-utils')
compileOnly 'net.md-5:bungeecord-api:1.16-R0.4'
compileOnly('net.kyori:adventure-platform-bungeecord:4.1.0') {
compileOnly('net.kyori:adventure-platform-bungeecord:4.3.3') {
exclude(module: 'adventure-bom')
exclude(module: 'adventure-api')
exclude(module: 'adventure-nbt')
+12 -3
View File
@@ -4,7 +4,11 @@ plugins {
}
test {
useJUnitPlatform {}
useJUnitPlatform {
if (!project.hasProperty('dockerTests')) {
excludeTags 'docker'
}
}
}
jacocoTestReport {
@@ -15,9 +19,14 @@ dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.1'
testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.9.1'
testImplementation 'org.junit.jupiter:junit-jupiter-params:5.9.1'
testImplementation 'org.mockito:mockito-core:4.11.0'
testImplementation 'org.mockito:mockito-junit-jupiter:4.11.0'
testImplementation "org.testcontainers:junit-jupiter:1.19.8"
testImplementation 'org.mockito:mockito-core:5.11.0'
testImplementation 'org.mockito:mockito-junit-jupiter:5.11.0'
testImplementation 'com.h2database:h2:2.1.214'
testImplementation 'org.mongodb:mongodb-driver-legacy:4.5.0'
testImplementation 'org.spongepowered:configurate-yaml:3.7.2'
testImplementation 'org.spongepowered:configurate-hocon:3.7.2'
testImplementation 'me.lucko.configurate:configurate-toml:3.7'
api project(':api')
api 'org.checkerframework:checker-qual:3.12.0'
@@ -1,108 +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.actionlog;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;
import me.lucko.luckperms.common.util.ImmutableCollectors;
import net.luckperms.api.actionlog.Action;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;
import java.util.UUID;
public class Log {
private static final Log EMPTY = new Log(ImmutableList.of());
public static Builder builder() {
return new Builder();
}
public static Log empty() {
return EMPTY;
}
private final SortedSet<LoggedAction> content;
Log(List<LoggedAction> content) {
this.content = ImmutableSortedSet.copyOf(content);
}
public SortedSet<LoggedAction> getContent() {
return this.content;
}
public SortedSet<LoggedAction> getContent(UUID actor) {
return this.content.stream()
.filter(e -> e.getSource().getUniqueId().equals(actor))
.collect(ImmutableCollectors.toSortedSet());
}
public SortedSet<LoggedAction> getUserHistory(UUID uniqueId) {
return this.content.stream()
.filter(e -> e.getTarget().getType() == Action.Target.Type.USER)
.filter(e -> e.getTarget().getUniqueId().isPresent() && e.getTarget().getUniqueId().get().equals(uniqueId))
.collect(ImmutableCollectors.toSortedSet());
}
public SortedSet<LoggedAction> getGroupHistory(String name) {
return this.content.stream()
.filter(e -> e.getTarget().getType() == Action.Target.Type.GROUP)
.filter(e -> e.getTarget().getName().equals(name))
.collect(ImmutableCollectors.toSortedSet());
}
public SortedSet<LoggedAction> getTrackHistory(String name) {
return this.content.stream()
.filter(e -> e.getTarget().getType() == Action.Target.Type.TRACK)
.filter(e -> e.getTarget().getName().equals(name))
.collect(ImmutableCollectors.toSortedSet());
}
public SortedSet<LoggedAction> getSearch(String query) {
return this.content.stream()
.filter(e -> e.matchesSearch(query))
.collect(ImmutableCollectors.toSortedSet());
}
public static class Builder {
private final List<LoggedAction> content = new ArrayList<>();
public Builder add(LoggedAction e) {
this.content.add(e);
return this;
}
public Log build() {
if (this.content.isEmpty()) {
return EMPTY;
}
return new Log(this.content);
}
}
}
@@ -29,12 +29,14 @@ import me.lucko.luckperms.common.command.access.CommandPermission;
import me.lucko.luckperms.common.commands.log.LogNotify;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.locale.Message;
import me.lucko.luckperms.common.messaging.InternalMessagingService;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.sender.Sender;
import net.luckperms.api.event.log.LogBroadcastEvent;
import net.luckperms.api.event.log.LogNotifyEvent;
import java.util.Collection;
import java.util.concurrent.CompletableFuture;
import java.util.regex.Pattern;
public class LogDispatcher {
@@ -64,7 +66,12 @@ public class LogDispatcher {
return !this.plugin.getEventDispatcher().dispatchLogBroadcast(cancelled, entry, origin);
}
private void broadcast(LoggedAction entry, LogNotifyEvent.Origin origin, Sender sender) {
// broadcast the entry to online players
private void broadcast(LoggedAction entry, LogBroadcastEvent.Origin broadcastOrigin, LogNotifyEvent.Origin origin, Sender sender) {
if (!shouldBroadcast(entry, broadcastOrigin)) {
return;
}
this.plugin.getOnlineSenders()
.filter(CommandPermission.LOG_NOTIFY::isAuthorized)
.filter(s -> {
@@ -74,41 +81,46 @@ public class LogDispatcher {
.forEach(s -> Message.LOG.send(s, entry));
}
public void dispatch(LoggedAction entry, Sender sender) {
// log the entry to storage
public CompletableFuture<Void> logToStorage(LoggedAction entry) {
if (!this.plugin.getEventDispatcher().dispatchLogPublish(false, entry)) {
this.plugin.getStorage().logAction(entry);
return this.plugin.getStorage().logAction(entry);
} else {
return CompletableFuture.completedFuture(null);
}
}
this.plugin.getMessagingService().ifPresent(service -> service.pushLog(entry));
if (shouldBroadcast(entry, LogBroadcastEvent.Origin.LOCAL)) {
broadcast(entry, LogNotifyEvent.Origin.LOCAL, sender);
// log the entry to messaging
public CompletableFuture<Void> logToMessaging(LoggedAction entry) {
InternalMessagingService messagingService = this.plugin.getMessagingService().orElse(null);
if (messagingService != null) {
return messagingService.pushLog(entry);
} else {
return CompletableFuture.completedFuture(null);
}
}
// log the entry to storage and messaging, and broadcast it to online players
private CompletableFuture<Void> dispatch(LoggedAction entry, Sender sender, LogBroadcastEvent.Origin broadcastOrigin, LogNotifyEvent.Origin origin) {
CompletableFuture<Void> storageFuture = logToStorage(entry);
CompletableFuture<Void> messagingFuture = logToMessaging(entry);
broadcast(entry, broadcastOrigin, origin, sender);
return CompletableFuture.allOf(storageFuture, messagingFuture);
}
public CompletableFuture<Void> dispatch(LoggedAction entry, Sender sender) {
return dispatch(entry, sender, LogBroadcastEvent.Origin.LOCAL, LogNotifyEvent.Origin.LOCAL);
}
public CompletableFuture<Void> dispatchFromApi(LoggedAction entry) {
return dispatch(entry, null, LogBroadcastEvent.Origin.LOCAL_API, LogNotifyEvent.Origin.LOCAL_API);
}
public void broadcastFromApi(LoggedAction entry) {
this.plugin.getMessagingService().ifPresent(extendedMessagingService -> extendedMessagingService.pushLog(entry));
if (shouldBroadcast(entry, LogBroadcastEvent.Origin.LOCAL_API)) {
broadcast(entry, LogNotifyEvent.Origin.LOCAL_API, null);
}
broadcast(entry, LogBroadcastEvent.Origin.LOCAL_API, LogNotifyEvent.Origin.LOCAL_API, null);
}
public void dispatchFromApi(LoggedAction entry) {
if (!this.plugin.getEventDispatcher().dispatchLogPublish(false, entry)) {
try {
this.plugin.getStorage().logAction(entry).get();
} catch (Exception e) {
this.plugin.getLogger().warn("Error whilst storing action", e);
}
}
broadcastFromApi(entry);
}
public void dispatchFromRemote(LoggedAction entry) {
if (shouldBroadcast(entry, LogBroadcastEvent.Origin.REMOTE)) {
broadcast(entry, LogNotifyEvent.Origin.REMOTE, null);
}
public void broadcastFromRemote(LoggedAction entry) {
broadcast(entry, LogBroadcastEvent.Origin.REMOTE, LogNotifyEvent.Origin.REMOTE, null);
}
}
@@ -23,54 +23,50 @@
* SOFTWARE.
*/
package me.lucko.luckperms.common.util;
package me.lucko.luckperms.common.actionlog;
import com.google.common.collect.ImmutableList;
import me.lucko.luckperms.common.filter.PageParameters;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
/**
* A simple pagination utility
*
* @param <T> the element type
*/
public class Paginated<T> {
private final List<T> content;
public Paginated(Collection<T> content) {
this.content = ImmutableList.copyOf(content);
public class LogPage {
public static LogPage of(List<LoggedAction> content, @Nullable PageParameters params, int totalEntries) {
return new LogPage(content, params, totalEntries);
}
public List<T> getContent() {
private final List<LoggedAction> content;
private final @Nullable PageParameters params;
private final int totalEntries;
LogPage(List<LoggedAction> content, @Nullable PageParameters params, int totalEntries) {
this.content = ImmutableList.copyOf(content);
this.params = params;
this.totalEntries = totalEntries;
}
public List<LoggedAction> getContent() {
return this.content;
}
public int getMaxPages(int entriesPerPage) {
return (int) Math.ceil((double) this.content.size() / (double) entriesPerPage);
public List<Entry<LoggedAction>> getNumberedContent() {
int startIndex = this.params != null
? this.params.pageSize() * (this.params.pageNumber() - 1)
: 0;
List<Entry<LoggedAction>> numberedContent = new ArrayList<>();
for (int i = 0; i < this.content.size(); i++) {
int index = startIndex + i + 1;
numberedContent.add(new Entry<>(index, this.content.get(i)));
}
return numberedContent;
}
public List<Entry<T>> getPage(int pageNo, int pageSize) {
if (pageNo < 1) {
throw new IllegalArgumentException("pageNo cannot be less than 1: " + pageNo);
}
int first = (pageNo - 1) * pageSize;
if (this.content.size() <= first) {
throw new IllegalStateException("Content does not contain that many elements. (requested page: " + pageNo +
", page size: " + pageSize + ", page first index: " + first + ", content size: " + this.content.size() + ")");
}
int last = first + pageSize - 1;
List<Entry<T>> out = new ArrayList<>(pageSize);
for (int i = first; i <= last && i < this.content.size(); i++) {
out.add(new Entry<>(i + 1, this.content.get(i)));
}
return out;
public int getTotalEntries() {
return this.totalEntries;
}
public static final class Entry<T> {
@@ -26,6 +26,7 @@
package me.lucko.luckperms.common.actionlog;
import com.google.common.base.Strings;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.model.Group;
import me.lucko.luckperms.common.model.HolderType;
import me.lucko.luckperms.common.model.PermissionHolder;
@@ -44,10 +45,10 @@ import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
/**
* An implementation of {@link Action} and {@link Action.Builder},
@@ -123,15 +124,11 @@ public class LoggedAction implements Action {
return ActionComparator.INSTANCE.compare(this, other);
}
public boolean matchesSearch(String query) {
query = Objects.requireNonNull(query, "query").toLowerCase(Locale.ROOT);
return this.source.name.toLowerCase(Locale.ROOT).contains(query) ||
this.target.name.toLowerCase(Locale.ROOT).contains(query) ||
this.description.toLowerCase(Locale.ROOT).contains(query);
}
public void submit(LuckPermsPlugin plugin, Sender sender) {
plugin.getLogDispatcher().dispatch(this, sender);
CompletableFuture<Void> future = plugin.getLogDispatcher().dispatch(this, sender);
if (plugin.getConfiguration().get(ConfigKeys.LOG_SYNCHRONOUSLY_IN_COMMANDS)) {
future.join();
}
}
@Override
@@ -393,14 +390,14 @@ public class LoggedAction implements Action {
}
}
public static char getTypeCharacter(Target.Type type) {
public static String getTypeString(Target.Type type) {
switch (type) {
case USER:
return 'U';
return "U";
case GROUP:
return 'G';
return "G";
case TRACK:
return 'T';
return "T";
default:
throw new AssertionError();
}
@@ -0,0 +1,60 @@
/*
* 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.actionlog.filter;
import me.lucko.luckperms.common.filter.FilterField;
import net.luckperms.api.actionlog.Action;
import java.util.UUID;
public final class ActionFields {
public static final FilterField<Action, UUID> SOURCE_UNIQUE_ID = FilterField.named(
"SOURCE_UNIQUE_ID",
action -> action.getSource().getUniqueId()
);
public static final FilterField<Action, String> SOURCE_NAME = FilterField.named(
"SOURCE_NAME",
action -> action.getSource().getName()
);
public static final FilterField<Action, Action.Target.Type> TARGET_TYPE = FilterField.named(
"TARGET_TYPE",
action -> action.getTarget().getType()
);
public static final FilterField<Action, UUID> TARGET_UNIQUE_ID = FilterField.named(
"TARGET_UNIQUE_ID",
action -> action.getTarget().getUniqueId().orElse(null)
);
public static final FilterField<Action, String> TARGET_NAME = FilterField.named(
"TARGET_NAME",
action -> action.getTarget().getName()
);
public static final FilterField<Action, String> DESCRIPTION = FilterField.named(
"DESCRIPTION",
action -> action.getDescription()
);
}
@@ -0,0 +1,70 @@
/*
* 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.actionlog.filter;
import me.lucko.luckperms.common.filter.FilterField;
import me.lucko.luckperms.common.filter.mongo.FilterMongoBuilder;
import net.luckperms.api.actionlog.Action;
import java.util.UUID;
public final class ActionFilterMongoBuilder extends FilterMongoBuilder<Action> {
public static final ActionFilterMongoBuilder INSTANCE = new ActionFilterMongoBuilder();
private ActionFilterMongoBuilder() {
}
@Override
public String mapFieldName(FilterField<Action, ?> field) {
if (field == ActionFields.SOURCE_UNIQUE_ID) {
return "source.uniqueId";
} else if (field == ActionFields.SOURCE_NAME) {
return "source.name";
} else if (field == ActionFields.TARGET_TYPE) {
return "target.type";
} else if (field == ActionFields.TARGET_UNIQUE_ID) {
return "target.uniqueId";
} else if (field == ActionFields.TARGET_NAME) {
return "target.name";
} else if (field == ActionFields.DESCRIPTION) {
return "description";
}
throw new AssertionError(field);
}
@Override
public Object mapConstraintValue(Object value) {
if (value instanceof String | value instanceof UUID) {
return value;
} else if (value instanceof Action.Target.Type) {
return ((Action.Target.Type) value).name();
} else {
throw new IllegalArgumentException("Don't know how to map value with type: " + value.getClass().getName());
}
}
}
@@ -0,0 +1,69 @@
/*
* 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.actionlog.filter;
import me.lucko.luckperms.common.actionlog.LoggedAction;
import me.lucko.luckperms.common.filter.FilterField;
import me.lucko.luckperms.common.filter.sql.FilterSqlBuilder;
import net.luckperms.api.actionlog.Action;
import java.util.UUID;
public class ActionFilterSqlBuilder extends FilterSqlBuilder<Action> {
@Override
public void visitFieldName(FilterField<Action, ?> field) {
if (field == ActionFields.SOURCE_UNIQUE_ID) {
this.builder.append("actor_uuid");
} else if (field == ActionFields.SOURCE_NAME) {
this.builder.append("actor_name");
} else if (field == ActionFields.TARGET_TYPE) {
this.builder.append("type");
} else if (field == ActionFields.TARGET_UNIQUE_ID) {
this.builder.append("acted_uuid");
} else if (field == ActionFields.TARGET_NAME) {
this.builder.append("acted_name");
} else if (field == ActionFields.DESCRIPTION) {
this.builder.append("action");
} else {
throw new AssertionError(field);
}
}
@Override
public void visitConstraintValue(Object value) {
if (value instanceof String) {
this.builder.variable(((String) value));
} else if (value instanceof UUID) {
this.builder.variable(value.toString());
} else if (value instanceof Action.Target.Type) {
this.builder.variable(LoggedAction.getTypeString((Action.Target.Type) value));
} else {
throw new IllegalArgumentException("Don't know how to write value with type: " + value.getClass().getName());
}
}
}
@@ -0,0 +1,110 @@
/*
* 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.actionlog.filter;
import me.lucko.luckperms.common.filter.Comparison;
import me.lucko.luckperms.common.filter.ConstraintFactory;
import me.lucko.luckperms.common.filter.FilterList;
import net.luckperms.api.actionlog.Action;
import net.luckperms.api.actionlog.Action.Target;
import java.util.UUID;
import java.util.function.Predicate;
import java.util.regex.Pattern;
public final class ActionFilters {
private ActionFilters() {}
// all actions
public static FilterList<Action> all() {
return FilterList.empty();
}
// all actions performed by a given source (actor)
public static FilterList<Action> source(UUID uniqueId) {
return FilterList.and(
ActionFields.SOURCE_UNIQUE_ID.isEqualTo(uniqueId, ConstraintFactory.UUIDS)
);
}
// all actions affecting a given user
public static FilterList<Action> user(UUID uniqueId) {
return FilterList.and(
ActionFields.TARGET_TYPE.isEqualTo(Target.Type.USER, TARGET_TYPE_CONSTRAINT_FACTORY),
ActionFields.TARGET_UNIQUE_ID.isEqualTo(uniqueId, ConstraintFactory.UUIDS)
);
}
// all actions affecting a given group
public static FilterList<Action> group(String name) {
return FilterList.and(
ActionFields.TARGET_TYPE.isEqualTo(Target.Type.GROUP, TARGET_TYPE_CONSTRAINT_FACTORY),
ActionFields.TARGET_NAME.isEqualTo(name, ConstraintFactory.STRINGS)
);
}
// all actions affecting a given track
public static FilterList<Action> track(String name) {
return FilterList.and(
ActionFields.TARGET_TYPE.isEqualTo(Target.Type.TRACK, TARGET_TYPE_CONSTRAINT_FACTORY),
ActionFields.TARGET_NAME.isEqualTo(name, ConstraintFactory.STRINGS)
);
}
// all actions matching the given search query
public static FilterList<Action> search(String query) {
return FilterList.or(
ActionFields.SOURCE_NAME.isSimilarTo("%" + query + "%", ConstraintFactory.STRINGS),
ActionFields.TARGET_NAME.isSimilarTo("%" + query + "%", ConstraintFactory.STRINGS),
ActionFields.DESCRIPTION.isSimilarTo("%" + query + "%", ConstraintFactory.STRINGS)
);
}
private static final ConstraintFactory<Target.Type> TARGET_TYPE_CONSTRAINT_FACTORY = new ConstraintFactory<Target.Type>() {
@Override
public Predicate<Target.Type> equal(Target.Type value) {
return value::equals;
}
@Override
public Predicate<Target.Type> notEqual(Target.Type value) {
return string -> !value.equals(string);
}
@Override
public Predicate<Target.Type> similar(Target.Type value) {
Pattern pattern = Comparison.compilePatternForLikeSyntax(value.toString());
return type -> pattern.matcher(type.toString()).matches();
}
@Override
public Predicate<Target.Type> notSimilar(Target.Type value) {
Pattern pattern = Comparison.compilePatternForLikeSyntax(value.toString());
return type -> !pattern.matcher(type.toString()).matches();
}
};
}
@@ -25,6 +25,7 @@
package me.lucko.luckperms.common.api;
import me.lucko.luckperms.common.api.implementation.ApiActionFilterFactory;
import me.lucko.luckperms.common.api.implementation.ApiActionLogger;
import me.lucko.luckperms.common.api.implementation.ApiContextManager;
import me.lucko.luckperms.common.api.implementation.ApiGroupManager;
@@ -47,6 +48,7 @@ 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.actionlog.filter.ActionFilterFactory;
import net.luckperms.api.context.ContextManager;
import net.luckperms.api.messaging.MessagingService;
import net.luckperms.api.messenger.MessengerProvider;
@@ -55,6 +57,7 @@ import net.luckperms.api.model.group.GroupManager;
import net.luckperms.api.model.user.UserManager;
import net.luckperms.api.node.NodeBuilderRegistry;
import net.luckperms.api.node.matcher.NodeMatcherFactory;
import net.luckperms.api.platform.Health;
import net.luckperms.api.platform.Platform;
import net.luckperms.api.platform.PlayerAdapter;
import net.luckperms.api.platform.PluginMetadata;
@@ -172,6 +175,11 @@ public class LuckPermsApiProvider implements LuckPerms {
return this.plugin.getSyncTaskBuffer().request();
}
@Override
public @NonNull Health runHealthCheck() {
return this.plugin.runHealthCheck();
}
@Override
public @NonNull AbstractEventBus<?> getEventBus() {
return this.plugin.getEventDispatcher().getEventBus();
@@ -219,4 +227,8 @@ public class LuckPermsApiProvider implements LuckPerms {
return ApiNodeMatcherFactory.INSTANCE;
}
@Override
public @NonNull ActionFilterFactory getActionFilterFactory() {
return ApiActionFilterFactory.INSTANCE;
}
}
@@ -0,0 +1,47 @@
/*
* 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.api.implementation;
import me.lucko.luckperms.common.filter.FilterList;
import net.luckperms.api.actionlog.Action;
import net.luckperms.api.actionlog.filter.ActionFilter;
public class ApiActionFilter implements ActionFilter {
private final FilterList<Action> filter;
public ApiActionFilter(FilterList<Action> filter) {
this.filter = filter;
}
@Override
public boolean test(Action action) {
return this.filter.evaluate(action);
}
public FilterList<Action> getFilter() {
return this.filter;
}
}
@@ -0,0 +1,77 @@
/*
* 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.api.implementation;
import me.lucko.luckperms.common.actionlog.filter.ActionFilters;
import net.luckperms.api.actionlog.filter.ActionFilter;
import net.luckperms.api.actionlog.filter.ActionFilterFactory;
import java.util.Objects;
import java.util.UUID;
public final class ApiActionFilterFactory implements ActionFilterFactory {
public static final ApiActionFilterFactory INSTANCE = new ApiActionFilterFactory();
private ApiActionFilterFactory() {
}
@Override
public ActionFilter any() {
return new ApiActionFilter(ActionFilters.all());
}
@Override
public ActionFilter source(UUID uniqueId) {
Objects.requireNonNull(uniqueId, "uniqueId");
return new ApiActionFilter(ActionFilters.source(uniqueId));
}
@Override
public ActionFilter user(UUID uniqueId) {
Objects.requireNonNull(uniqueId, "uniqueId");
return new ApiActionFilter(ActionFilters.user(uniqueId));
}
@Override
public ActionFilter group(String name) {
Objects.requireNonNull(name, "name");
return new ApiActionFilter(ActionFilters.group(name));
}
@Override
public ActionFilter track(String name) {
Objects.requireNonNull(name, "name");
return new ApiActionFilter(ActionFilters.track(name));
}
@Override
public ActionFilter search(String query) {
Objects.requireNonNull(query, "query");
return new ApiActionFilter(ActionFilters.search(query));
}
}
@@ -25,50 +25,63 @@
package me.lucko.luckperms.common.api.implementation;
import me.lucko.luckperms.common.actionlog.Log;
import me.lucko.luckperms.common.api.ApiUtils;
import com.google.common.collect.ImmutableSortedSet;
import me.lucko.luckperms.common.actionlog.LoggedAction;
import me.lucko.luckperms.common.util.ImmutableCollectors;
import net.luckperms.api.actionlog.Action;
import net.luckperms.api.actionlog.ActionLog;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.List;
import java.util.Objects;
import java.util.SortedSet;
import java.util.UUID;
@SuppressWarnings({"unchecked", "rawtypes"})
@Deprecated
public class ApiActionLog implements ActionLog {
private final Log handle;
private final SortedSet<Action> content;
public ApiActionLog(Log handle) {
this.handle = handle;
public ApiActionLog(List<LoggedAction> content) {
this.content = ImmutableSortedSet.copyOf(content);
}
@Override
public @NonNull SortedSet<Action> getContent() {
return (SortedSet) this.handle.getContent();
return this.content;
}
@Override
public @NonNull SortedSet<Action> getContent(@NonNull UUID actor) {
Objects.requireNonNull(actor, "actor");
return (SortedSet) this.handle.getContent(actor);
return this.content.stream()
.filter(e -> e.getSource().getUniqueId().equals(actor))
.collect(ImmutableCollectors.toSortedSet());
}
@Override
public @NonNull SortedSet<Action> getUserHistory(@NonNull UUID uniqueId) {
Objects.requireNonNull(uniqueId, "uuid");
return (SortedSet) this.handle.getUserHistory(uniqueId);
return this.content.stream()
.filter(e -> e.getTarget().getType() == Action.Target.Type.USER)
.filter(e -> e.getTarget().getUniqueId().isPresent() && e.getTarget().getUniqueId().get().equals(uniqueId))
.collect(ImmutableCollectors.toSortedSet());
}
@Override
public @NonNull SortedSet<Action> getGroupHistory(@NonNull String name) {
Objects.requireNonNull(name, "name");
return (SortedSet) this.handle.getGroupHistory(ApiUtils.checkName(name));
return this.content.stream()
.filter(e -> e.getTarget().getType() == Action.Target.Type.GROUP)
.filter(e -> e.getTarget().getName().equals(name))
.collect(ImmutableCollectors.toSortedSet());
}
@Override
public @NonNull SortedSet<Action> getTrackHistory(@NonNull String name) {
Objects.requireNonNull(name, "name");
return (SortedSet) this.handle.getTrackHistory(ApiUtils.checkName(name));
return this.content.stream()
.filter(e -> e.getTarget().getType() == Action.Target.Type.TRACK)
.filter(e -> e.getTarget().getName().equals(name))
.collect(ImmutableCollectors.toSortedSet());
}
}
@@ -25,13 +25,22 @@
package me.lucko.luckperms.common.api.implementation;
import me.lucko.luckperms.common.actionlog.LogDispatcher;
import me.lucko.luckperms.common.actionlog.LogPage;
import me.lucko.luckperms.common.actionlog.LoggedAction;
import me.lucko.luckperms.common.actionlog.filter.ActionFilters;
import me.lucko.luckperms.common.filter.FilterList;
import me.lucko.luckperms.common.filter.PageParameters;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import net.luckperms.api.actionlog.Action;
import net.luckperms.api.actionlog.ActionLog;
import net.luckperms.api.actionlog.ActionLogger;
import net.luckperms.api.actionlog.filter.ActionFilter;
import net.luckperms.api.util.Page;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
public class ApiActionLogger implements ActionLogger {
@@ -47,22 +56,66 @@ public class ApiActionLogger implements ActionLogger {
}
@Override
@Deprecated
public @NonNull CompletableFuture<ActionLog> getLog() {
return this.plugin.getStorage().getLog().thenApply(ApiActionLog::new);
return this.plugin.getStorage().getLogPage(ActionFilters.all(), null)
.thenApply(result -> new ApiActionLog(result.getContent()));
}
@Override
public @NonNull CompletableFuture<List<Action>> queryActions(@NonNull ActionFilter filter) {
return this.plugin.getStorage().getLogPage(getFilterList(filter), null).thenApply(ActionPage::new).thenApply(Page::entries);
}
@Override
public @NonNull CompletableFuture<Page<Action>> queryActions(@NonNull ActionFilter filter, int pageSize, int pageNumber) {
return this.plugin.getStorage().getLogPage(getFilterList(filter), new PageParameters(pageSize, pageNumber)).thenApply(ActionPage::new);
}
@Override
public @NonNull CompletableFuture<Void> submit(@NonNull Action entry) {
return CompletableFuture.runAsync(() -> this.plugin.getLogDispatcher().dispatchFromApi((LoggedAction) entry), this.plugin.getBootstrap().getScheduler().async());
return this.plugin.getLogDispatcher().dispatchFromApi((LoggedAction) entry);
}
@Override
public @NonNull CompletableFuture<Void> submitToStorage(@NonNull Action entry) {
return this.plugin.getStorage().logAction(entry);
return this.plugin.getLogDispatcher().logToStorage((LoggedAction) entry);
}
@Override
public @NonNull CompletableFuture<Void> broadcastAction(@NonNull Action entry) {
return CompletableFuture.runAsync(() -> this.plugin.getLogDispatcher().broadcastFromApi((LoggedAction) entry), this.plugin.getBootstrap().getScheduler().async());
LogDispatcher dispatcher = this.plugin.getLogDispatcher();
CompletableFuture<Void> messagingFuture = dispatcher.logToStorage(((LoggedAction) entry));
dispatcher.broadcastFromApi(((LoggedAction) entry));
return messagingFuture;
}
private static FilterList<Action> getFilterList(ActionFilter filter) {
Objects.requireNonNull(filter, "filter");
if (filter instanceof ApiActionFilter) {
return ((ApiActionFilter) filter).getFilter();
} else {
throw new IllegalArgumentException("Unknown filter type: " + filter.getClass());
}
}
private static final class ActionPage implements Page<Action> {
private final LogPage page;
private ActionPage(LogPage page) {
this.page = page;
}
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public @NonNull List<Action> entries() {
return (List) this.page.getContent();
}
@Override
public int overallSize() {
return this.page.getTotalEntries();
}
}
}
@@ -54,4 +54,11 @@ public class ApiMessagingService implements MessagingService {
Objects.requireNonNull(user, "user");
this.handle.pushUserUpdate(ApiUser.cast(user));
}
@Override
public void sendCustomMessage(@NonNull String channelId, @NonNull String payload) {
Objects.requireNonNull(channelId, "channelId");
Objects.requireNonNull(payload, "payload");
this.handle.pushCustomPayload(channelId, payload);
}
}
@@ -38,6 +38,7 @@ import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
public class ApiTrackManager extends ApiAbstractManager<Track, net.luckperms.api.track.Track, TrackManager<?>> implements net.luckperms.api.track.TrackManager {
public ApiTrackManager(LuckPermsPlugin plugin, TrackManager<?> handle) {
@@ -74,6 +75,19 @@ public class ApiTrackManager extends ApiAbstractManager<Track, net.luckperms.api
return this.plugin.getStorage().deleteTrack(ApiTrack.cast(track), DeletionCause.API);
}
@Override
public @NonNull CompletableFuture<Void> modifyTrack(@NonNull String name, @NonNull Consumer<? super net.luckperms.api.track.Track> action) {
Objects.requireNonNull(name, "name");
Objects.requireNonNull(action, "action");
return this.plugin.getStorage().createAndLoadTrack(name, CreationCause.API)
.thenApplyAsync(track -> {
action.accept(track.getApiProxy());
return track;
}, this.plugin.getBootstrap().getScheduler().async())
.thenCompose(track -> this.plugin.getStorage().saveTrack(track));
}
@Override
public @NonNull CompletableFuture<Void> loadAllTracks() {
return this.plugin.getStorage().loadAllTracks();
@@ -25,14 +25,13 @@
package me.lucko.luckperms.common.bulkupdate;
import me.lucko.luckperms.common.bulkupdate.action.Action;
import me.lucko.luckperms.common.bulkupdate.query.Query;
import me.lucko.luckperms.common.bulkupdate.action.BulkUpdateAction;
import me.lucko.luckperms.common.filter.FilterList;
import me.lucko.luckperms.common.model.HolderType;
import net.luckperms.api.node.Node;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
@@ -46,35 +45,30 @@ public final class BulkUpdate {
private final DataType dataType;
// the action to apply to the data which matches the constraints
private final Action action;
private final BulkUpdateAction action;
// a set of constraints which data must match to be acted upon
private final List<Query> queries;
// a set of filters which data must match to be acted upon
private final FilterList<Node> filters;
// update statistics of the operation (number of nodes, users and groups affected)
private final BulkUpdateStatistics statistics = new BulkUpdateStatistics();
private final boolean trackStatistics;
public BulkUpdate(DataType dataType, Action action, List<Query> queries, boolean trackStatistics) {
public BulkUpdate(DataType dataType, BulkUpdateAction action, FilterList<Node> filters, boolean trackStatistics) {
this.dataType = dataType;
this.action = action;
this.queries = queries;
this.filters = filters;
this.trackStatistics = trackStatistics;
}
/**
* Check to see if a Node instance satisfies the constrints of this query
* Check to see if a Node instance satisfies the constraints of this query
*
* @param node the node to check
* @return true if satisfied
*/
public boolean satisfiesConstraints(Node node) {
for (Query query : this.queries) {
if (!query.isSatisfiedBy(node)) {
return false;
}
}
return true;
public boolean satisfiesFilters(Node node) {
return this.filters.evaluate(node);
}
/**
@@ -84,7 +78,7 @@ public final class BulkUpdate {
* @return the transformed node, or null if the node should be deleted
*/
private Node apply(Node node) {
if (!satisfiesConstraints(node)) {
if (!satisfiesFilters(node)) {
return node; // make no change
}
@@ -129,63 +123,16 @@ public final class BulkUpdate {
return results;
}
/**
* Converts this {@link BulkUpdate} to SQL syntax
*
* @return this query in SQL form
*/
public PreparedStatementBuilder buildAsSql() {
// DELETE FROM {table} WHERE ...
// UPDATE {table} SET ... WHERE ...
PreparedStatementBuilder builder = new PreparedStatementBuilder();
// add the action
// (DELETE FROM or UPDATE)
this.action.appendSql(builder);
return appendConstraintsAsSql(builder);
}
/**
* Appends the constraints of this {@link BulkUpdate} to the provided statement builder in SQL syntax
*
* @param builder the statement builder to append the constraints to
* @return the same statement builder provided as input
*/
public PreparedStatementBuilder appendConstraintsAsSql(PreparedStatementBuilder builder) {
// if there are no constraints, just return without a WHERE clause
if (this.queries.isEmpty()) {
return builder;
}
// append constraints
builder.append(" WHERE");
for (int i = 0; i < this.queries.size(); i++) {
Query query = this.queries.get(i);
builder.append(" ");
if (i != 0) {
builder.append("AND ");
}
query.appendSql(builder);
}
return builder;
}
public DataType getDataType() {
return this.dataType;
}
public Action getAction() {
public BulkUpdateAction getAction() {
return this.action;
}
public List<Query> getQueries() {
return this.queries;
public FilterList<Node> getFilters() {
return this.filters;
}
public boolean isTrackingStatistics() {
@@ -204,12 +151,12 @@ public final class BulkUpdate {
return this.getDataType() == that.getDataType() &&
Objects.equals(this.getAction(), that.getAction()) &&
Objects.equals(this.getQueries(), that.getQueries());
Objects.equals(this.getFilters(), that.getFilters());
}
@Override
public int hashCode() {
return Objects.hash(getDataType(), getAction(), getQueries(), isTrackingStatistics());
return Objects.hash(getDataType(), getAction(), getFilters(), isTrackingStatistics());
}
@Override
@@ -217,7 +164,7 @@ public final class BulkUpdate {
return "BulkUpdate(" +
"dataType=" + this.getDataType() + ", " +
"action=" + this.getAction() + ", " +
"constraints=" + this.getQueries() + ", " +
"constraints=" + this.getFilters() + ", " +
"trackStatistics=" + this.isTrackingStatistics() + ")";
}
}
@@ -26,8 +26,12 @@
package me.lucko.luckperms.common.bulkupdate;
import com.google.common.collect.ImmutableList;
import me.lucko.luckperms.common.bulkupdate.action.Action;
import me.lucko.luckperms.common.bulkupdate.query.Query;
import me.lucko.luckperms.common.bulkupdate.action.BulkUpdateAction;
import me.lucko.luckperms.common.filter.Comparison;
import me.lucko.luckperms.common.filter.ConstraintFactory;
import me.lucko.luckperms.common.filter.Filter;
import me.lucko.luckperms.common.filter.FilterList;
import net.luckperms.api.node.Node;
import java.util.LinkedHashSet;
import java.util.Set;
@@ -45,18 +49,18 @@ public class BulkUpdateBuilder {
private DataType dataType = DataType.ALL;
// the action to apply to the data which matches the constraints
private Action action = null;
private BulkUpdateAction action = null;
// should the operation count the number of affected nodes, users and groups
private boolean trackStatistics = false;
// a set of constraints which data must match to be acted upon
private final Set<Query> queries = new LinkedHashSet<>();
// a set of filters which data must match to be acted upon
private final Set<Filter<Node, String>> filters = new LinkedHashSet<>();
private BulkUpdateBuilder() {
}
public BulkUpdateBuilder action(Action action) {
public BulkUpdateBuilder action(BulkUpdateAction action) {
this.action = action;
return this;
}
@@ -71,8 +75,8 @@ public class BulkUpdateBuilder {
return this;
}
public BulkUpdateBuilder query(Query query) {
this.queries.add(query);
public BulkUpdateBuilder filter(BulkUpdateField field, Comparison comparison, String value) {
this.filters.add(new Filter<>(field, ConstraintFactory.STRINGS.build(comparison, value)));
return this;
}
@@ -81,7 +85,8 @@ public class BulkUpdateBuilder {
throw new IllegalStateException("no action specified");
}
return new BulkUpdate(this.dataType, this.action, ImmutableList.copyOf(this.queries), this.trackStatistics);
FilterList<Node> filters = new FilterList<>(FilterList.LogicalOperator.AND, ImmutableList.copyOf(this.filters));
return new BulkUpdate(this.dataType, this.action, filters, this.trackStatistics);
}
@Override
@@ -89,7 +94,7 @@ public class BulkUpdateBuilder {
return "BulkUpdateBuilder(" +
"dataType=" + this.dataType + ", " +
"action=" + this.action + ", " +
"constraints=" + this.queries + ", " +
"constraints=" + this.filters + ", " +
"trackStatistics=" + this.trackStatistics + ")";
}
}
@@ -23,54 +23,45 @@
* SOFTWARE.
*/
package me.lucko.luckperms.standalone.app.integration;
package me.lucko.luckperms.common.bulkupdate;
import com.google.gson.Gson;
import me.lucko.luckperms.common.filter.FilterField;
import net.luckperms.api.context.DefaultContextKeys;
import net.luckperms.api.node.Node;
import java.util.Map;
import java.util.Locale;
/**
* An interface able to provide information about the application/plugin health.
* Represents a field being used in a bulk update
*/
public interface HealthReporter {
/**
* Polls the current health status.
*
* @return the health status
*/
Health poll();
final class Health {
private static final Gson GSON = new Gson();
private final boolean up;
private final Map<String, String> details;
Health(boolean up, Map<String, String> details) {
this.up = up;
this.details = details;
}
public boolean isUp() {
return this.up;
}
public Map<String, String> details() {
return this.details;
}
public enum BulkUpdateField implements FilterField<Node, String> {
PERMISSION {
@Override
public String toString() {
return GSON.toJson(this);
public String getValue(Node node) {
return node.getKey();
}
},
public static Health up(Map<String, String> details) {
return new Health(true, details);
SERVER {
@Override
public String getValue(Node node) {
return node.getContexts().getAnyValue(DefaultContextKeys.SERVER_KEY).orElse("global");
}
},
public static Health down(Map<String, String> details) {
return new Health(false, details);
WORLD {
@Override
public String getValue(Node node) {
return node.getContexts().getAnyValue(DefaultContextKeys.WORLD_KEY).orElse("global");
}
};
public static BulkUpdateField of(String s) {
try {
return valueOf(s.toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException e) {
return null;
}
}
@@ -0,0 +1,76 @@
/*
* 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.bulkupdate;
import me.lucko.luckperms.common.bulkupdate.action.BulkUpdateAction;
import me.lucko.luckperms.common.bulkupdate.action.DeleteAction;
import me.lucko.luckperms.common.bulkupdate.action.UpdateAction;
import me.lucko.luckperms.common.filter.FilterField;
import me.lucko.luckperms.common.filter.sql.FilterSqlBuilder;
import net.luckperms.api.node.Node;
public class BulkUpdateSqlBuilder extends FilterSqlBuilder<Node> {
public void visit(BulkUpdate update) {
visit(update.getAction());
visit(update.getFilters());
}
public void visit(BulkUpdateAction action) {
if (action instanceof UpdateAction) {
visit(((UpdateAction) action));
} else if (action instanceof DeleteAction) {
visit(((DeleteAction) action));
} else {
throw new UnsupportedOperationException(action.getClass().getName());
}
}
public void visit(UpdateAction action) {
this.builder.append("UPDATE {table} SET ");
visitFieldName(action.getField());
this.builder.append("=");
this.builder.variable(action.getNewValue());
}
public void visit(DeleteAction action) {
this.builder.append("DELETE FROM {table}");
}
@Override
public void visitFieldName(FilterField<Node, ?> field) {
if (field == BulkUpdateField.PERMISSION) {
this.builder.append("permission");
} else if (field == BulkUpdateField.SERVER) {
this.builder.append("server");
} else if (field == BulkUpdateField.WORLD) {
this.builder.append("world");
} else {
throw new AssertionError(field);
}
}
}
@@ -25,13 +25,12 @@
package me.lucko.luckperms.common.bulkupdate.action;
import me.lucko.luckperms.common.bulkupdate.PreparedStatementBuilder;
import net.luckperms.api.node.Node;
/**
* Represents an action to be applied to a given node.
*/
public interface Action {
public interface BulkUpdateAction {
/**
* Gets the name of this action
@@ -44,17 +43,8 @@ public interface Action {
* Applies this action to the given NodeModel, and returns the result.
*
* @param from the node to base changes from
* @return the new nodemodel instance, or null if the node should be deleted.
* @return the new node instance, or null if the node should be deleted.
*/
Node apply(Node from);
/**
* Gets this action in SQL form.
*
* Will include a placeholder for the table, as "{table}".
*
* @param builder the statement builder
*/
void appendSql(PreparedStatementBuilder builder);
}
@@ -25,10 +25,9 @@
package me.lucko.luckperms.common.bulkupdate.action;
import me.lucko.luckperms.common.bulkupdate.PreparedStatementBuilder;
import net.luckperms.api.node.Node;
public class DeleteAction implements Action {
public class DeleteAction implements BulkUpdateAction {
public static DeleteAction create() {
return new DeleteAction();
@@ -46,9 +45,4 @@ public class DeleteAction implements Action {
public Node apply(Node from) {
return null; // this action just deletes nodes, so return null
}
@Override
public void appendSql(PreparedStatementBuilder builder) {
builder.append("DELETE FROM {table}");
}
}
@@ -25,28 +25,27 @@
package me.lucko.luckperms.common.bulkupdate.action;
import me.lucko.luckperms.common.bulkupdate.PreparedStatementBuilder;
import me.lucko.luckperms.common.bulkupdate.query.QueryField;
import me.lucko.luckperms.common.bulkupdate.BulkUpdateField;
import me.lucko.luckperms.common.node.factory.NodeBuilders;
import net.luckperms.api.context.DefaultContextKeys;
import net.luckperms.api.context.MutableContextSet;
import net.luckperms.api.node.Node;
public class UpdateAction implements Action {
public class UpdateAction implements BulkUpdateAction {
public static UpdateAction of(QueryField field, String value) {
public static UpdateAction of(BulkUpdateField field, String value) {
return new UpdateAction(field, value);
}
// the field we're updating
private final QueryField field;
private final BulkUpdateField field;
// the new value of the field
private final String value;
private final String newValue;
private UpdateAction(QueryField field, String value) {
private UpdateAction(BulkUpdateField field, String newValue) {
this.field = field;
this.value = value;
this.newValue = newValue;
}
@Override
@@ -54,11 +53,19 @@ public class UpdateAction implements Action {
return "update";
}
public BulkUpdateField getField() {
return this.field;
}
public String getNewValue() {
return this.newValue;
}
@Override
public Node apply(Node from) {
switch (this.field) {
case PERMISSION:
return NodeBuilders.determineMostApplicable(this.value)
return NodeBuilders.determineMostApplicable(this.newValue)
.value(from.getValue())
.expiry(from.getExpiry())
.context(from.getContexts())
@@ -66,8 +73,8 @@ public class UpdateAction implements Action {
case SERVER: {
MutableContextSet contexts = from.getContexts().mutableCopy();
contexts.removeAll(DefaultContextKeys.SERVER_KEY);
if (!this.value.equals("global")) {
contexts.add(DefaultContextKeys.SERVER_KEY, this.value);
if (!this.newValue.equals("global")) {
contexts.add(DefaultContextKeys.SERVER_KEY, this.newValue);
}
return from.toBuilder()
@@ -77,8 +84,8 @@ public class UpdateAction implements Action {
case WORLD: {
MutableContextSet contexts = from.getContexts().mutableCopy();
contexts.removeAll(DefaultContextKeys.WORLD_KEY);
if (!this.value.equals("global")) {
contexts.add(DefaultContextKeys.WORLD_KEY, this.value);
if (!this.newValue.equals("global")) {
contexts.add(DefaultContextKeys.WORLD_KEY, this.newValue);
}
return from.toBuilder()
@@ -89,10 +96,4 @@ public class UpdateAction implements Action {
throw new RuntimeException();
}
}
@Override
public void appendSql(PreparedStatementBuilder builder) {
builder.append("UPDATE {table} SET " + this.field.getSqlName() + "=");
builder.variable(this.value);
}
}
@@ -1,112 +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.bulkupdate.comparison;
import me.lucko.luckperms.common.bulkupdate.PreparedStatementBuilder;
import java.util.regex.Pattern;
/**
* An enumeration of standard {@link Comparison}s.
*/
public enum StandardComparison implements Comparison {
EQUAL("==", "=") {
@Override
public CompiledExpression compile(String expression) {
return expression::equalsIgnoreCase;
}
},
NOT_EQUAL("!=", "!=") {
@Override
public CompiledExpression compile(String expression) {
return string -> !expression.equalsIgnoreCase(string);
}
},
SIMILAR("~~", "LIKE") {
@Override
public CompiledExpression compile(String expression) {
Pattern pattern = StandardComparison.compilePatternForLikeSyntax(expression);
return string -> pattern.matcher(string).matches();
}
},
NOT_SIMILAR("!~", "NOT LIKE") {
@Override
public CompiledExpression compile(String expression) {
Pattern pattern = StandardComparison.compilePatternForLikeSyntax(expression);
return string -> !pattern.matcher(string).matches();
}
};
public static final String WILDCARD = "%";
public static final String WILDCARD_ONE = "_";
private final String symbol;
private final String asSql;
StandardComparison(String symbol, String asSql) {
this.symbol = symbol;
this.asSql = asSql;
}
@Override
public String getSymbol() {
return this.symbol;
}
@Override
public void appendSql(PreparedStatementBuilder builder) {
builder.append(this.asSql);
}
@Override
public String toString() {
return this.symbol;
}
public static StandardComparison parseComparison(String s) {
for (StandardComparison t : values()) {
if (t.getSymbol().equals(s)) {
return t;
}
}
return null;
}
static Pattern compilePatternForLikeSyntax(String expression) {
expression = expression.replace(".", "\\.");
// convert from SQL LIKE syntax to regex
expression = expression.replace(WILDCARD_ONE, ".");
expression = expression.replace(WILDCARD, ".*");
return Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
}
}
@@ -1,83 +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.bulkupdate.query;
import me.lucko.luckperms.common.bulkupdate.PreparedStatementBuilder;
import me.lucko.luckperms.common.bulkupdate.comparison.Constraint;
import net.luckperms.api.context.DefaultContextKeys;
import net.luckperms.api.node.Node;
/**
* Represents a query component
*/
public class Query {
public static Query of(QueryField field, Constraint constraint) {
return new Query(field, constraint);
}
// the field this query is comparing against
private final QueryField field;
// the constraint
private final Constraint constraint;
private Query(QueryField field, Constraint constraint) {
this.field = field;
this.constraint = constraint;
}
/**
* Returns if the given node satisfies this query
*
* @param node the node
* @return true if satisfied
*/
public boolean isSatisfiedBy(Node node) {
switch (this.field) {
case PERMISSION:
return this.constraint.eval(node.getKey());
case SERVER:
return this.constraint.eval(node.getContexts().getAnyValue(DefaultContextKeys.SERVER_KEY).orElse("global"));
case WORLD:
return this.constraint.eval(node.getContexts().getAnyValue(DefaultContextKeys.WORLD_KEY).orElse("global"));
default:
throw new RuntimeException();
}
}
public void appendSql(PreparedStatementBuilder builder) {
this.constraint.appendSql(builder, this.field.getSqlName());
}
public QueryField getField() {
return this.field;
}
public Constraint getConstraint() {
return this.constraint;
}
}
@@ -86,39 +86,44 @@ public abstract class ParentCommand<T, I> extends Command<Void> {
return;
}
final String targetArgument = args.get(0);
I targetId = null;
if (this.type == Type.TAKES_ARGUMENT_FOR_TARGET) {
targetId = parseTarget(targetArgument, plugin, sender);
if (this.type == Type.TARGETED) {
final String targetArgument = args.get(0);
I targetId = parseTarget(targetArgument, plugin, sender);
if (targetId == null) {
return;
}
}
ReentrantLock lock = getLockForTarget(targetId);
lock.lock();
try {
T target = getTarget(targetId, plugin, sender);
if (target == null) {
return;
}
ReentrantLock lock = getLockForTarget(targetId);
lock.lock();
try {
sub.execute(plugin, sender, target, args.subList(this.type.minArgs, args.size()), label);
T target = getTarget(targetId, plugin, sender);
if (target == null) {
return;
}
try {
sub.execute(plugin, sender, target, args.subList(this.type.minArgs, args.size()), label);
} catch (CommandException e) {
e.handle(sender, label, sub);
}
cleanup(target, plugin);
} finally {
lock.unlock();
}
} else {
try {
sub.execute(plugin, sender, null, args.subList(this.type.minArgs, args.size()), label);
} catch (CommandException e) {
e.handle(sender, label, sub);
}
cleanup(target, plugin);
} finally {
lock.unlock();
}
}
@Override
public List<String> tabComplete(LuckPermsPlugin plugin, Sender sender, ArgumentList args) {
switch (this.type) {
case TAKES_ARGUMENT_FOR_TARGET:
case TARGETED:
return TabCompleter.create()
.at(0, CompletionSupplier.startsWith(() -> getTargets(plugin).stream()))
.at(1, CompletionSupplier.startsWith(() -> getChildren().stream()
@@ -133,7 +138,7 @@ public abstract class ParentCommand<T, I> extends Command<Void> {
.orElse(Collections.emptyList())
)
.complete(args);
case NO_TARGET_ARGUMENT:
case NOT_TARGETED:
return TabCompleter.create()
.at(0, CompletionSupplier.startsWith(() -> getChildren().stream()
.filter(s -> s.isAuthorized(sender))
@@ -178,21 +183,31 @@ public abstract class ParentCommand<T, I> extends Command<Void> {
return getChildren().stream().anyMatch(sc -> sc.isAuthorized(sender));
}
protected abstract List<String> getTargets(LuckPermsPlugin plugin);
protected List<String> getTargets(LuckPermsPlugin plugin) {
throw new UnsupportedOperationException();
}
protected abstract I parseTarget(String target, LuckPermsPlugin plugin, Sender sender);
protected I parseTarget(String target, LuckPermsPlugin plugin, Sender sender) {
throw new UnsupportedOperationException();
}
protected abstract ReentrantLock getLockForTarget(I target);
protected ReentrantLock getLockForTarget(I target) {
throw new UnsupportedOperationException();
}
protected abstract T getTarget(I target, LuckPermsPlugin plugin, Sender sender);
protected T getTarget(I target, LuckPermsPlugin plugin, Sender sender) {
throw new UnsupportedOperationException();
}
protected abstract void cleanup(T t, LuckPermsPlugin plugin);
protected void cleanup(T t, LuckPermsPlugin plugin) {
throw new UnsupportedOperationException();
}
public enum Type {
// e.g. /lp log sub-command....
NO_TARGET_ARGUMENT(0),
NOT_TARGETED(0),
// e.g. /lp user <USER> sub-command....
TAKES_ARGUMENT_FOR_TARGET(1);
TARGETED(1);
private final int cmdIndex;
private final int minArgs;
@@ -28,12 +28,9 @@ package me.lucko.luckperms.common.commands.group;
import me.lucko.luckperms.common.actionlog.LoggedAction;
import me.lucko.luckperms.common.bulkupdate.BulkUpdate;
import me.lucko.luckperms.common.bulkupdate.BulkUpdateBuilder;
import me.lucko.luckperms.common.bulkupdate.BulkUpdateField;
import me.lucko.luckperms.common.bulkupdate.DataType;
import me.lucko.luckperms.common.bulkupdate.action.DeleteAction;
import me.lucko.luckperms.common.bulkupdate.comparison.Constraint;
import me.lucko.luckperms.common.bulkupdate.comparison.StandardComparison;
import me.lucko.luckperms.common.bulkupdate.query.Query;
import me.lucko.luckperms.common.bulkupdate.query.QueryField;
import me.lucko.luckperms.common.command.abstraction.SingleCommand;
import me.lucko.luckperms.common.command.access.ArgumentPermissions;
import me.lucko.luckperms.common.command.access.CommandPermission;
@@ -43,6 +40,7 @@ import me.lucko.luckperms.common.command.tabcomplete.TabCompleter;
import me.lucko.luckperms.common.command.tabcomplete.TabCompletions;
import me.lucko.luckperms.common.command.utils.ArgumentList;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.filter.Comparison;
import me.lucko.luckperms.common.locale.Message;
import me.lucko.luckperms.common.messaging.InternalMessagingService;
import me.lucko.luckperms.common.model.Group;
@@ -115,7 +113,7 @@ public class DeleteGroup extends SingleCommand {
.trackStatistics(false)
.dataType(DataType.ALL)
.action(DeleteAction.create())
.query(Query.of(QueryField.PERMISSION, Constraint.of(StandardComparison.EQUAL, Inheritance.key(groupName))))
.filter(BulkUpdateField.PERMISSION, Comparison.EQUAL, Inheritance.key(groupName))
.build();
plugin.getStorage().applyBulkUpdate(operation).whenCompleteAsync((v, ex) -> {
if (ex != null) {
@@ -60,7 +60,7 @@ public class GroupParentCommand extends ParentCommand<Group, String> {
.build(key -> new ReentrantLock());
public GroupParentCommand() {
super(CommandSpec.GROUP, "Group", Type.TAKES_ARGUMENT_FOR_TARGET, ImmutableList.<Command<Group>>builder()
super(CommandSpec.GROUP, "Group", Type.TARGETED, ImmutableList.<Command<Group>>builder()
.add(new GroupInfo())
.add(new CommandPermission<>(HolderType.GROUP))
.add(new CommandParent<>(HolderType.GROUP))
@@ -28,11 +28,8 @@ package me.lucko.luckperms.common.commands.group;
import me.lucko.luckperms.common.actionlog.LoggedAction;
import me.lucko.luckperms.common.bulkupdate.BulkUpdate;
import me.lucko.luckperms.common.bulkupdate.BulkUpdateBuilder;
import me.lucko.luckperms.common.bulkupdate.BulkUpdateField;
import me.lucko.luckperms.common.bulkupdate.action.UpdateAction;
import me.lucko.luckperms.common.bulkupdate.comparison.Constraint;
import me.lucko.luckperms.common.bulkupdate.comparison.StandardComparison;
import me.lucko.luckperms.common.bulkupdate.query.Query;
import me.lucko.luckperms.common.bulkupdate.query.QueryField;
import me.lucko.luckperms.common.command.abstraction.ChildCommand;
import me.lucko.luckperms.common.command.access.ArgumentPermissions;
import me.lucko.luckperms.common.command.access.CommandPermission;
@@ -41,6 +38,7 @@ import me.lucko.luckperms.common.command.tabcomplete.CompletionSupplier;
import me.lucko.luckperms.common.command.tabcomplete.TabCompleter;
import me.lucko.luckperms.common.command.utils.ArgumentList;
import me.lucko.luckperms.common.command.utils.StorageAssistant;
import me.lucko.luckperms.common.filter.Comparison;
import me.lucko.luckperms.common.locale.Message;
import me.lucko.luckperms.common.model.Group;
import me.lucko.luckperms.common.node.types.Inheritance;
@@ -112,8 +110,8 @@ public class GroupRename extends ChildCommand<Group> {
BulkUpdate operation = BulkUpdateBuilder.create()
.trackStatistics(false)
.dataType(me.lucko.luckperms.common.bulkupdate.DataType.ALL)
.action(UpdateAction.of(QueryField.PERMISSION, Inheritance.key(newGroupName)))
.query(Query.of(QueryField.PERMISSION, Constraint.of(StandardComparison.EQUAL, Inheritance.key(target.getName()))))
.action(UpdateAction.of(BulkUpdateField.PERMISSION, Inheritance.key(newGroupName)))
.filter(BulkUpdateField.PERMISSION, Comparison.EQUAL, Inheritance.key(target.getName()))
.build();
return plugin.getStorage().applyBulkUpdate(operation);
} else {
@@ -25,25 +25,26 @@
package me.lucko.luckperms.common.commands.log;
import me.lucko.luckperms.common.actionlog.Log;
import me.lucko.luckperms.common.actionlog.LogPage;
import me.lucko.luckperms.common.actionlog.LoggedAction;
import me.lucko.luckperms.common.actionlog.filter.ActionFilters;
import me.lucko.luckperms.common.command.abstraction.ChildCommand;
import me.lucko.luckperms.common.command.access.CommandPermission;
import me.lucko.luckperms.common.command.spec.CommandSpec;
import me.lucko.luckperms.common.command.tabcomplete.TabCompleter;
import me.lucko.luckperms.common.command.tabcomplete.TabCompletions;
import me.lucko.luckperms.common.command.utils.ArgumentList;
import me.lucko.luckperms.common.filter.PageParameters;
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.storage.misc.DataConstraints;
import me.lucko.luckperms.common.util.Paginated;
import me.lucko.luckperms.common.util.Predicates;
import java.util.List;
import java.util.Locale;
public class LogGroupHistory extends ChildCommand<Log> {
public class LogGroupHistory extends ChildCommand<Void> {
private static final int ENTRIES_PER_PAGE = 10;
public LogGroupHistory() {
@@ -51,44 +52,34 @@ public class LogGroupHistory extends ChildCommand<Log> {
}
@Override
public void execute(LuckPermsPlugin plugin, Sender sender, Log log, ArgumentList args, String label) {
public void execute(LuckPermsPlugin plugin, Sender sender, Void ignored, ArgumentList args, String label) {
String group = args.get(0).toLowerCase(Locale.ROOT);
if (!DataConstraints.GROUP_NAME_TEST.test(group)) {
Message.GROUP_INVALID_ENTRY.send(sender, group);
return;
}
Paginated<LoggedAction> content = new Paginated<>(log.getGroupHistory(group));
PageParameters pageParams = new PageParameters(ENTRIES_PER_PAGE, args.getIntOrDefault(1, 1));
LogPage log = plugin.getStorage().getLogPage(ActionFilters.group(group), pageParams).join();
int page = args.getIntOrDefault(1, Integer.MIN_VALUE);
if (page != Integer.MIN_VALUE) {
showLog(page, sender, content);
} else {
showLog(content.getMaxPages(ENTRIES_PER_PAGE), sender, content);
}
}
int page = pageParams.pageNumber();
int maxPage = pageParams.getMaxPage(log.getTotalEntries());
private static void showLog(int page, Sender sender, Paginated<LoggedAction> log) {
int maxPage = log.getMaxPages(ENTRIES_PER_PAGE);
if (maxPage == 0) {
if (log.getTotalEntries() == 0) {
Message.LOG_NO_ENTRIES.send(sender);
return;
}
if (page == Integer.MIN_VALUE) {
page = maxPage;
}
if (page < 1 || page > maxPage) {
Message.LOG_INVALID_PAGE_RANGE.send(sender, maxPage);
return;
}
List<Paginated.Entry<LoggedAction>> entries = log.getPage(page, ENTRIES_PER_PAGE);
List<LogPage.Entry<LoggedAction>> entries = log.getNumberedContent();
String name = entries.stream().findAny().get().value().getTarget().getName();
Message.LOG_HISTORY_GROUP_HEADER.send(sender, name, page, maxPage);
for (Paginated.Entry<LoggedAction> e : entries) {
for (LogPage.Entry<LoggedAction> e : entries) {
Message.LOG_ENTRY.send(sender, e.position(), e.value());
}
}
@@ -25,7 +25,6 @@
package me.lucko.luckperms.common.commands.log;
import me.lucko.luckperms.common.actionlog.Log;
import me.lucko.luckperms.common.command.abstraction.ChildCommand;
import me.lucko.luckperms.common.command.access.CommandPermission;
import me.lucko.luckperms.common.command.spec.CommandSpec;
@@ -43,7 +42,7 @@ import net.luckperms.api.node.Node;
import java.util.Optional;
import java.util.UUID;
public class LogNotify extends ChildCommand<Log> {
public class LogNotify extends ChildCommand<Void> {
private static final String IGNORE_NODE = "luckperms.log.notify.ignoring";
public LogNotify() {
@@ -83,7 +82,7 @@ public class LogNotify extends ChildCommand<Log> {
}
@Override
public void execute(LuckPermsPlugin plugin, Sender sender, Log log, ArgumentList args, String label) {
public void execute(LuckPermsPlugin plugin, Sender sender, Void ignored, ArgumentList args, String label) {
if (sender.isConsole()) {
Message.LOG_NOTIFY_CONSOLE.send(sender);
return;
@@ -26,22 +26,13 @@
package me.lucko.luckperms.common.commands.log;
import com.google.common.collect.ImmutableList;
import me.lucko.luckperms.common.actionlog.Log;
import me.lucko.luckperms.common.command.abstraction.Command;
import me.lucko.luckperms.common.command.abstraction.ParentCommand;
import me.lucko.luckperms.common.command.spec.CommandSpec;
import me.lucko.luckperms.common.locale.Message;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.sender.Sender;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
public class LogParentCommand extends ParentCommand<Log, Void> {
private final ReentrantLock lock = new ReentrantLock();
public class LogParentCommand extends ParentCommand<Void, Void> {
public LogParentCommand() {
super(CommandSpec.LOG, "Log", Type.NO_TARGET_ARGUMENT, ImmutableList.<Command<Log>>builder()
super(CommandSpec.LOG, "Log", Type.NOT_TARGETED, ImmutableList.<Command<Void>>builder()
.add(new LogRecent())
.add(new LogSearch())
.add(new LogNotify())
@@ -51,38 +42,4 @@ public class LogParentCommand extends ParentCommand<Log, Void> {
.build()
);
}
@Override
protected ReentrantLock getLockForTarget(Void target) {
return this.lock; // all commands target the same log, so we share a lock between all "targets"
}
@Override
protected Log getTarget(Void target, LuckPermsPlugin plugin, Sender sender) {
Log log = plugin.getStorage().getLog().join();
if (log == null) {
Message.LOG_LOAD_ERROR.send(sender);
}
return log;
}
@Override
protected void cleanup(Log log, LuckPermsPlugin plugin) {
}
@Override
protected List<String> getTargets(LuckPermsPlugin plugin) {
// should never be called if we specify Type.NO_TARGET_ARGUMENT in the constructor
throw new UnsupportedOperationException();
}
@Override
protected Void parseTarget(String target, LuckPermsPlugin plugin, Sender sender) {
// should never be called if we specify Type.NO_TARGET_ARGUMENT in the constructor
throw new UnsupportedOperationException();
}
}
@@ -25,22 +25,23 @@
package me.lucko.luckperms.common.commands.log;
import me.lucko.luckperms.common.actionlog.Log;
import me.lucko.luckperms.common.actionlog.LogPage;
import me.lucko.luckperms.common.actionlog.LoggedAction;
import me.lucko.luckperms.common.actionlog.filter.ActionFilters;
import me.lucko.luckperms.common.command.abstraction.ChildCommand;
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.filter.PageParameters;
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.Paginated;
import me.lucko.luckperms.common.util.Predicates;
import java.util.List;
import java.util.UUID;
public class LogRecent extends ChildCommand<Log> {
public class LogRecent extends ChildCommand<Void> {
private static final int ENTRIES_PER_PAGE = 10;
public LogRecent() {
@@ -48,39 +49,32 @@ public class LogRecent extends ChildCommand<Log> {
}
@Override
public void execute(LuckPermsPlugin plugin, Sender sender, Log log, ArgumentList args, String label) {
if (args.isEmpty()) {
// No page or user
Paginated<LoggedAction> content = new Paginated<>(log.getContent());
showLog(content.getMaxPages(ENTRIES_PER_PAGE), false, sender, content);
return;
public void execute(LuckPermsPlugin plugin, Sender sender, Void ignored, ArgumentList args, String label) {
int page = 1;
UUID uuid = null;
if (!args.isEmpty()) {
int pageNo = args.getIntOrDefault(0, Integer.MIN_VALUE);
if (pageNo != Integer.MIN_VALUE) {
page = pageNo;
} else {
uuid = args.getUserTarget(0, plugin, sender);
if (uuid == null) {
return;
}
pageNo = args.getIntOrDefault(1, Integer.MIN_VALUE);
if (pageNo != Integer.MIN_VALUE) {
page = pageNo;
}
}
}
int page = args.getIntOrDefault(0, Integer.MIN_VALUE);
if (page != Integer.MIN_VALUE) {
Paginated<LoggedAction> content = new Paginated<>(log.getContent());
showLog(page, false, sender, content);
return;
}
PageParameters pageParams = new PageParameters(ENTRIES_PER_PAGE, page);
LogPage log = plugin.getStorage().getLogPage(uuid == null ? ActionFilters.all() : ActionFilters.source(uuid), pageParams).join();
// User and possibly page
UUID uuid = args.getUserTarget(0, plugin, sender);
if (uuid == null) {
return;
}
Paginated<LoggedAction> content = new Paginated<>(log.getContent(uuid));
page = args.getIntOrDefault(1, Integer.MIN_VALUE);
if (page != Integer.MIN_VALUE) {
showLog(page, true, sender, content);
} else {
showLog(content.getMaxPages(ENTRIES_PER_PAGE), true, sender, content);
}
}
private static void showLog(int page, boolean specificUser, Sender sender, Paginated<LoggedAction> log) {
int maxPage = log.getMaxPages(ENTRIES_PER_PAGE);
if (maxPage == 0) {
int maxPage = pageParams.getMaxPage(log.getTotalEntries());
if (log.getTotalEntries() == 0) {
Message.LOG_NO_ENTRIES.send(sender);
return;
}
@@ -90,8 +84,8 @@ public class LogRecent extends ChildCommand<Log> {
return;
}
List<Paginated.Entry<LoggedAction>> entries = log.getPage(page, ENTRIES_PER_PAGE);
if (specificUser) {
List<LogPage.Entry<LoggedAction>> entries = log.getNumberedContent();
if (uuid != null) {
String name = entries.stream().findAny().get().value().getSource().getName();
if (name.contains("@")) {
name = name.split("@")[0];
@@ -101,8 +95,9 @@ public class LogRecent extends ChildCommand<Log> {
Message.LOG_RECENT_HEADER.send(sender, page, maxPage);
}
for (Paginated.Entry<LoggedAction> e : entries) {
for (LogPage.Entry<LoggedAction> e : entries) {
Message.LOG_ENTRY.send(sender, e.position(), e.value());
}
}
}
@@ -25,21 +25,22 @@
package me.lucko.luckperms.common.commands.log;
import me.lucko.luckperms.common.actionlog.Log;
import me.lucko.luckperms.common.actionlog.LogPage;
import me.lucko.luckperms.common.actionlog.LoggedAction;
import me.lucko.luckperms.common.actionlog.filter.ActionFilters;
import me.lucko.luckperms.common.command.abstraction.ChildCommand;
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.filter.PageParameters;
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.Paginated;
import me.lucko.luckperms.common.util.Predicates;
import java.util.List;
public class LogSearch extends ChildCommand<Log> {
public class LogSearch extends ChildCommand<Void> {
private static final int ENTRIES_PER_PAGE = 10;
public LogSearch() {
@@ -47,8 +48,8 @@ public class LogSearch extends ChildCommand<Log> {
}
@Override
public void execute(LuckPermsPlugin plugin, Sender sender, Log log, ArgumentList args, String label) {
int page = Integer.MIN_VALUE;
public void execute(LuckPermsPlugin plugin, Sender sender, Void ignored, ArgumentList args, String label) {
int page = 1;
if (args.size() > 1) {
try {
page = Integer.parseInt(args.get(args.size() - 1));
@@ -59,36 +60,26 @@ public class LogSearch extends ChildCommand<Log> {
}
final String query = String.join(" ", args);
Paginated<LoggedAction> content = new Paginated<>(log.getSearch(query));
PageParameters pageParams = new PageParameters(ENTRIES_PER_PAGE, page);
LogPage log = plugin.getStorage().getLogPage(ActionFilters.search(query), pageParams).join();
if (page != Integer.MIN_VALUE) {
showLog(page, query, sender, content);
} else {
showLog(content.getMaxPages(ENTRIES_PER_PAGE), query, sender, content);
}
}
private static void showLog(int page, String query, Sender sender, Paginated<LoggedAction> log) {
int maxPage = log.getMaxPages(ENTRIES_PER_PAGE);
if (maxPage == 0) {
int maxPage = pageParams.getMaxPage(log.getTotalEntries());
if (log.getTotalEntries() == 0) {
Message.LOG_NO_ENTRIES.send(sender);
return;
}
if (page == Integer.MIN_VALUE) {
page = maxPage;
}
if (page < 1 || page > maxPage) {
Message.LOG_INVALID_PAGE_RANGE.send(sender, maxPage);
return;
}
List<Paginated.Entry<LoggedAction>> entries = log.getPage(page, ENTRIES_PER_PAGE);
List<LogPage.Entry<LoggedAction>> entries = log.getNumberedContent();
Message.LOG_SEARCH_HEADER.send(sender, query, page, maxPage);
for (Paginated.Entry<LoggedAction> e : entries) {
for (LogPage.Entry<LoggedAction> e : entries) {
Message.LOG_ENTRY.send(sender, e.position(), e.value());
}
}
}
@@ -25,25 +25,26 @@
package me.lucko.luckperms.common.commands.log;
import me.lucko.luckperms.common.actionlog.Log;
import me.lucko.luckperms.common.actionlog.LogPage;
import me.lucko.luckperms.common.actionlog.LoggedAction;
import me.lucko.luckperms.common.actionlog.filter.ActionFilters;
import me.lucko.luckperms.common.command.abstraction.ChildCommand;
import me.lucko.luckperms.common.command.access.CommandPermission;
import me.lucko.luckperms.common.command.spec.CommandSpec;
import me.lucko.luckperms.common.command.tabcomplete.TabCompleter;
import me.lucko.luckperms.common.command.tabcomplete.TabCompletions;
import me.lucko.luckperms.common.command.utils.ArgumentList;
import me.lucko.luckperms.common.filter.PageParameters;
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.storage.misc.DataConstraints;
import me.lucko.luckperms.common.util.Paginated;
import me.lucko.luckperms.common.util.Predicates;
import java.util.List;
import java.util.Locale;
public class LogTrackHistory extends ChildCommand<Log> {
public class LogTrackHistory extends ChildCommand<Void> {
private static final int ENTRIES_PER_PAGE = 10;
public LogTrackHistory() {
@@ -51,44 +52,33 @@ public class LogTrackHistory extends ChildCommand<Log> {
}
@Override
public void execute(LuckPermsPlugin plugin, Sender sender, Log log, ArgumentList args, String label) {
public void execute(LuckPermsPlugin plugin, Sender sender, Void ignored, ArgumentList args, String label) {
String track = args.get(0).toLowerCase(Locale.ROOT);
if (!DataConstraints.TRACK_NAME_TEST.test(track)) {
Message.TRACK_INVALID_ENTRY.send(sender, track);
return;
}
PageParameters pageParams = new PageParameters(ENTRIES_PER_PAGE, args.getIntOrDefault(1, 1));
LogPage log = plugin.getStorage().getLogPage(ActionFilters.track(track), pageParams).join();
Paginated<LoggedAction> content = new Paginated<>(log.getTrackHistory(track));
int page = pageParams.pageNumber();
int maxPage = pageParams.getMaxPage(log.getTotalEntries());
int page = args.getIntOrDefault(1, Integer.MIN_VALUE);
if (page != Integer.MIN_VALUE) {
showLog(page, sender, content);
} else {
showLog(content.getMaxPages(ENTRIES_PER_PAGE), sender, content);
}
}
private static void showLog(int page, Sender sender, Paginated<LoggedAction> log) {
int maxPage = log.getMaxPages(ENTRIES_PER_PAGE);
if (maxPage == 0) {
if (log.getTotalEntries() == 0) {
Message.LOG_NO_ENTRIES.send(sender);
return;
}
if (page == Integer.MIN_VALUE) {
page = maxPage;
}
if (page < 1 || page > maxPage) {
Message.LOG_INVALID_PAGE_RANGE.send(sender, maxPage);
return;
}
List<Paginated.Entry<LoggedAction>> entries = log.getPage(page, ENTRIES_PER_PAGE);
List<LogPage.Entry<LoggedAction>> entries = log.getNumberedContent();
String name = entries.stream().findAny().get().value().getTarget().getName();
Message.LOG_HISTORY_TRACK_HEADER.send(sender, name, page, maxPage);
for (Paginated.Entry<LoggedAction> e : entries) {
for (LogPage.Entry<LoggedAction> e : entries) {
Message.LOG_ENTRY.send(sender, e.position(), e.value());
}
}
@@ -25,22 +25,23 @@
package me.lucko.luckperms.common.commands.log;
import me.lucko.luckperms.common.actionlog.Log;
import me.lucko.luckperms.common.actionlog.LogPage;
import me.lucko.luckperms.common.actionlog.LoggedAction;
import me.lucko.luckperms.common.actionlog.filter.ActionFilters;
import me.lucko.luckperms.common.command.abstraction.ChildCommand;
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.filter.PageParameters;
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.Paginated;
import me.lucko.luckperms.common.util.Predicates;
import java.util.List;
import java.util.UUID;
public class LogUserHistory extends ChildCommand<Log> {
public class LogUserHistory extends ChildCommand<Void> {
private static final int ENTRIES_PER_PAGE = 10;
public LogUserHistory() {
@@ -48,25 +49,19 @@ public class LogUserHistory extends ChildCommand<Log> {
}
@Override
public void execute(LuckPermsPlugin plugin, Sender sender, Log log, ArgumentList args, String label) {
public void execute(LuckPermsPlugin plugin, Sender sender, Void ignored, ArgumentList args, String label) {
UUID uuid = args.getUserTarget(0, plugin, sender);
if (uuid == null) {
return;
}
Paginated<LoggedAction> content = new Paginated<>(log.getUserHistory(uuid));
PageParameters pageParams = new PageParameters(ENTRIES_PER_PAGE, args.getIntOrDefault(1, 1));
LogPage log = plugin.getStorage().getLogPage(ActionFilters.user(uuid), pageParams).join();
int page = args.getIntOrDefault(1, Integer.MIN_VALUE);
if (page != Integer.MIN_VALUE) {
showLog(page, sender, content);
} else {
showLog(content.getMaxPages(ENTRIES_PER_PAGE), sender, content);
}
}
int page = pageParams.pageNumber();
int maxPage = pageParams.getMaxPage(log.getTotalEntries());
private static void showLog(int page, Sender sender, Paginated<LoggedAction> log) {
int maxPage = log.getMaxPages(ENTRIES_PER_PAGE);
if (maxPage == 0) {
if (log.getTotalEntries() == 0) {
Message.LOG_NO_ENTRIES.send(sender);
return;
}
@@ -76,11 +71,11 @@ public class LogUserHistory extends ChildCommand<Log> {
return;
}
List<Paginated.Entry<LoggedAction>> entries = log.getPage(page, ENTRIES_PER_PAGE);
List<LogPage.Entry<LoggedAction>> entries = log.getNumberedContent();
String name = entries.stream().findAny().get().value().getTarget().getName();
Message.LOG_HISTORY_USER_HEADER.send(sender, name, page, maxPage);
for (Paginated.Entry<LoggedAction> e : entries) {
for (LogPage.Entry<LoggedAction> e : entries) {
Message.LOG_ENTRY.send(sender, e.position(), e.value());
}
}
@@ -28,15 +28,12 @@ package me.lucko.luckperms.common.commands.misc;
import com.github.benmanes.caffeine.cache.Cache;
import me.lucko.luckperms.common.bulkupdate.BulkUpdate;
import me.lucko.luckperms.common.bulkupdate.BulkUpdateBuilder;
import me.lucko.luckperms.common.bulkupdate.BulkUpdateField;
import me.lucko.luckperms.common.bulkupdate.BulkUpdateSqlBuilder;
import me.lucko.luckperms.common.bulkupdate.BulkUpdateStatistics;
import me.lucko.luckperms.common.bulkupdate.DataType;
import me.lucko.luckperms.common.bulkupdate.action.DeleteAction;
import me.lucko.luckperms.common.bulkupdate.action.UpdateAction;
import me.lucko.luckperms.common.bulkupdate.comparison.Comparison;
import me.lucko.luckperms.common.bulkupdate.comparison.Constraint;
import me.lucko.luckperms.common.bulkupdate.comparison.StandardComparison;
import me.lucko.luckperms.common.bulkupdate.query.Query;
import me.lucko.luckperms.common.bulkupdate.query.QueryField;
import me.lucko.luckperms.common.command.abstraction.CommandException;
import me.lucko.luckperms.common.command.abstraction.SingleCommand;
import me.lucko.luckperms.common.command.access.CommandPermission;
@@ -44,6 +41,7 @@ import me.lucko.luckperms.common.command.spec.CommandSpec;
import me.lucko.luckperms.common.command.utils.ArgumentException;
import me.lucko.luckperms.common.command.utils.ArgumentList;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.filter.Comparison;
import me.lucko.luckperms.common.locale.Message;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.sender.Sender;
@@ -112,7 +110,7 @@ public class BulkUpdateCommand extends SingleCommand {
}
String field = args.remove(0);
QueryField queryField = QueryField.of(field);
BulkUpdateField queryField = BulkUpdateField.of(field);
if (queryField == null) {
throw new ArgumentException.DetailedUsage();
}
@@ -131,20 +129,20 @@ public class BulkUpdateCommand extends SingleCommand {
return;
}
QueryField field = QueryField.of(parts[0]);
BulkUpdateField field = BulkUpdateField.of(parts[0]);
if (field == null) {
Message.BULK_UPDATE_INVALID_CONSTRAINT.send(sender, constraint);
return;
}
Comparison comparison = StandardComparison.parseComparison(parts[1]);
Comparison comparison = Comparison.parse(parts[1]);
if (comparison == null) {
Message.BULK_UPDATE_INVALID_COMPARISON.send(sender, parts[1]);
return;
}
String expr = parts[2];
bulkUpdateBuilder.query(Query.of(field, Constraint.of(comparison, expr)));
bulkUpdateBuilder.filter(field, comparison, expr);
}
BulkUpdate bulkUpdate = bulkUpdateBuilder.build();
@@ -155,7 +153,11 @@ public class BulkUpdateCommand extends SingleCommand {
String id = String.format("%04d", ThreadLocalRandom.current().nextInt(10000));
this.pendingOperations.put(id, bulkUpdate);
Message.BULK_UPDATE_QUEUED.send(sender, bulkUpdate.buildAsSql().toReadableString().replace("{table}", bulkUpdate.getDataType().getName()));
BulkUpdateSqlBuilder sqlBuilder = new BulkUpdateSqlBuilder();
sqlBuilder.visit(bulkUpdate);
String readableSql = sqlBuilder.builder().toReadableString().replace("{table}", bulkUpdate.getDataType().getName());
Message.BULK_UPDATE_QUEUED.send(sender, readableSql);
Message.BULK_UPDATE_CONFIRM.send(sender, label, id);
}
}
@@ -33,9 +33,6 @@ 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 net.kyori.adventure.text.Component;
import java.util.Map;
public class InfoCommand extends SingleCommand {
public InfoCommand() {
@@ -44,8 +41,7 @@ public class InfoCommand extends SingleCommand {
@Override
public void execute(LuckPermsPlugin plugin, Sender sender, ArgumentList args, String label) {
Map<Component, Component> storageMeta = plugin.getStorage().getMeta();
Message.INFO.send(sender, plugin, storageMeta);
Message.INFO.send(sender, plugin, plugin.getStorage().getMeta());
}
}
@@ -26,9 +26,6 @@
package me.lucko.luckperms.common.commands.misc;
import com.google.common.collect.Maps;
import me.lucko.luckperms.common.bulkupdate.comparison.Comparison;
import me.lucko.luckperms.common.bulkupdate.comparison.Constraint;
import me.lucko.luckperms.common.bulkupdate.comparison.StandardComparison;
import me.lucko.luckperms.common.cache.LoadingMap;
import me.lucko.luckperms.common.command.abstraction.SingleCommand;
import me.lucko.luckperms.common.command.access.CommandPermission;
@@ -36,6 +33,7 @@ import me.lucko.luckperms.common.command.spec.CommandSpec;
import me.lucko.luckperms.common.command.tabcomplete.TabCompleter;
import me.lucko.luckperms.common.command.tabcomplete.TabCompletions;
import me.lucko.luckperms.common.command.utils.ArgumentList;
import me.lucko.luckperms.common.filter.Comparison;
import me.lucko.luckperms.common.locale.Message;
import me.lucko.luckperms.common.model.HolderType;
import me.lucko.luckperms.common.node.comparator.NodeEntryComparator;
@@ -62,13 +60,13 @@ public class SearchCommand extends SingleCommand {
@Override
public void execute(LuckPermsPlugin plugin, Sender sender, ArgumentList args, String label) {
Comparison comparison = StandardComparison.parseComparison(args.get(0));
Comparison comparison = Comparison.parse(args.get(0));
if (comparison == null) {
comparison = StandardComparison.EQUAL;
comparison = Comparison.EQUAL;
args.add(0, "==");
}
ConstraintNodeMatcher<Node> matcher = StandardNodeMatchers.of(Constraint.of(comparison, args.get(1)));
ConstraintNodeMatcher<Node> matcher = StandardNodeMatchers.key(args.get(1), comparison);
int page = args.getIntOrDefault(2, 1);
Message.SEARCH_SEARCHING.send(sender, matcher.toString());
@@ -120,7 +118,7 @@ public class SearchCommand extends SingleCommand {
headerMessage.send(sender, page, pages.size(), results.size());
for (Map.Entry<String, NodeEntry<T, Node>> ent : mappedContent) {
Message.SEARCH_NODE_ENTRY.send(sender, comparison != StandardComparison.EQUAL, ent.getValue().getNode(), ent.getKey(), holderType, label, sender.getPlugin());
Message.SEARCH_NODE_ENTRY.send(sender, comparison != Comparison.EQUAL, ent.getValue().getNode(), ent.getKey(), holderType, label, sender.getPlugin());
}
}
}
@@ -53,7 +53,7 @@ public class TrackParentCommand extends ParentCommand<Track, String> {
.build(key -> new ReentrantLock());
public TrackParentCommand() {
super(CommandSpec.TRACK, "Track", Type.TAKES_ARGUMENT_FOR_TARGET, ImmutableList.<Command<Track>>builder()
super(CommandSpec.TRACK, "Track", Type.TARGETED, ImmutableList.<Command<Track>>builder()
.add(new TrackInfo())
.add(new TrackEditor())
.add(new TrackAppend())
@@ -62,7 +62,7 @@ public class UserParentCommand extends ParentCommand<User, UserIdentifier> {
.build(key -> new ReentrantLock());
public UserParentCommand() {
super(CommandSpec.USER, "User", Type.TAKES_ARGUMENT_FOR_TARGET, ImmutableList.<Command<User>>builder()
super(CommandSpec.USER, "User", Type.TARGETED, ImmutableList.<Command<User>>builder()
.add(new UserInfo())
.add(new CommandPermission<>(HolderType.USER))
.add(new CommandParent<>(HolderType.USER))
@@ -443,6 +443,11 @@ public final class ConfigKeys {
.collect(ImmutableCollectors.toList());
});
/**
* If log should be posted synchronously to storage/messaging in commands
*/
public static final ConfigKey<Boolean> LOG_SYNCHRONOUSLY_IN_COMMANDS = booleanKey("log-synchronously-in-commands", false);
/**
* If LuckPerms should automatically install translation bundles and periodically update them.
*/
@@ -755,4 +760,15 @@ public final class ConfigKeys {
return KEYS;
}
/**
* Check if the value at the given path should be censored in console/log output
*
* @param path the path
* @return true if the value should be censored
*/
public static boolean shouldCensorValue(final String path) {
final String lower = path.toLowerCase(Locale.ROOT);
return lower.contains("password") || lower.contains("uri");
}
}
@@ -25,6 +25,7 @@
package me.lucko.luckperms.common.config.generic.adapter;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -50,7 +51,8 @@ public class EnvironmentVariableConfigAdapter extends StringBasedConfigurationAd
String value = System.getenv(key);
if (value != null) {
this.plugin.getLogger().info("Resolved configuration value from environment variable: " + key + " = " + (path.contains("password") ? "*****" : value));
String printableValue = ConfigKeys.shouldCensorValue(path) ? "*****" : value;
this.plugin.getLogger().info(String.format("Resolved configuration value from environment variable: %s = %s", key, printableValue));
}
return value;
}
@@ -25,6 +25,7 @@
package me.lucko.luckperms.common.config.generic.adapter;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import org.checkerframework.checker.nullness.qual.Nullable;
@@ -46,7 +47,8 @@ public class SystemPropertyConfigAdapter extends StringBasedConfigurationAdapter
String value = System.getProperty(key);
if (value != null) {
this.plugin.getLogger().info("Resolved configuration value from system property: " + key + " = " + (path.contains("password") ? "*****" : value));
String printableValue = ConfigKeys.shouldCensorValue(path) ? "*****" : value;
this.plugin.getLogger().info(String.format("Resolved configuration value from system property: %s = %s", key, printableValue));
}
return value;
}
@@ -76,15 +76,15 @@ public enum Dependency {
ADVENTURE_PLATFORM_BUKKIT(
"me{}lucko",
"adventure-platform-bukkit",
"4.13.0",
"Rif/+xdGfRrlhxXYb2+jMFBnwnLQ2pnjAJ/BxWApins=",
"4.13.3",
"ZXw7pf+a6tjGdB2WO1rB/KQ+ETLAH8kQFSu3El7jopY=",
Relocation.of("adventure", "net{}kyori{}adventure")
),
ADVENTURE_PLATFORM_BUNGEECORD(
"me{}lucko",
"adventure-platform-bungeecord",
"4.13.0",
"MLk/qAgWC9YT2ImLq/sVo114V5Rk1jQr4jc57WAoO74=",
"4.13.3",
"7hnndD6dO6LZoRbtOBdn6OFK0y/T2PqNLHxCg6zaQlo=",
Relocation.of("adventure", "net{}kyori{}adventure")
),
EVENT(
@@ -58,6 +58,7 @@ import net.luckperms.api.event.log.LogNetworkPublishEvent;
import net.luckperms.api.event.log.LogNotifyEvent;
import net.luckperms.api.event.log.LogPublishEvent;
import net.luckperms.api.event.log.LogReceiveEvent;
import net.luckperms.api.event.messaging.CustomMessageReceiveEvent;
import net.luckperms.api.event.node.NodeAddEvent;
import net.luckperms.api.event.node.NodeClearEvent;
import net.luckperms.api.event.node.NodeMutateEvent;
@@ -70,9 +71,11 @@ import net.luckperms.api.event.player.lookup.UsernameLookupEvent;
import net.luckperms.api.event.player.lookup.UsernameValidityCheckEvent;
import net.luckperms.api.event.source.Source;
import net.luckperms.api.event.sync.ConfigReloadEvent;
import net.luckperms.api.event.sync.PostNetworkSyncEvent;
import net.luckperms.api.event.sync.PostSyncEvent;
import net.luckperms.api.event.sync.PreNetworkSyncEvent;
import net.luckperms.api.event.sync.PreSyncEvent;
import net.luckperms.api.event.sync.SyncType;
import net.luckperms.api.event.track.TrackCreateEvent;
import net.luckperms.api.event.track.TrackDeleteEvent;
import net.luckperms.api.event.track.TrackLoadAllEvent;
@@ -223,6 +226,10 @@ public final class EventDispatcher {
postAsync(LogReceiveEvent.class, id, entry);
}
public void dispatchCustomMessageReceive(String channelId, String payload) {
postAsync(CustomMessageReceiveEvent.class, channelId, payload);
}
public void dispatchNodeChanges(PermissionHolder target, DataType dataType, Difference<Node> changes) {
if (!this.eventBus.shouldPost(NodeAddEvent.class) && !this.eventBus.shouldPost(NodeRemoveEvent.class)) {
return;
@@ -270,12 +277,16 @@ public final class EventDispatcher {
postAsync(ConfigReloadEvent.class);
}
public void dispatchNetworkPostSync(UUID id, SyncType type, boolean didOccur, UUID specificUserUniqueId) {
postAsync(PostNetworkSyncEvent.class, id, type, didOccur, specificUserUniqueId);
}
public void dispatchPostSync() {
postAsync(PostSyncEvent.class);
}
public boolean dispatchNetworkPreSync(boolean initialState, UUID id) {
return postCancellable(PreNetworkSyncEvent.class, initialState, id);
public boolean dispatchNetworkPreSync(boolean initialState, UUID id, SyncType type, UUID specificUserUniqueId) {
return postCancellable(PreNetworkSyncEvent.class, initialState, id, type, specificUserUniqueId);
}
public boolean dispatchPreSync(boolean initialState) {
@@ -404,6 +415,7 @@ public final class EventDispatcher {
LogNotifyEvent.class,
LogPublishEvent.class,
LogReceiveEvent.class,
CustomMessageReceiveEvent.class,
NodeAddEvent.class,
NodeClearEvent.class,
NodeRemoveEvent.class,
@@ -414,6 +426,7 @@ public final class EventDispatcher {
UsernameLookupEvent.class,
UsernameValidityCheckEvent.class,
ConfigReloadEvent.class,
PostNetworkSyncEvent.class,
PostSyncEvent.class,
PreNetworkSyncEvent.class,
PreSyncEvent.class,
@@ -23,48 +23,60 @@
* SOFTWARE.
*/
package me.lucko.luckperms.common.bulkupdate.comparison;
package me.lucko.luckperms.common.filter;
import me.lucko.luckperms.common.bulkupdate.PreparedStatementBuilder;
import java.util.regex.Pattern;
/**
* A method of comparing two strings
*/
public interface Comparison {
public enum Comparison {
EQUAL("=="),
NOT_EQUAL("!="),
SIMILAR("~~"),
NOT_SIMILAR("!~");
public static final String WILDCARD = "%";
public static final String WILDCARD_ONE = "_";
private final String symbol;
Comparison(String symbol) {
this.symbol = symbol;
}
/**
* Gets the symbol which represents this comparison
*
* @return the comparison symbol
*/
String getSymbol();
public String getSymbol() {
return this.symbol;
}
/**
* Creates a {@link CompiledExpression} for the given expression
*
* @param expression the expression
* @return the compiled expression
*/
CompiledExpression compile(String expression);
@Override
public String toString() {
return this.symbol;
}
/**
* Returns the comparison operator in SQL form
*/
void appendSql(PreparedStatementBuilder builder);
public static Comparison parse(String s) {
for (Comparison t : values()) {
if (t.getSymbol().equals(s)) {
return t;
}
}
return null;
}
/**
* An instance of {@link Comparison} which is bound to an expression.
*/
interface CompiledExpression {
public static Pattern compilePatternForLikeSyntax(String expression) {
expression = expression.replace(".", "\\.");
/**
* Tests the expression against a given string, according to the
* rules of the parent {@link Comparison}.
*
* @param string the string
* @return if there was a match
*/
boolean test(String string);
// convert from SQL LIKE syntax to regex
expression = expression.replace(WILDCARD_ONE, ".");
expression = expression.replace(WILDCARD, ".*");
return Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
}
}
@@ -23,24 +23,28 @@
* SOFTWARE.
*/
package me.lucko.luckperms.common.bulkupdate.comparison;
package me.lucko.luckperms.common.filter;
import me.lucko.luckperms.common.bulkupdate.PreparedStatementBuilder;
import java.util.function.Predicate;
public class Constraint {
public static Constraint of(Comparison comparison, String expression) {
return new Constraint(comparison, expression);
}
public class Constraint<T> {
private final Comparison comparison;
private final String expressionValue;
private final Comparison.CompiledExpression compiledExpression;
private final T value;
private final Predicate<T> predicate;
private Constraint(Comparison comparison, String expression) {
Constraint(Comparison comparison, T value, Predicate<T> predicate) {
this.comparison = comparison;
this.expressionValue = expression;
this.compiledExpression = this.comparison.compile(this.expressionValue);
this.value = value;
this.predicate = predicate;
}
public Comparison comparison() {
return this.comparison;
}
public T value() {
return this.value;
}
/**
@@ -49,20 +53,12 @@ public class Constraint {
* @param value the value
* @return true if satisfied
*/
public boolean eval(String value) {
return this.compiledExpression.test(value);
}
public void appendSql(PreparedStatementBuilder builder, String field) {
// e.g. field LIKE ?
builder.append(field).append(' ');
this.comparison.appendSql(builder);
builder.append(' ');
builder.variable(this.expressionValue);
public boolean evaluate(T value) {
return this.predicate.test(value);
}
@Override
public String toString() {
return this.comparison + " " + this.expressionValue;
return this.comparison + " " + this.value;
}
}
@@ -0,0 +1,102 @@
/*
* 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.filter;
import java.util.UUID;
import java.util.function.Predicate;
import java.util.regex.Pattern;
public interface ConstraintFactory<T> {
Predicate<T> equal(T value);
Predicate<T> notEqual(T value);
Predicate<T> similar(T value);
Predicate<T> notSimilar(T value);
default Constraint<T> build(Comparison comparison, T value) {
switch (comparison) {
case EQUAL:
return new Constraint<>(comparison, value, equal(value));
case NOT_EQUAL:
return new Constraint<>(comparison, value, notEqual(value));
case SIMILAR:
return new Constraint<>(comparison, value, similar(value));
case NOT_SIMILAR:
return new Constraint<>(comparison, value, notSimilar(value));
default:
throw new AssertionError(comparison);
}
}
ConstraintFactory<String> STRINGS = new ConstraintFactory<String>() {
@Override
public Predicate<String> equal(String value) {
return value::equalsIgnoreCase;
}
@Override
public Predicate<String> notEqual(String value) {
return string -> !value.equalsIgnoreCase(string);
}
@Override
public Predicate<String> similar(String value) {
Pattern pattern = Comparison.compilePatternForLikeSyntax(value);
return string -> pattern.matcher(string).matches();
}
@Override
public Predicate<String> notSimilar(String value) {
Pattern pattern = Comparison.compilePatternForLikeSyntax(value);
return string -> !pattern.matcher(string).matches();
}
};
ConstraintFactory<UUID> UUIDS = new ConstraintFactory<UUID>() {
@Override
public Predicate<UUID> equal(UUID value) {
return value::equals;
}
@Override
public Predicate<UUID> notEqual(UUID value) {
return string -> !value.equals(string);
}
@Override
public Predicate<UUID> similar(UUID value) {
Pattern pattern = Comparison.compilePatternForLikeSyntax(value.toString());
return uuid -> pattern.matcher(uuid.toString()).matches();
}
@Override
public Predicate<UUID> notSimilar(UUID value) {
Pattern pattern = Comparison.compilePatternForLikeSyntax(value.toString());
return uuid -> !pattern.matcher(uuid.toString()).matches();
}
};
}
@@ -0,0 +1,59 @@
/*
* 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.filter;
public class Filter<T, FT> {
private final FilterField<T, FT> field;
private final Constraint<FT> constraint;
public Filter(FilterField<T, FT> field, Constraint<FT> constraint) {
this.field = field;
this.constraint = constraint;
}
public final FilterField<T, FT> field() {
return this.field;
}
public final Constraint<FT> constraint() {
return this.constraint;
}
/**
* Returns if the given value satisfies this filter
*
* @param value the value
* @return true if satisfied
*/
public boolean evaluate(T value) {
return this.constraint.evaluate(this.field.getValue(value));
}
@Override
public String toString() {
return this.field + " " + this.constraint;
}
}
@@ -0,0 +1,74 @@
/*
* 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.filter;
import java.util.function.Function;
/**
* Represents a field that can be filtered on.
*
* @param <T> the type the field is on
*/
public interface FilterField<T, FT> {
static <T, FT> FilterField<T, FT> named(String name, Function<T, FT> func) {
return new FilterField<T, FT>() {
@Override
public FT getValue(T object) {
return func.apply(object);
}
@Override
public String toString() {
return name;
}
};
}
/**
* Gets the value of this field on the given object.
*
* @param object the object
* @return the field value as a string
*/
FT getValue(T object);
default Filter<T, FT> isEqualTo(FT value, ConstraintFactory<FT> factory) {
return new Filter<>(this, factory.build(Comparison.EQUAL, value));
}
default Filter<T, FT> isNotEqualTo(FT value, ConstraintFactory<FT> factory) {
return new Filter<>(this, factory.build(Comparison.NOT_EQUAL, value));
}
default Filter<T, FT> isSimilarTo(FT value, ConstraintFactory<FT> factory) {
return new Filter<>(this, factory.build(Comparison.SIMILAR, value));
}
default Filter<T, FT> isNotSimilarTo(FT value, ConstraintFactory<FT> factory) {
return new Filter<>(this, factory.build(Comparison.NOT_SIMILAR, value));
}
}
@@ -0,0 +1,101 @@
/*
* 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.filter;
import com.google.common.collect.ForwardingList;
import com.google.common.collect.ImmutableList;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
public class FilterList<T> extends ForwardingList<Filter<T, ?>> {
public static <T> FilterList<T> empty() {
return new FilterList<>(LogicalOperator.AND, ImmutableList.of());
}
@SafeVarargs
public static <T> FilterList<T> and(Filter<T, ?>... filters) {
return new FilterList<>(LogicalOperator.AND, ImmutableList.copyOf(filters));
}
@SafeVarargs
public static <T> FilterList<T> or(Filter<T, ?>... filters) {
return new FilterList<>(LogicalOperator.OR, ImmutableList.copyOf(filters));
}
private final LogicalOperator operator;
private final List<Filter<T, ?>> filters;
public FilterList(LogicalOperator operator, List<Filter<T, ?>> filters) {
this.operator = operator;
this.filters = filters;
}
public LogicalOperator operator() {
return this.operator;
}
@Override
protected List<Filter<T, ?>> delegate() {
return this.filters;
}
/**
* Check to see if a value satisfies all (AND) or any (OR) filters in the list
*
* @param value the value to check
* @return true if satisfied
*/
public boolean evaluate(T value) {
return this.operator.match(this.filters, value);
}
@Override
public String toString() {
String operator = this.operator.name().toLowerCase(Locale.ROOT);
return this.filters.stream().map(Filter::toString).collect(Collectors.joining(" " + operator + " "));
}
public enum LogicalOperator {
AND {
@Override
public <T> boolean match(List<? extends Filter<T, ?>> filters, T value) {
return filters.stream().allMatch(filter -> filter.evaluate(value)); // true if empty
}
},
OR {
@Override
public <T> boolean match(List<? extends Filter<T, ?>> filters, T value) {
return filters.stream().anyMatch(filter -> filter.evaluate(value)); // false if empty
}
};
public abstract <T> boolean match(List<? extends Filter<T, ?>> filters, T value);
}
}
@@ -0,0 +1,79 @@
/*
* 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.filter;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
public class PageParameters {
private final int pageSize;
private final int pageNumber;
public PageParameters(int pageSize, int pageNumber) {
if (pageSize < 1) {
throw new IllegalArgumentException("pageSize cannot be less than 1: " + pageSize);
}
if (pageNumber < 1) {
throw new IllegalArgumentException("pageNumber cannot be less than 1: " + pageNumber);
}
this.pageSize = pageSize;
this.pageNumber = pageNumber;
}
public int pageSize() {
return this.pageSize;
}
public int pageNumber() {
return this.pageNumber;
}
public <T> List<T> paginate(List<T> input) {
int fromIndex = this.pageSize * (this.pageNumber - 1);
if (fromIndex >= input.size()) {
return Collections.emptyList();
}
int toIndex = Math.min(fromIndex + this.pageSize, input.size());
return input.subList(fromIndex, toIndex);
}
public <T> Stream<T> paginate(Stream<T> input) {
return input.skip((long) this.pageSize * (this.pageNumber - 1)).limit(this.pageSize);
}
public int getMaxPage(int totalEntries) {
if (totalEntries == 0) {
return 0;
}
return (totalEntries + this.pageSize - 1) / this.pageSize;
}
}
@@ -0,0 +1,87 @@
/*
* 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.filter.mongo;
import com.mongodb.client.FindIterable;
import com.mongodb.client.model.Filters;
import me.lucko.luckperms.common.filter.Comparison;
import me.lucko.luckperms.common.filter.Constraint;
import me.lucko.luckperms.common.filter.PageParameters;
import org.bson.conversions.Bson;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.regex.Pattern;
public class ConstraintMongoBuilder {
public static final ConstraintMongoBuilder INSTANCE = new ConstraintMongoBuilder();
protected ConstraintMongoBuilder() {
}
public Object mapConstraintValue(Object value) {
return value;
}
public Bson make(Constraint<?> constraint, String fieldName) {
Comparison comparison = constraint.comparison();
Object value = mapConstraintValue(constraint.value());
switch (comparison) {
case EQUAL:
return Filters.eq(fieldName, value);
case NOT_EQUAL:
return Filters.ne(fieldName, value);
case SIMILAR: {
if (!(value instanceof String)) {
throw new IllegalArgumentException("Unable to create SIMILAR comparison for non-string type: " + value.getClass().getName());
}
Pattern pattern = Comparison.compilePatternForLikeSyntax((String) value);
return Filters.regex(fieldName, pattern);
}
case NOT_SIMILAR: {
if (!(value instanceof String)) {
throw new IllegalArgumentException("Unable to create NOT_SIMILAR comparison for non-string type: " + value.getClass().getName());
}
Pattern pattern = Comparison.compilePatternForLikeSyntax((String) value);
return Filters.not(Filters.regex(fieldName, pattern));
}
default:
throw new AssertionError(comparison);
}
}
public static <R> FindIterable<R> page(@Nullable PageParameters params, FindIterable<R> iterable) {
if (params == null) {
return iterable;
}
int pageSize = params.pageSize();
int pageNumber = params.pageNumber();
return iterable.limit(pageSize).skip((pageNumber - 1) * pageSize);
}
}
@@ -0,0 +1,65 @@
/*
* 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.filter.mongo;
import com.mongodb.client.model.Filters;
import me.lucko.luckperms.common.filter.Filter;
import me.lucko.luckperms.common.filter.FilterField;
import me.lucko.luckperms.common.filter.FilterList;
import org.bson.conversions.Bson;
import java.util.List;
import java.util.stream.Collectors;
public abstract class FilterMongoBuilder<T> extends ConstraintMongoBuilder {
public abstract String mapFieldName(FilterField<T, ?> field);
public Bson make(Filter<T, ?> filter) {
return make(filter.constraint(), mapFieldName(filter.field()));
}
public Bson make(FilterList.LogicalOperator combineOperator, List<? extends Filter<T, ?>> filters) {
if (filters.isEmpty()) {
return Filters.empty();
}
List<Bson> bsonFilters = filters.stream().map(this::make).collect(Collectors.toList());
switch (combineOperator) {
case AND:
return Filters.and(bsonFilters);
case OR:
return Filters.or(bsonFilters);
default:
throw new AssertionError(combineOperator);
}
}
public Bson make(FilterList<T> filters) {
return make(filters.operator(), filters);
}
}
@@ -0,0 +1,84 @@
/*
* 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.filter.sql;
import me.lucko.luckperms.common.filter.Comparison;
import me.lucko.luckperms.common.filter.Constraint;
import me.lucko.luckperms.common.filter.PageParameters;
import me.lucko.luckperms.common.storage.implementation.sql.builder.AbstractSqlBuilder;
import org.checkerframework.checker.nullness.qual.Nullable;
public class ConstraintSqlBuilder extends AbstractSqlBuilder {
public void visitConstraintValue(Object value) {
if (value instanceof String) {
this.builder.variable(((String) value));
} else {
throw new IllegalArgumentException("Don't know how to write value with type: " + value.getClass().getName());
}
}
public void visit(Constraint<?> constraint) {
// '= value'
// '!= value'
// 'LIKE value'
// 'NOT LIKE value'
visit(constraint.comparison());
this.builder.append(' ');
visitConstraintValue(constraint.value());
}
public void visit(Comparison comparison) {
switch (comparison) {
case EQUAL:
this.builder.append("=");
break;
case NOT_EQUAL:
this.builder.append("!=");
break;
case SIMILAR:
this.builder.append("LIKE");
break;
case NOT_SIMILAR:
this.builder.append("NOT LIKE");
break;
default:
throw new AssertionError(comparison);
}
}
public void visit(@Nullable PageParameters params) {
if (params == null) {
return;
}
int pageSize = params.pageSize();
int pageNumber = params.pageNumber();
this.builder.append(" LIMIT " + pageSize + " OFFSET " + (pageNumber - 1) * pageSize);
}
}
@@ -0,0 +1,81 @@
/*
* 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.filter.sql;
import me.lucko.luckperms.common.filter.Filter;
import me.lucko.luckperms.common.filter.FilterField;
import me.lucko.luckperms.common.filter.FilterList;
import java.util.List;
public abstract class FilterSqlBuilder<T> extends ConstraintSqlBuilder {
public abstract void visitFieldName(FilterField<T, ?> field);
public void visit(Filter<T, ?> filter) {
// 'field = value'
// 'field != value'
// 'field LIKE value'
// 'field NOT LIKE value'
visitFieldName(filter.field());
this.builder.append(' ');
visit(filter.constraint());
}
public void visit(FilterList.LogicalOperator combineOperator, List<? extends Filter<T, ?>> filters) {
if (filters.isEmpty()) {
return;
}
String combineString;
switch (combineOperator) {
case AND:
combineString = "AND ";
break;
case OR:
combineString = "OR ";
break;
default:
throw new AssertionError(combineOperator);
}
this.builder.append(" WHERE");
for (int i = 0; i < filters.size(); i++) {
Filter<T, ?> filter = filters.get(i);
this.builder.append(" ");
if (i != 0) {
this.builder.append(combineString);
}
visit(filter);
}
}
public void visit(FilterList<T> filters) {
visit(filters.operator(), filters);
}
}
@@ -36,6 +36,7 @@ import me.lucko.luckperms.common.plugin.AbstractLuckPermsPlugin;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.plugin.bootstrap.LuckPermsBootstrap;
import me.lucko.luckperms.common.sender.Sender;
import me.lucko.luckperms.common.storage.StorageMetadata;
import me.lucko.luckperms.common.util.DurationFormatter;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.ComponentLike;
@@ -55,6 +56,7 @@ import net.luckperms.api.node.types.InheritanceNode;
import net.luckperms.api.node.types.MetaNode;
import net.luckperms.api.util.Tristate;
import java.text.DecimalFormat;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
@@ -298,7 +300,7 @@ public interface Message {
.append(text()
.color(DARK_GRAY)
.append(text('['))
.append(text(LoggedAction.getTypeCharacter(action.getTarget().getType()), GREEN))
.append(text(LoggedAction.getTypeString(action.getTarget().getType()), GREEN))
.append(text(']'))
)
.append(space())
@@ -1535,7 +1537,7 @@ public interface Message {
)
);
Args2<LuckPermsPlugin, Map<Component, Component>> INFO = (plugin, storageMeta) -> joinNewline(
Args2<LuckPermsPlugin, StorageMetadata> INFO = (plugin, storageMeta) -> joinNewline(
// "&2Running &bLuckPerms v{}&2 by &bLuck&2."
// "&f- &3Platform: &f{}"
// "&f- &3Server Brand: &f{}"
@@ -1598,14 +1600,39 @@ public interface Message {
.append(text(plugin.getStorage().getName(), WHITE))
);
for (Map.Entry<Component, Component> metaEntry : storageMeta.entrySet()) {
if (storageMeta.connected() != null) {
builder.append(newline());
builder.append(prefixed(text()
.color(DARK_AQUA)
.append(text(" "))
.append(metaEntry.getKey())
.append(translatable("luckperms.command.info.storage.meta.connected-key"))
.append(text(": "))
.append(metaEntry.getValue())
.append(formatBoolean(storageMeta.connected()))
));
}
if (storageMeta.ping() != null) {
builder.append(newline());
builder.append(prefixed(text()
.color(DARK_AQUA)
.append(text(" "))
.append(translatable("luckperms.command.info.storage.meta.ping-key"))
.append(text(": "))
.append(text(storageMeta.ping() + "ms", GREEN))
));
}
if (storageMeta.sizeBytes() != null) {
DecimalFormat format = new DecimalFormat("#.##");
String size = format.format(storageMeta.sizeBytes() / 1048576D) + "MB";
builder.append(newline());
builder.append(prefixed(text()
.color(DARK_AQUA)
.append(text(" "))
.append(translatable("luckperms.command.info.storage.meta.file-size-key"))
.append(text(": "))
.append(text(size, GREEN))
));
}
})),
@@ -3751,7 +3778,7 @@ public interface Message {
.append(text()
.color(DARK_GRAY)
.append(text('['))
.append(text(LoggedAction.getTypeCharacter(action.getTarget().getType()), GREEN))
.append(text(LoggedAction.getTypeString(action.getTarget().getType()), GREEN))
.append(text(']'))
)
.append(space())
@@ -31,6 +31,8 @@ import net.luckperms.api.actionlog.Action;
import net.luckperms.api.messenger.Messenger;
import net.luckperms.api.messenger.MessengerProvider;
import java.util.concurrent.CompletableFuture;
public interface InternalMessagingService {
/**
@@ -60,20 +62,28 @@ public interface InternalMessagingService {
* Uses the messaging service to inform other servers about a general
* change.
*/
void pushUpdate();
CompletableFuture<Void> pushUpdate();
/**
* Pushes an update for a specific user.
*
* @param user the user
*/
void pushUserUpdate(User user);
CompletableFuture<Void> pushUserUpdate(User user);
/**
* Pushes a log entry to connected servers.
*
* @param logEntry the log entry
*/
void pushLog(Action logEntry);
CompletableFuture<Void> pushLog(Action logEntry);
/**
* Pushes a custom payload to connected servers.
*
* @param channelId the channel id
* @param payload the payload
*/
CompletableFuture<Void> pushCustomPayload(String channelId, String payload);
}
@@ -31,19 +31,23 @@ import me.lucko.luckperms.common.actionlog.LoggedAction;
import me.lucko.luckperms.common.cache.BufferedRequest;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.messaging.message.ActionLogMessageImpl;
import me.lucko.luckperms.common.messaging.message.CustomMessageImpl;
import me.lucko.luckperms.common.messaging.message.UpdateMessageImpl;
import me.lucko.luckperms.common.messaging.message.UserUpdateMessageImpl;
import me.lucko.luckperms.common.model.User;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.util.AsyncInterface;
import me.lucko.luckperms.common.util.ExpiringSet;
import me.lucko.luckperms.common.util.gson.GsonProvider;
import me.lucko.luckperms.common.util.gson.JObject;
import net.luckperms.api.actionlog.Action;
import net.luckperms.api.event.sync.SyncType;
import net.luckperms.api.messenger.IncomingMessageConsumer;
import net.luckperms.api.messenger.Messenger;
import net.luckperms.api.messenger.MessengerProvider;
import net.luckperms.api.messenger.message.Message;
import net.luckperms.api.messenger.message.type.ActionLogMessage;
import net.luckperms.api.messenger.message.type.CustomMessage;
import net.luckperms.api.messenger.message.type.UpdateMessage;
import net.luckperms.api.messenger.message.type.UserUpdateMessage;
import org.checkerframework.checker.nullness.qual.NonNull;
@@ -51,9 +55,10 @@ import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class LuckPermsMessagingService implements InternalMessagingService, IncomingMessageConsumer {
public class LuckPermsMessagingService extends AsyncInterface implements InternalMessagingService, IncomingMessageConsumer {
private final LuckPermsPlugin plugin;
private final ExpiringSet<UUID> receivedMessages;
private final PushUpdateBuffer updateBuffer;
@@ -62,13 +67,14 @@ public class LuckPermsMessagingService implements InternalMessagingService, Inco
private final Messenger messenger;
public LuckPermsMessagingService(LuckPermsPlugin plugin, MessengerProvider messengerProvider) {
super(plugin);
this.plugin = plugin;
this.messengerProvider = messengerProvider;
this.messenger = messengerProvider.obtain(this);
Objects.requireNonNull(this.messenger, "messenger");
this.receivedMessages = new ExpiringSet<>(1, TimeUnit.HOURS);
this.receivedMessages = new ExpiringSet<>(5, TimeUnit.MINUTES);
this.updateBuffer = new PushUpdateBuffer(plugin);
}
@@ -104,8 +110,8 @@ public class LuckPermsMessagingService implements InternalMessagingService, Inco
}
@Override
public void pushUpdate() {
this.plugin.getBootstrap().getScheduler().executeAsync(() -> {
public CompletableFuture<Void> pushUpdate() {
return future(() -> {
UUID requestId = generatePingId();
this.plugin.getLogger().info("[Messaging] Sending ping with id: " + requestId);
this.messenger.sendOutgoingMessage(new UpdateMessageImpl(requestId));
@@ -113,8 +119,8 @@ public class LuckPermsMessagingService implements InternalMessagingService, Inco
}
@Override
public void pushUserUpdate(User user) {
this.plugin.getBootstrap().getScheduler().executeAsync(() -> {
public CompletableFuture<Void> pushUserUpdate(User user) {
return future(() -> {
UUID requestId = generatePingId();
this.plugin.getLogger().info("[Messaging] Sending user ping for '" + user.getPlainDisplayName() + "' with id: " + requestId);
this.messenger.sendOutgoingMessage(new UserUpdateMessageImpl(requestId, user.getUniqueId()));
@@ -122,8 +128,8 @@ public class LuckPermsMessagingService implements InternalMessagingService, Inco
}
@Override
public void pushLog(Action logEntry) {
this.plugin.getBootstrap().getScheduler().executeAsync(() -> {
public CompletableFuture<Void> pushLog(Action logEntry) {
return future(() -> {
UUID requestId = generatePingId();
if (this.plugin.getEventDispatcher().dispatchLogNetworkPublish(!this.plugin.getConfiguration().get(ConfigKeys.PUSH_LOG_ENTRIES), requestId, logEntry)) {
@@ -135,6 +141,14 @@ public class LuckPermsMessagingService implements InternalMessagingService, Inco
});
}
@Override
public CompletableFuture<Void> pushCustomPayload(String channelId, String payload) {
return future(() -> {
UUID requestId = generatePingId();
this.messenger.sendOutgoingMessage(new CustomMessageImpl(requestId, channelId, payload));
});
}
@Override
public boolean consumeIncomingMessage(@NonNull Message message) {
Objects.requireNonNull(message, "message");
@@ -146,7 +160,8 @@ public class LuckPermsMessagingService implements InternalMessagingService, Inco
// determine if the message can be handled by us
boolean valid = message instanceof UpdateMessage ||
message instanceof UserUpdateMessage ||
message instanceof ActionLogMessage;
message instanceof ActionLogMessage ||
message instanceof CustomMessage;
// instead of throwing an exception here, just return false
// it means an instance of LP can gracefully handle messages it doesn't
@@ -208,6 +223,9 @@ public class LuckPermsMessagingService implements InternalMessagingService, Inco
case ActionLogMessageImpl.TYPE:
decoded = ActionLogMessageImpl.decode(content, id);
break;
case CustomMessageImpl.TYPE:
decoded = CustomMessageImpl.decode(content, id);
break;
default:
// gracefully return if we just don't recognise the type
return false;
@@ -235,34 +253,46 @@ public class LuckPermsMessagingService implements InternalMessagingService, Inco
private void processIncomingMessage(Message message) {
if (message instanceof UpdateMessage) {
UpdateMessage msg = (UpdateMessage) message;
UUID msgId = msg.getId();
this.plugin.getLogger().info("[Messaging] Received update ping with id: " + msg.getId());
if (this.plugin.getEventDispatcher().dispatchNetworkPreSync(false, msg.getId())) {
if (this.plugin.getEventDispatcher().dispatchNetworkPreSync(false, msgId, SyncType.FULL, null)) {
return;
}
this.plugin.getSyncTaskBuffer().request();
this.plugin.getLogger().info("[Messaging] Received update ping with id: " + msgId);
this.plugin.getSyncTaskBuffer().request()
.thenRunAsync(() -> this.plugin.getEventDispatcher().dispatchNetworkPostSync(msgId, SyncType.FULL, true, null));
} else if (message instanceof UserUpdateMessage) {
UserUpdateMessage msg = (UserUpdateMessage) message;
UUID msgId = msg.getId();
UUID userUniqueId = msg.getUserUniqueId();
User user = this.plugin.getUserManager().getIfLoaded(msg.getUserUniqueId());
if (this.plugin.getEventDispatcher().dispatchNetworkPreSync(false, msgId, SyncType.SPECIFIC_USER, userUniqueId)) {
return;
}
User user = this.plugin.getUserManager().getIfLoaded(userUniqueId);
if (user == null) {
this.plugin.getEventDispatcher().dispatchNetworkPostSync(msgId, SyncType.SPECIFIC_USER, false, userUniqueId);
return;
}
this.plugin.getLogger().info("[Messaging] Received user update ping for '" + user.getPlainDisplayName() + "' with id: " + msg.getId());
if (this.plugin.getEventDispatcher().dispatchNetworkPreSync(false, msg.getId())) {
return;
}
this.plugin.getStorage().loadUser(user.getUniqueId(), null);
this.plugin.getLogger().info("[Messaging] Received user update ping for '" + user.getPlainDisplayName() + "' with id: " + msgId);
this.plugin.getStorage().loadUser(user.getUniqueId(), null)
.thenRunAsync(() -> this.plugin.getEventDispatcher().dispatchNetworkPostSync(msgId, SyncType.SPECIFIC_USER, true, userUniqueId));
} else if (message instanceof ActionLogMessage) {
ActionLogMessage msg = (ActionLogMessage) message;
this.plugin.getEventDispatcher().dispatchLogReceive(msg.getId(), msg.getAction());
this.plugin.getLogDispatcher().dispatchFromRemote((LoggedAction) msg.getAction());
this.plugin.getLogDispatcher().broadcastFromRemote((LoggedAction) msg.getAction());
} else if (message instanceof CustomMessage) {
CustomMessage msg = (CustomMessage) message;
this.plugin.getEventDispatcher().dispatchCustomMessageReceive(msg.getChannelId(), msg.getPayload());
} else {
throw new IllegalArgumentException("Unknown message type: " + message.getClass().getName());
}
@@ -0,0 +1,85 @@
/*
* 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.messaging.message;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import me.lucko.luckperms.common.messaging.LuckPermsMessagingService;
import me.lucko.luckperms.common.util.gson.JObject;
import net.luckperms.api.messenger.message.type.CustomMessage;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.UUID;
public class CustomMessageImpl extends AbstractMessage implements CustomMessage {
public static final String TYPE = "custom";
public static CustomMessageImpl decode(@Nullable JsonElement content, UUID id) {
if (content == null) {
throw new IllegalStateException("Missing content");
}
JsonObject obj = content.getAsJsonObject();
if (!obj.has("channelId")) {
throw new IllegalStateException("Incoming message has no 'channelId' argument: " + content);
}
if (!obj.has("payload")) {
throw new IllegalStateException("Incoming message has no 'payload' argument: " + content);
}
String channelId = obj.get("channelId").getAsString();
String payload = obj.get("payload").getAsString();
return new CustomMessageImpl(id, channelId, payload);
}
private final String channelId;
private final String payload;
public CustomMessageImpl(UUID id, String channelId, String payload) {
super(id);
this.channelId = channelId;
this.payload = payload;
}
@Override
public @NonNull String getChannelId() {
return this.channelId;
}
@Override
public @NonNull String getPayload() {
return this.payload;
}
@Override
public @NonNull String asEncodedString() {
return LuckPermsMessagingService.encodeMessageAsString(
TYPE, getId(), new JObject().add("channelId", this.channelId).add("payload", this.payload).toJson()
);
}
}
@@ -25,7 +25,9 @@
package me.lucko.luckperms.common.node.matcher;
import me.lucko.luckperms.common.bulkupdate.comparison.Constraint;
import me.lucko.luckperms.common.filter.Comparison;
import me.lucko.luckperms.common.filter.Constraint;
import me.lucko.luckperms.common.filter.ConstraintFactory;
import net.luckperms.api.node.Node;
import net.luckperms.api.node.matcher.NodeMatcher;
import org.checkerframework.checker.nullness.qual.NonNull;
@@ -35,20 +37,20 @@ import org.checkerframework.checker.nullness.qual.Nullable;
* Abstract implementation of {@link NodeMatcher} backed by a {@link Constraint}.
*/
public abstract class ConstraintNodeMatcher<T extends Node> implements NodeMatcher<T> {
private final Constraint constraint;
private final Constraint<String> constraint;
protected ConstraintNodeMatcher(Constraint constraint) {
this.constraint = constraint;
protected ConstraintNodeMatcher(Comparison comparison, String value) {
this.constraint = ConstraintFactory.STRINGS.build(comparison, value);
}
public Constraint getConstraint() {
public Constraint<String> getConstraint() {
return this.constraint;
}
public abstract @Nullable T filterConstraintMatch(@NonNull Node node);
public @Nullable T match(Node node) {
return getConstraint().eval(node.getKey()) ? filterConstraintMatch(node) : null;
return getConstraint().evaluate(node.getKey()) ? filterConstraintMatch(node) : null;
}
@Override
@@ -25,8 +25,7 @@
package me.lucko.luckperms.common.node.matcher;
import me.lucko.luckperms.common.bulkupdate.comparison.Constraint;
import me.lucko.luckperms.common.bulkupdate.comparison.StandardComparison;
import me.lucko.luckperms.common.filter.Comparison;
import me.lucko.luckperms.common.node.AbstractNode;
import me.lucko.luckperms.common.node.types.DisplayName;
import me.lucko.luckperms.common.node.types.Inheritance;
@@ -45,12 +44,12 @@ import org.checkerframework.checker.nullness.qual.Nullable;
public final class StandardNodeMatchers {
private StandardNodeMatchers() {}
public static ConstraintNodeMatcher<Node> of(Constraint constraint) {
return new Generic(constraint);
public static ConstraintNodeMatcher<Node> key(String value, Comparison comparison) {
return new Generic(comparison, value);
}
public static ConstraintNodeMatcher<Node> key(String key) {
return new Generic(Constraint.of(StandardComparison.EQUAL, key));
return new Generic(Comparison.EQUAL, key);
}
public static <T extends Node> ConstraintNodeMatcher<T> key(T node) {
@@ -58,7 +57,7 @@ public final class StandardNodeMatchers {
}
public static ConstraintNodeMatcher<Node> keyStartsWith(String startsWith) {
return new Generic(Constraint.of(StandardComparison.SIMILAR, startsWith + StandardComparison.WILDCARD));
return new Generic(Comparison.SIMILAR, startsWith + Comparison.WILDCARD);
}
public static <T extends Node> ConstraintNodeMatcher<T> equals(T other, NodeEqualityPredicate equalityPredicate) {
@@ -74,8 +73,8 @@ public final class StandardNodeMatchers {
}
private static class Generic extends ConstraintNodeMatcher<Node> {
Generic(Constraint constraint) {
super(constraint);
Generic(Comparison comparison, String value) {
super(comparison, value);
}
@Override
@@ -89,7 +88,7 @@ public final class StandardNodeMatchers {
private final NodeEqualityPredicate equalityPredicate;
NodeEquals(T node, NodeEqualityPredicate equalityPredicate) {
super(Constraint.of(StandardComparison.EQUAL, node.getKey()));
super(Comparison.EQUAL, node.getKey());
this.node = node;
this.equalityPredicate = equalityPredicate;
}
@@ -106,7 +105,7 @@ public final class StandardNodeMatchers {
private static final class MetaKeyEquals extends ConstraintNodeMatcher<MetaNode> {
MetaKeyEquals(String metaKey) {
super(Constraint.of(StandardComparison.SIMILAR, Meta.key(metaKey, StandardComparison.WILDCARD)));
super(Comparison.SIMILAR, Meta.key(metaKey, Comparison.WILDCARD));
}
@Override
@@ -118,8 +117,8 @@ public final class StandardNodeMatchers {
private static final class TypeEquals<T extends Node> extends ConstraintNodeMatcher<T> {
private final NodeType<? extends T> type;
protected TypeEquals(NodeType<? extends T> type) {
super(getConstraintForType(type));
TypeEquals(NodeType<? extends T> type) {
super(Comparison.SIMILAR, getSimilarToComparisonValue(type));
this.type = type;
}
@@ -128,21 +127,21 @@ public final class StandardNodeMatchers {
return this.type.tryCast(node).orElse(null);
}
private static Constraint getConstraintForType(NodeType<?> type) {
private static String getSimilarToComparisonValue(NodeType<?> type) {
if (type == NodeType.REGEX_PERMISSION) {
return Constraint.of(StandardComparison.SIMILAR, RegexPermission.key(StandardComparison.WILDCARD));
return RegexPermission.key(Comparison.WILDCARD);
} else if (type == NodeType.INHERITANCE) {
return Constraint.of(StandardComparison.SIMILAR, Inheritance.key(StandardComparison.WILDCARD));
return Inheritance.key(Comparison.WILDCARD);
} else if (type == NodeType.PREFIX) {
return Constraint.of(StandardComparison.SIMILAR, Prefix.NODE_MARKER + StandardComparison.WILDCARD + AbstractNode.NODE_SEPARATOR + StandardComparison.WILDCARD);
return Prefix.NODE_MARKER + Comparison.WILDCARD + AbstractNode.NODE_SEPARATOR + Comparison.WILDCARD;
} else if (type == NodeType.SUFFIX) {
return Constraint.of(StandardComparison.SIMILAR, Suffix.NODE_MARKER + StandardComparison.WILDCARD + AbstractNode.NODE_SEPARATOR + StandardComparison.WILDCARD);
return Suffix.NODE_MARKER + Comparison.WILDCARD + AbstractNode.NODE_SEPARATOR + Comparison.WILDCARD;
} else if (type == NodeType.META) {
return Constraint.of(StandardComparison.SIMILAR, Meta.key(StandardComparison.WILDCARD, StandardComparison.WILDCARD));
return Meta.key(Comparison.WILDCARD, Comparison.WILDCARD);
} else if (type == NodeType.WEIGHT) {
return Constraint.of(StandardComparison.SIMILAR, Weight.NODE_MARKER + StandardComparison.WILDCARD);
return Weight.NODE_MARKER + Comparison.WILDCARD;
} else if (type == NodeType.DISPLAY_NAME) {
return Constraint.of(StandardComparison.SIMILAR, DisplayName.key(StandardComparison.WILDCARD));
return DisplayName.key(Comparison.WILDCARD);
}
throw new IllegalArgumentException("Unable to create a NodeMatcher for NodeType " + type.name());
@@ -52,8 +52,10 @@ import me.lucko.luckperms.common.locale.TranslationRepository;
import me.lucko.luckperms.common.messaging.InternalMessagingService;
import me.lucko.luckperms.common.messaging.MessagingFactory;
import me.lucko.luckperms.common.plugin.logging.PluginLogger;
import me.lucko.luckperms.common.plugin.util.HealthCheckResult;
import me.lucko.luckperms.common.storage.Storage;
import me.lucko.luckperms.common.storage.StorageFactory;
import me.lucko.luckperms.common.storage.StorageMetadata;
import me.lucko.luckperms.common.storage.implementation.file.watcher.FileWatcher;
import me.lucko.luckperms.common.storage.misc.DataConstraints;
import me.lucko.luckperms.common.tasks.CacheHousekeepingTask;
@@ -64,6 +66,7 @@ import me.lucko.luckperms.common.verbose.VerboseHandler;
import me.lucko.luckperms.common.webeditor.socket.WebEditorSocket;
import me.lucko.luckperms.common.webeditor.store.WebEditorStore;
import net.luckperms.api.LuckPerms;
import net.luckperms.api.platform.Health;
import okhttp3.OkHttpClient;
import java.io.IOException;
@@ -74,8 +77,11 @@ import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.Month;
import java.util.Collections;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
@@ -107,6 +113,8 @@ public abstract class AbstractLuckPermsPlugin implements LuckPermsPlugin {
private EventDispatcher eventDispatcher;
private SimpleExtensionManager extensionManager;
private boolean running = false;
/**
* Performs the initial actions to load the plugin
*/
@@ -248,6 +256,9 @@ public abstract class AbstractLuckPermsPlugin implements LuckPermsPlugin {
// perform any platform-specific final setup tasks
performFinalSetup();
// mark as running
this.running = true;
Duration timeTaken = Duration.between(getBootstrap().getStartupTime(), Instant.now());
getLogger().info("Successfully enabled. (took " + timeTaken.toMillis() + "ms)");
}
@@ -272,6 +283,9 @@ public abstract class AbstractLuckPermsPlugin implements LuckPermsPlugin {
// unload extensions
this.extensionManager.close();
// mark as not running
this.running = false;
// remove any hooks into the platform
removePlatformHooks();
@@ -383,6 +397,31 @@ public abstract class AbstractLuckPermsPlugin implements LuckPermsPlugin {
}
}
@Override
public Health runHealthCheck() {
if (!this.running) {
return HealthCheckResult.unhealthy(Collections.emptyMap());
}
StorageMetadata meta = this.storage.getMeta();
if (meta.connected() != null && !meta.connected()) {
return HealthCheckResult.unhealthy(Collections.singletonMap("reason", "storage disconnected"));
}
Map<String, Object> map = new LinkedHashMap<>();
if (meta.connected() != null) {
map.put("storageConnected", meta.connected());
}
if (meta.ping() != null) {
map.put("storagePing", meta.ping());
}
if (meta.sizeBytes() != null) {
map.put("storageSizeBytes", meta.sizeBytes());
}
return HealthCheckResult.healthy(map);
}
@Override
public Optional<UUID> lookupUniqueId(String username) {
// get a result from the DB cache
@@ -57,6 +57,7 @@ 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 net.luckperms.api.platform.Health;
import net.luckperms.api.query.QueryOptions;
import java.util.Collections;
@@ -263,6 +264,13 @@ public interface LuckPermsPlugin {
*/
WebEditorStore getWebEditorStore();
/**
* Runs a health check for the plugin.
*
* @return the result of the healthcheck
*/
Health runHealthCheck();
/**
* Gets a calculated context instance for the user using the rules of the platform.
*
@@ -0,0 +1,67 @@
/*
* 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.plugin.util;
import com.google.gson.Gson;
import net.luckperms.api.platform.Health;
import java.util.Map;
public class HealthCheckResult implements Health {
private static final Gson GSON = new Gson();
public static HealthCheckResult healthy(Map<String, Object> details) {
return new HealthCheckResult(true, details);
}
public static HealthCheckResult unhealthy(Map<String, Object> details) {
return new HealthCheckResult(false, details);
}
private final boolean healthy;
private final Map<String, Object> details;
HealthCheckResult(boolean healthy, Map<String, Object> details) {
this.healthy = healthy;
this.details = details;
}
@Override
public boolean isHealthy() {
return this.healthy;
}
@Override
public Map<String, Object> getDetails() {
return this.details;
}
@Override
public String toString() {
return GSON.toJson(this);
}
}
@@ -78,7 +78,7 @@ public final class AbstractSender<T> implements Sender {
@Override
public void sendMessage(Component message) {
if (isConsole()) {
if (this.factory.shouldSplitNewlines(this.sender)) {
for (Component line : splitNewlines(message)) {
this.factory.sendMessage(this.sender, line);
}
@@ -89,12 +89,12 @@ public final class AbstractSender<T> implements Sender {
@Override
public Tristate getPermissionValue(String permission) {
return (isConsole() && this.factory.consoleHasAllPermissions()) ? Tristate.TRUE : this.factory.getPermissionValue(this.sender, permission);
return isConsole() ? Tristate.TRUE : this.factory.getPermissionValue(this.sender, permission);
}
@Override
public boolean hasPermission(String permission) {
return (isConsole() && this.factory.consoleHasAllPermissions()) || this.factory.hasPermission(this.sender, permission);
return isConsole() || this.factory.hasPermission(this.sender, permission);
}
@Override
@@ -63,8 +63,8 @@ public abstract class SenderFactory<P extends LuckPermsPlugin, T> implements Aut
protected abstract boolean isConsole(T sender);
protected boolean consoleHasAllPermissions() {
return true;
protected boolean shouldSplitNewlines(T sender) {
return isConsole(sender);
}
public final Sender wrap(T sender) {
@@ -26,8 +26,10 @@
package me.lucko.luckperms.common.storage;
import com.google.common.collect.ImmutableList;
import me.lucko.luckperms.common.actionlog.Log;
import me.lucko.luckperms.common.actionlog.LogPage;
import me.lucko.luckperms.common.bulkupdate.BulkUpdate;
import me.lucko.luckperms.common.filter.FilterList;
import me.lucko.luckperms.common.filter.PageParameters;
import me.lucko.luckperms.common.model.Group;
import me.lucko.luckperms.common.model.Track;
import me.lucko.luckperms.common.model.User;
@@ -36,13 +38,13 @@ import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.storage.implementation.StorageImplementation;
import me.lucko.luckperms.common.storage.implementation.split.SplitStorage;
import me.lucko.luckperms.common.storage.misc.NodeEntry;
import me.lucko.luckperms.common.util.Throwing;
import net.kyori.adventure.text.Component;
import me.lucko.luckperms.common.util.AsyncInterface;
import net.luckperms.api.actionlog.Action;
import net.luckperms.api.event.cause.CreationCause;
import net.luckperms.api.event.cause.DeletionCause;
import net.luckperms.api.model.PlayerSaveResult;
import net.luckperms.api.node.Node;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.Collection;
import java.util.Collections;
@@ -52,18 +54,17 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
/**
* Provides a {@link CompletableFuture} based API for interacting with a {@link StorageImplementation}.
*/
public class Storage {
public class Storage extends AsyncInterface {
private final LuckPermsPlugin plugin;
private final StorageImplementation implementation;
public Storage(LuckPermsPlugin plugin, StorageImplementation implementation) {
super(plugin);
this.plugin = plugin;
this.implementation = implementation;
}
@@ -80,32 +81,6 @@ public class Storage {
}
}
private <T> CompletableFuture<T> future(Callable<T> supplier) {
return CompletableFuture.supplyAsync(() -> {
try {
return supplier.call();
} catch (Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new CompletionException(e);
}
}, this.plugin.getBootstrap().getScheduler().async());
}
private CompletableFuture<Void> future(Throwing.Runnable runnable) {
return CompletableFuture.runAsync(() -> {
try {
runnable.run();
} catch (Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new CompletionException(e);
}
}, this.plugin.getBootstrap().getScheduler().async());
}
public String getName() {
return this.implementation.getImplementationName();
}
@@ -126,7 +101,7 @@ public class Storage {
}
}
public Map<Component, Component> getMeta() {
public StorageMetadata getMeta() {
return this.implementation.getMeta();
}
@@ -134,8 +109,8 @@ public class Storage {
return future(() -> this.implementation.logAction(entry));
}
public CompletableFuture<Log> getLog() {
return future(this.implementation::getLog);
public CompletableFuture<LogPage> getLogPage(FilterList<Action> filters, @Nullable PageParameters page) {
return future(() -> this.implementation.getLogPage(filters, page));
}
public CompletableFuture<Void> applyBulkUpdate(BulkUpdate bulkUpdate) {
@@ -0,0 +1,77 @@
/*
* 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.storage;
public class StorageMetadata {
// remote
private Boolean connected;
private Integer ping;
// local
private Long sizeBytes;
public Boolean connected() {
return this.connected;
}
public Integer ping() {
return this.ping;
}
public Long sizeBytes() {
return this.sizeBytes;
}
public StorageMetadata connected(boolean connected) {
this.connected = connected;
return this;
}
public StorageMetadata ping(int ping) {
this.ping = ping;
return this;
}
public StorageMetadata sizeBytes(long sizeBytes) {
this.sizeBytes = sizeBytes;
return this;
}
public StorageMetadata combine(StorageMetadata other) {
if (this.connected == null || (other.connected != null && !other.connected)) {
this.connected = other.connected;
}
if (this.ping == null || (other.ping != null && other.ping > this.ping)) {
this.ping = other.ping;
}
if (this.sizeBytes == null || (other.sizeBytes != null && other.sizeBytes > this.sizeBytes)) {
this.sizeBytes = other.sizeBytes;
}
return this;
}
}
@@ -25,21 +25,22 @@
package me.lucko.luckperms.common.storage.implementation;
import me.lucko.luckperms.common.actionlog.Log;
import me.lucko.luckperms.common.actionlog.LogPage;
import me.lucko.luckperms.common.bulkupdate.BulkUpdate;
import me.lucko.luckperms.common.filter.FilterList;
import me.lucko.luckperms.common.filter.PageParameters;
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.node.matcher.ConstraintNodeMatcher;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.storage.StorageMetadata;
import me.lucko.luckperms.common.storage.misc.NodeEntry;
import net.kyori.adventure.text.Component;
import net.luckperms.api.actionlog.Action;
import net.luckperms.api.model.PlayerSaveResult;
import net.luckperms.api.node.Node;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -55,13 +56,11 @@ public interface StorageImplementation {
void shutdown();
default Map<Component, Component> getMeta() {
return Collections.emptyMap();
}
StorageMetadata getMeta();
void logAction(Action entry) throws Exception;
Log getLog() throws Exception;
LogPage getLogPage(FilterList<Action> filters, @Nullable PageParameters page) throws Exception;
void applyBulkUpdate(BulkUpdate bulkUpdate) throws Exception;
Loaded 100 of 181 files, more files were not shown because too many files have changed in this diff. Show more