Skip to content

sun-mc-dev/ProfileRoles

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ProfileRoles

Advanced PlayerProfile API Integration Example

Java Paper PlayerProfile

An industrial-grade example plugin demonstrating professional integration with the PlayerProfile API, showcasing modern Minecraft plugin development practices using Java 21, Paper API, Adventure API, PacketEvents, and LuckPerms.


🎯 Purpose

This plugin serves as a comprehensive reference implementation for developers looking to integrate with the PlayerProfile API. It demonstrates:

  • Role-based Profile Management: Automatic profile templates with predefined items, permissions, and settings
  • LuckPerms Integration: Dynamic permission group switching based on active profiles
  • PacketEvents Usage: Enhanced visual effects during profile switches
  • Professional Code Patterns: Thread-safe operations, proper async handling, comprehensive error handling
  • Modern APIs: Adventure API for rich text components, Paper API for latest features
  • Extensive Documentation: Javadoc comments throughout for maintainability

✨ Features

Role Templates

The plugin includes 5 predefined role templates:

  1. Admin (Creative Mode)

    • Full server control
    • Command block and barrier items
    • LuckPerms group: admin
  2. Moderator (Survival Mode)

    • Teleport compass for player navigation
    • Rule book reference
    • LuckPerms group: moderator
  3. Builder (Creative Mode)

    • WorldEdit wand
    • Debug stick
    • 64 barrier blocks
    • LuckPerms group: builder
  4. Player (Survival Mode)

    • Default gameplay experience
    • Spawn compass
    • LuckPerms group: default
  5. VIP (Survival Mode)

    • Special perks
    • VIP exclusive items
    • 5 golden apples
    • LuckPerms group: vip

Advanced Features

  • Profile Context Tracking: Monitors player profile usage statistics
  • Smart Tab Completion: Context-aware suggestions for commands
  • Visual Effects: Enhanced titles and action bar messages during switches
  • Permission Integration: Automatic LuckPerms group synchronization
  • Packet Manipulation: Custom packet handling for smooth transitions
  • Thread Safety: All operations are thread-safe using concurrent collections
  • Async Operations: Non-blocking profile operations

📋 Requirements

  • Minecraft Version: 1.21.4+
  • Server Software: Paper or forks (Purpur, Pufferfish)
  • Java: 21+
  • Required Dependencies:
    • PlayerProfile v1.0.1+
    • PacketEvents 2.11.1+
  • Optional Dependencies:
    • LuckPerms (for permission context switching)

🚀 Installation

  1. Download the latest ProfileRoles-X.X.X.jar
  2. Ensure PlayerProfile and PacketEvents are installed
  3. Place the JAR in your plugins/ folder
  4. Restart your server
  5. Configure permissions (see below)

🎮 Commands

Command Description Permission
/profilerole create <role> Create a role-based profile profileroles.create.<role>
/profilerole switch <role> Switch to a role profile profileroles.use
/profilerole list List your profiles profileroles.use
/profilerole info [role] View role information profileroles.use
/profilerole stats View profile statistics profileroles.use
/profilerole templates List available templates profileroles.use

Aliases: /prole, /pr, /roles


🔐 Permissions

Basic Permissions

profileroles.use: true                 # Basic usage (default: true)
profileroles.admin: false              # Full admin access (default: op)

Role Creation Permissions

profileroles.create.admin: false       # Create admin profiles (default: op)
profileroles.create.moderator: false   # Create mod profiles (default: op)
profileroles.create.builder: false     # Create builder profiles (default: op)
profileroles.create.player: true       # Create player profiles (default: true)
profileroles.create.vip: false         # Create VIP profiles (default: false)

LuckPerms Configuration Example

# Allow all players to use basic features
lp group default permission set profileroles.use true
lp group default permission set profileroles.create.player true

# Allow VIP players to create VIP profiles
lp group vip permission set profileroles.create.vip true

# Staff can create mod profiles
lp group moderator permission set profileroles.create.moderator true

# Admins get everything
lp group admin permission set profileroles.admin true

🛠️ Developer Guide

Key Classes

ProfileRoles.java

The main plugin class containing:

  • Role template initialization
  • Event handling for profile switches
  • LuckPerms integration
  • PacketEvents listener setup

RoleCommand.java

Command handler providing:

  • All /profilerole subcommands
  • Intelligent tab completion
  • Rich text formatting with Adventure API

RoleTemplate

Builder pattern implementation for role definitions:

RoleTemplate template = RoleTemplate.builder()
    .name("custom")
    .displayName(Component.text("Custom Role", NamedTextColor.AQUA))
    .gameMode(GameMode.ADVENTURE)
    .luckPermsGroup("custom-group")
    .addItem(customItem)
    .build();

ProfileContext

Tracks player profile usage:

  • Current and previous profiles
  • Switch timestamp
  • Total switches count

Integration Examples

Creating Custom Templates

@Override
public void onEnable() {
    // ... existing code ...
    
    // Add custom template
    getRoleTemplates().put("custom", RoleTemplate.builder()
        .name("custom")
        .displayName(Component.text("Custom", NamedTextColor.AQUA))
        .gameMode(GameMode.ADVENTURE)
        .luckPermsGroup("custom-group")
        .addItem(createCustomItem())
        .build());
}

private ItemStack createCustomItem() {
    ItemStack item = new ItemStack(Material.NETHER_STAR);
    ItemMeta meta = item.getItemMeta();
    
    meta.displayName(Component.text("Special Item", NamedTextColor.LIGHT_PURPLE)
        .decoration(TextDecoration.ITALIC, false));
    
    meta.lore(List.of(
        Component.text("Custom functionality", NamedTextColor.GRAY)
            .decoration(TextDecoration.ITALIC, false)
    ));
    
    item.setItemMeta(meta);
    return item;
}

Listening to Profile Events

@EventHandler(priority = EventPriority.MONITOR)
public void onProfileSwitch(ProfileSwitchEvent event) {
    if (!event.isPost()) return;
    
    Player player = event.getPlayer();
    String toProfile = event.getToProfile();
    
    // Custom logic when player switches to specific profile
    if (toProfile.equals("admin")) {
        // Grant temporary fly permission
        player.setAllowFlight(true);
    }
}

Using ProfileAPI

private void handleCustomSwitch(Player player, String profileName) {
    ProfileAPI api = ProfileAPI.getInstance();
    
    // Check if profile exists
    if (!api.profileExists(player.getUniqueId(), profileName)) {
        player.sendMessage("Profile doesn't exist!");
        return;
    }
    
    // Initiate switch
    api.switchProfile(player, profileName).thenAccept(success -> {
        if (success) {
            // Apply custom effects
            getServer().getScheduler().runTask(this, () -> {
                player.playSound(player.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1.0f, 1.0f);
            });
        }
    });
}

🏗️ Architecture Highlights

Thread Safety

  • ConcurrentHashMap for role templates and player contexts
  • Proper synchronization for LuckPerms operations
  • Async ProfileAPI calls with sync callbacks for Bukkit API

Event-Driven Design

  • Pre-switch validation and preparation
  • Post-switch template application
  • Comprehensive event handling chain

Modern Java Patterns

  • Builder pattern for RoleTemplate
  • CompletableFuture for async operations
  • Stream API for collections processing
  • Record-like immutability patterns

Performance Optimizations

  • Lazy initialization of expensive resources
  • Cached template lookups
  • Efficient packet handling with PacketEvents
  • Minimal main thread blocking

📊 Technical Specifications

Code Metrics

  • Lines of Code: ~800 (excluding comments)
  • Javadoc Coverage: 100%
  • Thread Safety: Full concurrent support
  • Null Safety: @NotNull/@Nullable annotations throughout

Dependencies

<dependencies>
    <dependency>
        <groupId>io.papermc.paper</groupId>
        <artifactId>paper-api</artifactId>
        <version>1.21.4-R0.1-SNAPSHOT</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>com.github.sun-mc-dev</groupId>
        <artifactId>PlayerProfile</artifactId>
        <version>v1.0.1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>com.github.retrooper</groupId>
        <artifactId>packetevents-spigot</artifactId>
        <version>2.11.1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>net.luckperms</groupId>
        <artifactId>api</artifactId>
        <version>5.4</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

🤝 Contributing

This is an example/reference plugin, but contributions to improve the example are welcome!

Areas for Enhancement

  • Additional role templates
  • Configuration file support
  • Custom item NBT data
  • Economy integration examples
  • Database persistence examples

📜 License

This example plugin is provided as-is for educational and reference purposes. Feel free to use and modify for your own projects.


💡 Learning Points

What This Example Demonstrates

  1. Proper API Integration: Correct usage of ProfileAPI methods
  2. Event Handling: Pre- and post-event processing
  3. Async Programming: CompletableFuture best practices
  4. UI/UX Design: Rich text components with Adventure API
  5. Permission Management: LuckPerms integration patterns
  6. Packet Manipulation: PacketEvents usage for enhanced effects
  7. Code Organization: Professional plugin structure
  8. Documentation: Comprehensive Javadoc and comments
  9. Error Handling: Graceful failure recovery
  10. Performance: Thread-safe, efficient operations

Design Patterns Used

  • Builder Pattern: RoleTemplate.Builder
  • Singleton Pattern: Plugin instance access
  • Observer Pattern: Event system
  • Factory Pattern: Item creation methods
  • Strategy Pattern: Template application logic

📞 Support

For issues related to:


🙏 Acknowledgments

  • SunMC Development Team - PlayerProfile API
  • PaperMC Team - Modern Minecraft server software
  • Adventure Team - Modern text component library
  • Retrooper - PacketEvents library
  • Luck - LuckPerms permission system

Built with ❤️ as a reference for the Minecraft plugin development community

About

PlayerProfile API implmented plugin for reference

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Contributors 2

  •  
  •  

Languages