Skip to content

Public API

alexisleder edited this page Sep 27, 2026 · 2 revisions

LederProtections Public API

LederProtections exposes public API contract 1.0 for addons such as LederFly and sell-wand integrations. The public contract lives in the separate LederAPI repository; the private LederProtections project contains only its implementation. Consumers must keep the API out of their own jar and isolate optional integration code so their plugin can still load when LederProtections is absent.

The current LederProtections release is 1.4.1; it does not change the API contract or artifact version. Find the source and build instructions in the LederAPI repository.

Compile-only artifact

The lederprotections-api module publishes these coordinates:

com.alexisleder:lederprotections-api:1.0.0

The API jar contains only interfaces, immutable models and Bukkit events below com.alexisleder.lederprotections.api. It never contains api.internal or plugin implementation classes. It references Bukkit types, so consumers must retain their own Spigot/Paper API compileOnly dependency.

Until a remote Maven repository is selected, build the public project and publish it locally:

gradlew.bat clean build publishToMavenLocal

A local consumer can then use:

repositories {
    mavenLocal()
}

dependencies {
    compileOnly("com.alexisleder:lederprotections-api:1.0.0")
}

Do not shade or relocate this artifact into LederFly.

Loading the API

Declare the optional relationship in the consuming plugin:

softdepend:
  - LederProtections

Load the registered service directly. Do not cast the main plugin class and do not use ProtectionRecord or other internal services.

import com.alexisleder.lederprotections.api.LederProtectionsApi;
import org.bukkit.Bukkit;

final LederProtectionsApi api = Bukkit.getServicesManager().load(LederProtectionsApi.class);

if (api == null) {
    // Continue in standalone mode.
    return;
}

if (!LederProtectionsApi.API_VERSION.equals(api.getApiVersion())) {
    getLogger().warning("Unsupported LederProtections API: " + api.getApiVersion());
}

All API methods must be called from the server's main thread. Methods that receive or return Bukkit Location objects make defensive copies where needed.

Protection identity and access

ProtectionSnapshot#id() is the persistent identity addons should store in their own data files. Never compare snapshots by object identity.

api.findProtectionAt(player.getLocation()).ifPresent(protection -> {
    final boolean member = api.canUseMemberFeatures(player, protection.id());
    final boolean manager = api.canManageSettings(player, protection.id());
});

getStoredRole(UUID, id) only evaluates persisted owner/co-owner/member/blocked data and is appropriate for offline identity decisions. getEffectiveRole(Player, id) adds only the global lederprotections.admin role. The technical lederprotections.bypass.rules permission never becomes public membership or ADMIN through this API.

canUseMemberFeatures fails closed for BLOCKED, even when the player also has lederprotections.admin. This explicit precedence is intended for sensitive addon mechanics such as flight. A blocked entry also takes precedence over an accidental simultaneous member entry.

canManageSettings follows the same administrative meaning used for flags: admins and owners are allowed; co-owners require the protection's existing canEditFlags setting.

Protection action checks

The API exposes silent checks for common external actions:

boolean breakAllowed = api.canBreakBlock(player, block.getLocation());
boolean placeAllowed = api.canPlaceBlock(player, destination);
boolean interactionAllowed = api.canInteractWithBlock(player, block.getLocation());
boolean containerAllowed = api.canOpenContainer(player, block.getLocation());

These checks reuse the configured rule engine, per-protection overrides and the configured bypass permission. Invalid inputs, offline players and unloaded chunks fail closed, and API queries never load a chunk as a side effect.

canInteractWithBlock detects supported doors, trapdoors, gates, buttons, levers, pressure plates and containers. A valid loaded material that LederProtections does not govern is allowed.

Container access

Plugins that inspect, remove, transfer, or sell items from physical containers must validate access before reading or mutating the inventory:

if (!api.canOpenContainer(player, clickedBlock.getLocation())) {
    // Cancel before changing item stacks or crediting the player.
    return;
}

sellContainerContents(player, clickedBlock);

The method uses the same material-specific rule as a normal inventory opening: chest-open, barrel-open, shulker-open, or container-open. It also honors per-protection overrides, disabled rules, and the configured rule-engine bypass. It is silent so the consuming plugin can use its own denial message.

For AxSellwands/AxIntegrations, map its OPEN_CONTAINER permission to this method and perform the check before collecting or zeroing the container's item stacks. Invalid locations and unsupported block materials fail closed; valid unprotected containers remain allowed.

Safe locations

The safe-location API reuses LederProtections' checks for a solid non-dangerous floor, two safe body blocks, world height, and containment of both feet and head.

import com.alexisleder.lederprotections.api.model.SafeLocationRequest;

final SafeLocationRequest request = new SafeLocationRequest(
        protection.id(),
        previousValidLocation,
        2,      // remain two blocks inside the horizontal edge
        4,      // bounded horizontal search
        6,      // bounded vertical search
        true    // fall back to the configured home and protection stone
);

api.findSafeLocation(request).ifPresent(player::teleport);

The public request limits inset/radius to 16 blocks and vertical range to 32 blocks. If no location can be proven safe, the result is empty. The API never writes blocks or teleports the player itself.

Every ProtectionSnapshot also carries an optional immutable teleport home. During ProtectionRemovedEvent, the ID-only overload returns empty because the repository entry no longer exists; use the snapshot overload instead:

@EventHandler
public void onProtectionRemoved(final ProtectionRemovedEvent event) {
    final ProtectionSnapshot removed = event.getProtection();
    final SafeLocationRequest request = new SafeLocationRequest(
            removed.id(),
            lastKnownSafeLocation,
            2,
            4,
            6,
            true
    );

    api.findSafeLocation(removed, request).ifPresent(this::landPlayerSafely);
}

This overload does not restore the protection or trust old block states. It uses the old bounds, stone and home only as search context, then validates the current world blocks again. It is also valid after the event has returned because the snapshot owns all required immutable data.

Lifecycle events

The following synchronous, non-cancelable Bukkit events are available:

  • ProtectionCreatedEvent
  • ProtectionChangedEvent
  • ProtectionRemovedEvent

Events are delivered on the next main-thread cycle after a successful persisted mutation. This allows the originating operation to update its spatial index and coalesces same-cycle rollbacks. A create followed by a successful rollback produces no public lifecycle event.

If an existing protection is updated and then removed in that same cycle, the removal event carries the last record actually deleted, including its final bounds and teleport home.

An administrative /lep sync also compares the previous in-memory state with the successfully reloaded file, so additions, removals, bounds, and access edits made on disk produce the same lifecycle events after the index rebuild.

ProtectionChangedEvent#getChanges() can contain ACCESS, BOUNDS, OWNER, CO_OWNER_PERMISSIONS, and other categories. Addons should react to the category they need and use the immutable before/after snapshots carried by the event.

@EventHandler
public void onProtectionChanged(final ProtectionChangedEvent event) {
    if (event.hasChange(ProtectionChangeType.ACCESS)
            || event.hasChange(ProtectionChangeType.BOUNDS)) {
        revalidateActiveUsers(event.getProtection().id());
    }
}

@EventHandler
public void onProtectionRemoved(final ProtectionRemovedEvent event) {
    deleteAddonSettings(event.getProtection().id());
}

Extending /p

Addons can register a subcommand without intercepting chat or PlayerCommandPreprocessEvent:

api.getCommandExtensions().register(this, "fly", new ProtectionCommandExtension() {
    @Override
    public boolean canExecute(final CommandSender sender) {
        return sender.hasPermission("lederfly.use");
    }

    @Override
    public void execute(
            final CommandSender sender,
            final String label,
            final List<String> arguments
    ) {
        openFlightMenu(sender);
    }
});

Arguments passed to the extension exclude fly, so /p fly buy receives ["buy"]. The label preserves the alias the user typed. Root suggestions and delegated tab completion respect canExecute.

Built-in LederProtections names are reserved, duplicate registrations fail, and all entries owned by an addon are removed automatically during its PluginDisableEvent. Registration and unregistration must occur on the main thread.

Standalone addons

For a plugin such as LederFly that also operates independently:

  1. Put every reference to LederProtections API classes in an integration package that is only instantiated after confirming the plugin and service are present.
  2. Treat a missing service as standalone only when LederProtections is genuinely absent. If the plugin is installed but its service is absent or incompatible, fail closed instead of granting world-wide standalone access.
  3. Store LederFly's own settings and balances in LederFly, keyed by ProtectionSnapshot#id() only when the integration is active.
  4. Listen for removal and access/bounds changes to clean settings and revalidate currently flying players.
  5. Register /p fly only while the API is available; keep LederFly's own root command available in standalone mode.

Clone this wiki locally